repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/tensorizer_loader/test_tensorizer.py
tests/model_executor/model_loader/tensorizer_loader/test_tensorizer.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import asyncio import gc import json import os import pathlib import subprocess import sys from typing import Any import pytest import torch import vllm.model_executor.model_loader.tensorizer from tests.utils import VLLM_PATH, RemoteOpenAIServer from vllm import LLM, SamplingParams from vllm.engine.arg_utils import EngineArgs from vllm.model_executor.model_loader.tensorizer import ( TensorizerConfig, TensorSerializer, is_vllm_tensorized, open_stream, tensorize_vllm_model, ) from vllm.model_executor.model_loader.tensorizer_loader import ( BLACKLISTED_TENSORIZER_ARGS, ) from vllm.utils.import_utils import PlaceholderModule from .conftest import DummyExecutor, assert_from_collective_rpc try: import tensorizer from tensorizer import EncryptionParams except ImportError: tensorizer = PlaceholderModule("tensorizer") # type: ignore[assignment] EncryptionParams = tensorizer.placeholder_attr("EncryptionParams") class TensorizerCaughtError(Exception): pass EXAMPLES_PATH = VLLM_PATH / "examples" pytest_plugins = ("pytest_asyncio",) prompts = [ "Hello, my name is", "The president of the United States is", "The capital of France is", "The future of AI is", ] # Create a sampling params object. sampling_params = SamplingParams(temperature=0.8, top_p=0.95, seed=0) def patch_init_and_catch_error(self, obj, method_name, expected_error: type[Exception]): original = getattr(obj, method_name, None) if original is None: raise ValueError("Method '{}' not found.".format(method_name)) def wrapper(*args, **kwargs): try: return original(*args, **kwargs) except expected_error as err: raise TensorizerCaughtError from err setattr(obj, method_name, wrapper) self.load_model() def assert_specific_tensorizer_error_is_raised( executor, obj: Any, method_name: str, expected_error: type[Exception], ): with pytest.raises(TensorizerCaughtError): executor.collective_rpc( patch_init_and_catch_error, args=( obj, method_name, expected_error, ), ) def is_curl_installed(): try: subprocess.check_call(["curl", "--version"]) return True except (subprocess.CalledProcessError, FileNotFoundError): return False def write_keyfile(keyfile_path: str): encryption_params = EncryptionParams.random() pathlib.Path(keyfile_path).parent.mkdir(parents=True, exist_ok=True) with open(keyfile_path, "wb") as f: f.write(encryption_params.key) @pytest.mark.skipif(not is_curl_installed(), reason="cURL is not installed") def test_deserialized_encrypted_vllm_model_has_same_outputs( model_ref, vllm_runner, tmp_path, model_path ): args = EngineArgs(model=model_ref) with vllm_runner(model_ref) as vllm_model: key_path = tmp_path / model_ref / "model.key" write_keyfile(key_path) outputs = vllm_model.generate(prompts, sampling_params) config_for_serializing = TensorizerConfig( tensorizer_uri=str(model_path), encryption_keyfile=str(key_path) ) tensorize_vllm_model(args, config_for_serializing) config_for_deserializing = TensorizerConfig( tensorizer_uri=str(model_path), encryption_keyfile=str(key_path) ) with vllm_runner( model_ref, load_format="tensorizer", model_loader_extra_config=config_for_deserializing, ) as loaded_vllm_model: # noqa: E501 deserialized_outputs = loaded_vllm_model.generate(prompts, sampling_params) # noqa: E501 assert outputs == deserialized_outputs def test_deserialized_hf_model_has_same_outputs( hf_runner, vllm_runner, tmp_path, model_ref, model_path ): with hf_runner(model_ref) as hf_model: max_tokens = 50 outputs = hf_model.generate_greedy(prompts, max_tokens=max_tokens) with open_stream(model_path, "wb+") as stream: serializer = TensorSerializer(stream) serializer.write_module(hf_model.model) with vllm_runner( model_ref, load_format="tensorizer", model_loader_extra_config=TensorizerConfig( tensorizer_uri=str(model_path), num_readers=1, ), ) as loaded_hf_model: deserialized_outputs = loaded_hf_model.generate_greedy( prompts, max_tokens=max_tokens ) assert outputs == deserialized_outputs def test_load_without_tensorizer_load_format(vllm_runner, capfd, model_ref): model = None try: model = vllm_runner( model_ref, model_loader_extra_config=TensorizerConfig(tensorizer_uri="test") ) pytest.fail("Expected RuntimeError for extra config keys") except RuntimeError: out, err = capfd.readouterr() combined_output = out + err assert ( "ValueError: Unexpected extra config keys for load format auto" ) in combined_output finally: del model gc.collect() torch.cuda.empty_cache() def test_raise_value_error_on_invalid_load_format(vllm_runner, capfd, model_ref): model = None try: model = vllm_runner( model_ref, load_format="safetensors", model_loader_extra_config=TensorizerConfig(tensorizer_uri="test"), ) pytest.fail("Expected RuntimeError for extra config keys") except RuntimeError: out, err = capfd.readouterr() combined_output = out + err assert ( "ValueError: Unexpected extra config keys for load format safetensors" ) in combined_output finally: del model gc.collect() torch.cuda.empty_cache() @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Requires 2 GPUs") def test_tensorizer_with_tp_path_without_template(vllm_runner, capfd): try: model_ref = "EleutherAI/pythia-1.4b" tensorized_path = f"s3://tensorized/{model_ref}/fp16/model.tensors" vllm_runner( model_ref, load_format="tensorizer", model_loader_extra_config=TensorizerConfig( tensorizer_uri=tensorized_path, num_readers=1, s3_endpoint="object.ord1.coreweave.com", ), tensor_parallel_size=2, disable_custom_all_reduce=True, ) except RuntimeError: out, err = capfd.readouterr() combined_output = out + err assert ( "ValueError: For a sharded model, tensorizer_uri " "should include a string format template like '%04d' " "to be formatted with the rank " "of the shard" ) in combined_output @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Requires 2 GPUs") def test_deserialized_encrypted_vllm_model_with_tp_has_same_outputs( vllm_runner, tmp_path ): model_ref = "EleutherAI/pythia-1.4b" # record outputs from un-sharded un-tensorized model with vllm_runner( model_ref, disable_custom_all_reduce=True, enforce_eager=True, ) as base_model: outputs = base_model.generate(prompts, sampling_params) # load model with two shards and serialize with encryption model_path = str(tmp_path / model_ref / "model-%02d.tensors") key_path = tmp_path / (model_ref + ".key") tensorizer_config = TensorizerConfig( tensorizer_uri=model_path, encryption_keyfile=str(key_path), ) tensorize_vllm_model( engine_args=EngineArgs( model=model_ref, tensor_parallel_size=2, disable_custom_all_reduce=True, enforce_eager=True, ), tensorizer_config=tensorizer_config, ) assert os.path.isfile(model_path % 0), "Serialization subprocess failed" assert os.path.isfile(model_path % 1), "Serialization subprocess failed" with vllm_runner( model_ref, tensor_parallel_size=2, load_format="tensorizer", disable_custom_all_reduce=True, enforce_eager=True, model_loader_extra_config=tensorizer_config, ) as loaded_vllm_model: deserialized_outputs = loaded_vllm_model.generate(prompts, sampling_params) assert outputs == deserialized_outputs @pytest.mark.flaky(reruns=3) def test_vllm_tensorized_model_has_same_outputs( model_ref, vllm_runner, tmp_path, model_path ): gc.collect() torch.cuda.empty_cache() config = TensorizerConfig(tensorizer_uri=str(model_path)) args = EngineArgs(model=model_ref) with vllm_runner(model_ref) as vllm_model: outputs = vllm_model.generate(prompts, sampling_params) tensorize_vllm_model(args, config) assert is_vllm_tensorized(config) with vllm_runner( model_ref, load_format="tensorizer", model_loader_extra_config=config ) as loaded_vllm_model: deserialized_outputs = loaded_vllm_model.generate(prompts, sampling_params) # noqa: E501 assert outputs == deserialized_outputs def test_load_with_just_model_tensors(just_serialize_model_tensors, model_ref): # For backwards compatibility, ensure Tensorizer can be still be loaded # for inference by passing the model reference name, not a local/S3 dir, # and the location of the model tensors model_dir = just_serialize_model_tensors extra_config = {"tensorizer_uri": f"{model_dir}/model.tensors"} ## Start OpenAI API server args = [ "--load-format", "tensorizer", "--model-loader-extra-config", json.dumps(extra_config), ] with RemoteOpenAIServer(model_ref, args): # This test only concerns itself with being able to load the model # and successfully initialize the server pass def test_assert_serialization_kwargs_passed_to_tensor_serializer(tmp_path): serialization_params = { "limit_cpu_concurrency": 2, } model_ref = "facebook/opt-125m" model_path = tmp_path / (model_ref + ".tensors") config = TensorizerConfig( tensorizer_uri=str(model_path), serialization_kwargs=serialization_params ) llm = LLM( model=model_ref, ) def serialization_test(self, *args, **kwargs): # This is performed in the ephemeral worker process, so monkey-patching # will actually work, and cleanup is guaranteed so don't # need to reset things original_dict = serialization_params to_compare = {} original = tensorizer.serialization.TensorSerializer.__init__ def tensorizer_serializer_wrapper(self, *args, **kwargs): nonlocal to_compare to_compare = kwargs.copy() return original(self, *args, **kwargs) tensorizer.serialization.TensorSerializer.__init__ = ( tensorizer_serializer_wrapper ) tensorizer_config = TensorizerConfig(**kwargs["tensorizer_config"]) self.save_tensorized_model( tensorizer_config=tensorizer_config, ) return to_compare | original_dict == to_compare kwargs = {"tensorizer_config": config.to_serializable()} assert assert_from_collective_rpc(llm, serialization_test, kwargs) def test_assert_deserialization_kwargs_passed_to_tensor_deserializer(tmp_path, capfd): deserialization_kwargs = { "num_readers": "bar", # illegal value } serialization_params = { "limit_cpu_concurrency": 2, } model_ref = "facebook/opt-125m" model_path = tmp_path / (model_ref + ".tensors") config = TensorizerConfig( tensorizer_uri=str(model_path), serialization_kwargs=serialization_params ) args = EngineArgs(model=model_ref) tensorize_vllm_model(args, config) loader_tc = TensorizerConfig( tensorizer_uri=str(model_path), deserialization_kwargs=deserialization_kwargs, ) engine_args = EngineArgs( model="facebook/opt-125m", load_format="tensorizer", model_loader_extra_config=loader_tc.to_serializable(), ) vllm_config = engine_args.create_engine_config() executor = DummyExecutor(vllm_config) assert_specific_tensorizer_error_is_raised( executor, tensorizer.serialization.TensorDeserializer, "__init__", TypeError, ) def test_assert_stream_kwargs_passed_to_tensor_deserializer(tmp_path, capfd): deserialization_kwargs = { "num_readers": 1, } serialization_params = { "limit_cpu_concurrency": 2, } model_ref = "facebook/opt-125m" model_path = tmp_path / (model_ref + ".tensors") config = TensorizerConfig( tensorizer_uri=str(model_path), serialization_kwargs=serialization_params ) args = EngineArgs(model=model_ref) tensorize_vllm_model(args, config) stream_kwargs = {"mode": "foo"} loader_tc = TensorizerConfig( tensorizer_uri=str(model_path), deserialization_kwargs=deserialization_kwargs, stream_kwargs=stream_kwargs, ) engine_args = EngineArgs( model="facebook/opt-125m", load_format="tensorizer", model_loader_extra_config=loader_tc.to_serializable(), ) vllm_config = engine_args.create_engine_config() executor = DummyExecutor(vllm_config) assert_specific_tensorizer_error_is_raised( executor, vllm.model_executor.model_loader.tensorizer, "open_stream", ValueError, ) @pytest.mark.asyncio async def test_serialize_and_serve_entrypoints(tmp_path): model_ref = "facebook/opt-125m" suffix = "test" try: result = subprocess.run( [ sys.executable, f"{VLLM_PATH}/examples/others/tensorize_vllm_model.py", "--model", model_ref, "serialize", "--serialized-directory", str(tmp_path), "--suffix", suffix, "--serialization-kwargs", '{"limit_cpu_concurrency": 4}', ], check=True, capture_output=True, text=True, ) except subprocess.CalledProcessError as e: print("Tensorizing failed.") print("STDOUT:\n", e.stdout) print("STDERR:\n", e.stderr) raise assert "Successfully serialized" in result.stdout # Next, try to serve with vllm serve model_uri = tmp_path / "vllm" / model_ref / suffix / "model.tensors" model_loader_extra_config = { "tensorizer_uri": str(model_uri), "stream_kwargs": { "force_http": False, }, "deserialization_kwargs": { "verify_hash": True, "num_readers": 8, }, } cmd = [ "-m", "vllm.entrypoints.cli.main", "serve", "--host", "localhost", "--load-format", "tensorizer", model_ref, "--model-loader-extra-config", json.dumps(model_loader_extra_config, indent=2), ] proc = await asyncio.create_subprocess_exec( sys.executable, *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, ) assert proc.stdout is not None fut = proc.stdout.readuntil(b"Application startup complete.") try: await asyncio.wait_for(fut, 180) except asyncio.TimeoutError: pytest.fail("Server did not start successfully") finally: proc.terminate() await proc.communicate() @pytest.mark.parametrize("illegal_value", BLACKLISTED_TENSORIZER_ARGS) def test_blacklisted_parameter_for_loading(tmp_path, vllm_runner, capfd, illegal_value): serialization_params = { "limit_cpu_concurrency": 2, } model_ref = "facebook/opt-125m" model_path = tmp_path / (model_ref + ".tensors") config = TensorizerConfig( tensorizer_uri=str(model_path), serialization_kwargs=serialization_params ) args = EngineArgs(model=model_ref) tensorize_vllm_model(args, config) loader_tc = {"tensorizer_uri": str(model_path), illegal_value: "foo"} try: vllm_runner( model_ref, load_format="tensorizer", model_loader_extra_config=loader_tc, ) except RuntimeError: out, err = capfd.readouterr() combined_output = out + err assert ( f"ValueError: {illegal_value} is not an allowed Tensorizer argument." ) in combined_output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/tensorizer_loader/__init__.py
tests/model_executor/model_loader/tensorizer_loader/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/runai_streamer_loader/conftest.py
tests/model_executor/model_loader/runai_streamer_loader/conftest.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.utils.network_utils import get_distributed_init_method, get_ip, get_open_port from vllm.v1.executor import UniProcExecutor from vllm.v1.worker.worker_base import WorkerWrapperBase # This is a dummy executor for patching in test_runai_model_streamer_s3.py. # We cannot use vllm_runner fixture here, because it spawns worker process. # The worker process reimports the patched entities, and the patch is not applied. class RunaiDummyExecutor(UniProcExecutor): def _init_executor(self) -> None: distributed_init_method = get_distributed_init_method(get_ip(), get_open_port()) local_rank = 0 rank = 0 is_driver_worker = True device_info = self.vllm_config.device_config.device.__str__().split(":") if len(device_info) > 1: local_rank = int(device_info[1]) worker_rpc_kwargs = dict( vllm_config=self.vllm_config, local_rank=local_rank, rank=rank, distributed_init_method=distributed_init_method, is_driver_worker=is_driver_worker, ) wrapper_kwargs = { "vllm_config": self.vllm_config, } self.driver_worker = WorkerWrapperBase(**wrapper_kwargs) self.collective_rpc("init_worker", args=([worker_rpc_kwargs],)) self.collective_rpc("init_device")
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/runai_streamer_loader/test_runai_utils.py
tests/model_executor/model_loader/runai_streamer_loader/test_runai_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import glob import hashlib import os import tempfile import huggingface_hub.constants from vllm.model_executor.model_loader.weight_utils import download_weights_from_hf from vllm.transformers_utils.runai_utils import ( ObjectStorageModel, is_runai_obj_uri, list_safetensors, ) def test_is_runai_obj_uri(): assert is_runai_obj_uri("gs://some-gcs-bucket/path") assert is_runai_obj_uri("s3://some-s3-bucket/path") assert not is_runai_obj_uri("nfs://some-nfs-path") def test_runai_list_safetensors_local(): with tempfile.TemporaryDirectory() as tmpdir: huggingface_hub.constants.HF_HUB_OFFLINE = False download_weights_from_hf( "openai-community/gpt2", allow_patterns=["*.safetensors", "*.json"], cache_dir=tmpdir, ) safetensors = glob.glob(f"{tmpdir}/**/*.safetensors", recursive=True) assert len(safetensors) > 0 parentdir = [os.path.dirname(safetensor) for safetensor in safetensors][0] files = list_safetensors(parentdir) assert len(safetensors) == len(files) def test_runai_pull_files_gcs(monkeypatch): monkeypatch.setenv("RUNAI_STREAMER_GCS_USE_ANONYMOUS_CREDENTIALS", "true") # Bypass default project lookup by setting GOOGLE_CLOUD_PROJECT monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "fake-project") filename = "LT08_L1GT_074061_20130309_20170505_01_T2_MTL.txt" gcs_bucket = "gs://gcp-public-data-landsat/LT08/01/074/061/LT08_L1GT_074061_20130309_20170505_01_T2/" gcs_url = f"{gcs_bucket}/{filename}" model = ObjectStorageModel(gcs_url) model.pull_files(gcs_bucket, allow_pattern=[f"*{filename}"]) # To re-generate / change URLs: # gsutil ls -L gs://<gcs-url> | grep "Hash (md5)" | tr -d ' ' \ # | cut -d":" -f2 | base64 -d | xxd -p expected_checksum = "f60dea775da1392434275b311b31a431" hasher = hashlib.new("md5") with open(os.path.join(model.dir, filename), "rb") as f: # Read the file in chunks to handle large files efficiently for chunk in iter(lambda: f.read(4096), b""): hasher.update(chunk) actual_checksum = hasher.hexdigest() assert actual_checksum == expected_checksum
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/runai_streamer_loader/__init__.py
tests/model_executor/model_loader/runai_streamer_loader/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_loader.py
tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_loader.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm import SamplingParams from vllm.config.load import LoadConfig from vllm.model_executor.model_loader import get_model_loader load_format = "runai_streamer" test_model = "openai-community/gpt2" # TODO(amacaskill): Replace with a GKE owned GCS bucket. test_gcs_model = "gs://vertex-model-garden-public-us/codegemma/codegemma-2b/" prompts = [ "Hello, my name is", "The president of the United States is", "The capital of France is", "The future of AI is", ] # Create a sampling params object. sampling_params = SamplingParams(temperature=0.8, top_p=0.95, seed=0) def get_runai_model_loader(): load_config = LoadConfig(load_format=load_format) return get_model_loader(load_config) def test_get_model_loader_with_runai_flag(): model_loader = get_runai_model_loader() assert model_loader.__class__.__name__ == "RunaiModelStreamerLoader" def test_runai_model_loader_download_files(vllm_runner): with vllm_runner(test_model, load_format=load_format) as llm: deserialized_outputs = llm.generate(prompts, sampling_params) assert deserialized_outputs def test_runai_model_loader_download_files_gcs( vllm_runner, monkeypatch: pytest.MonkeyPatch ): monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "fake-project") monkeypatch.setenv("RUNAI_STREAMER_GCS_USE_ANONYMOUS_CREDENTIALS", "true") monkeypatch.setenv( "CLOUD_STORAGE_EMULATOR_ENDPOINT", "https://storage.googleapis.com" ) with vllm_runner(test_gcs_model, load_format=load_format) as llm: deserialized_outputs = llm.generate(prompts, sampling_params) assert deserialized_outputs
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_s3.py
tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_s3.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from pathlib import Path from huggingface_hub import snapshot_download from runai_model_streamer.safetensors_streamer.streamer_mock import StreamerPatcher from vllm.engine.arg_utils import EngineArgs from .conftest import RunaiDummyExecutor load_format = "runai_streamer" test_model = "openai-community/gpt2" def test_runai_model_loader_download_files_s3_mocked_with_patch( vllm_runner, tmp_path: Path, monkeypatch, ): patcher = StreamerPatcher(str(tmp_path)) test_mock_s3_model = "s3://my-mock-bucket/gpt2/" # Download model from HF mock_model_dir = f"{tmp_path}/gpt2" snapshot_download(repo_id=test_model, local_dir=mock_model_dir) monkeypatch.setattr( "vllm.transformers_utils.runai_utils.runai_list_safetensors", patcher.shim_list_safetensors, ) monkeypatch.setattr( "vllm.transformers_utils.runai_utils.runai_pull_files", patcher.shim_pull_files, ) monkeypatch.setattr( "vllm.model_executor.model_loader.weight_utils.SafetensorsStreamer", patcher.create_mock_streamer, ) engine_args = EngineArgs( model=test_mock_s3_model, load_format=load_format, tensor_parallel_size=1, ) vllm_config = engine_args.create_engine_config() executor = RunaiDummyExecutor(vllm_config) executor.driver_worker.load_model()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/model_executor/model_loader/runai_streamer_loader/test_weight_utils.py
tests/model_executor/model_loader/runai_streamer_loader/test_weight_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import glob import tempfile import huggingface_hub.constants import torch from vllm.model_executor.model_loader.weight_utils import ( download_weights_from_hf, runai_safetensors_weights_iterator, safetensors_weights_iterator, ) def test_runai_model_loader(): with tempfile.TemporaryDirectory() as tmpdir: huggingface_hub.constants.HF_HUB_OFFLINE = False download_weights_from_hf( "openai-community/gpt2", allow_patterns=["*.safetensors"], cache_dir=tmpdir ) safetensors = glob.glob(f"{tmpdir}/**/*.safetensors", recursive=True) assert len(safetensors) > 0 runai_model_streamer_tensors = {} hf_safetensors_tensors = {} for name, tensor in runai_safetensors_weights_iterator(safetensors, True): runai_model_streamer_tensors[name] = tensor for name, tensor in safetensors_weights_iterator(safetensors, True): hf_safetensors_tensors[name] = tensor assert len(runai_model_streamer_tensors) == len(hf_safetensors_tensors) for name, runai_tensor in runai_model_streamer_tensors.items(): assert runai_tensor.dtype == hf_safetensors_tensors[name].dtype assert runai_tensor.shape == hf_safetensors_tensors[name].shape assert torch.all(runai_tensor.eq(hf_safetensors_tensors[name])) if __name__ == "__main__": test_runai_model_loader()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/config/test_model_arch_config.py
tests/config/test_model_arch_config.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Tests for ModelArchitectureConfig and its integration with ModelConfig.""" import json from pathlib import Path import pytest from vllm.config import ModelConfig, ParallelConfig, SpeculativeConfig from vllm.transformers_utils.model_arch_config_convertor import ( ModelArchConfigConvertorBase, ) BASE_TRUST_REMOTE_CODE_MODELS = { "nvidia/Llama-3_3-Nemotron-Super-49B-v1", "XiaomiMiMo/MiMo-7B-RL", # Excluded: Not available online right now # "FreedomIntelligence/openPangu-Ultra-MoE-718B-V1.1", "meituan-longcat/LongCat-Flash-Chat", } BASE_MODELS_TO_TEST = [ "state-spaces/mamba-130m-hf", "mistralai/Mamba-Codestral-7B-v0.1", # Excluded: terratorch/torchgeo version mismatch in CPU CI environment # (NonGeoDataset import error). Tested in model initialization tests. # "ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL-Sen1Floods11", "Zyphra/Zamba2-7B-instruct", # FIXME: mosaicml/mpt-7b has been deleted # "mosaicml/mpt-7b", # FIXME: databricks/dbrx-instruct has been deleted # "databricks/dbrx-instruct", "tiiuae/falcon-7b", "tiiuae/falcon-40b", "luccafong/deepseek_mtp_main_random", "Qwen/Qwen3-Next-80B-A3B-Instruct", "tiny-random/qwen3-next-moe", "zai-org/GLM-4.5", "baidu/ERNIE-4.5-21B-A3B-PT", # Models using base convertor "lmsys/gpt-oss-20b-bf16", "deepseek-ai/DeepSeek-V3.2-Exp", "meta-llama/Llama-4-Scout-17B-16E-Instruct", ] + list(BASE_TRUST_REMOTE_CODE_MODELS) # (target_model, draft_model, trust_remote_code) SPECULATIVE_MODELS = [ ("JackFram/llama-68m", "abhigoyal/vllm-medusa-llama-68m-random", False), ("luccafong/deepseek_mtp_main_random", "luccafong/deepseek_mtp_draft_random", True), ("eagle618/deepseek-v3-random", "eagle618/eagle-deepseek-v3-random", True), ("meta-llama/Meta-Llama-3-8B-Instruct", "yuhuili/EAGLE-LLaMA3-Instruct-8B", True), ("meta-llama/Llama-3.1-8B-Instruct", "yuhuili/EAGLE3-LLaMA3.1-Instruct-8B", True), ] def _load_groundtruth(filename: str) -> dict: """Load groundtruth JSON from the test directory.""" groundtruth_path = Path(__file__).parent / filename with open(groundtruth_path) as f: return json.load(f) def _assert_model_arch_config( model_config, expected: dict, check_head_size: bool = True ): """Assert model_arch_config matches expected values.""" model_arch_config = model_config.model_arch_config assert model_arch_config.architectures == expected["architectures"] assert model_arch_config.model_type == expected["model_type"] assert model_arch_config.text_model_type == expected["text_model_type"] assert model_arch_config.hidden_size == expected["hidden_size"] assert ( model_arch_config.total_num_hidden_layers == expected["total_num_hidden_layers"] ) assert ( model_arch_config.total_num_attention_heads == expected["total_num_attention_heads"] ) assert model_arch_config.vocab_size == expected["vocab_size"] assert model_arch_config.total_num_kv_heads == expected["total_num_kv_heads"] assert model_arch_config.num_experts == expected["num_experts"] assert model_arch_config.is_deepseek_mla == expected["is_deepseek_mla"] torch_dtype = ModelArchConfigConvertorBase.get_torch_dtype( model_config.hf_config, model_config.model, revision=model_config.revision ) assert str(torch_dtype) == expected["dtype"] if check_head_size: assert model_arch_config.head_size == expected["head_size"] def _assert_model_config_methods( model_config, expected: dict, check_head_size: bool = True ): """Assert model_config methods return expected values.""" assert model_config.architectures == expected["architectures"] assert model_config.get_vocab_size() == expected["vocab_size"] assert model_config.get_hidden_size() == expected["hidden_size"] assert model_config.get_total_num_kv_heads() == expected["total_num_kv_heads"] assert model_config.get_num_experts() == expected["num_experts"] assert ( model_config.get_total_num_hidden_layers() == expected["total_num_hidden_layers"] ) if check_head_size: assert model_config.get_head_size() == expected["head_size"] @pytest.mark.parametrize("model", BASE_MODELS_TO_TEST) def test_base_model_arch_config(model: str): """Test model architecture config for base models.""" groundtruth = _load_groundtruth("base_model_arch_groundtruth.json") expected = groundtruth[model] model_config = ModelConfig( model, trust_remote_code=model in BASE_TRUST_REMOTE_CODE_MODELS ) _assert_model_arch_config(model_config, expected) _assert_model_config_methods(model_config, expected) @pytest.mark.parametrize( "target_model,draft_model,trust_remote_code", SPECULATIVE_MODELS ) def test_draft_model_arch_config( target_model: str, draft_model: str, trust_remote_code: bool ): """Test model architecture config for draft/speculative models.""" groundtruth = _load_groundtruth("draft_model_arch_groundtruth.json") expected = groundtruth[draft_model] target_model_config = ModelConfig(target_model, trust_remote_code=trust_remote_code) speculative_config = SpeculativeConfig( model=draft_model, num_speculative_tokens=1, target_model_config=target_model_config, target_parallel_config=ParallelConfig(), ) model_config = speculative_config.draft_model_config # For medusa models, head_size may cause division by zero before # model_arch_config was introduced, so we conditionally check it check_head_size = isinstance(expected["head_size"], int) _assert_model_arch_config(model_config, expected, check_head_size=check_head_size) _assert_model_config_methods( model_config, expected, check_head_size=check_head_size )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/config/test_config_generation.py
tests/config/test_config_generation.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.engine.arg_utils import EngineArgs from vllm.model_executor.layers.quantization.quark.utils import deep_compare def test_cuda_empty_vs_unset_configs(monkeypatch: pytest.MonkeyPatch): """Test that configs created with normal (untouched) CUDA_VISIBLE_DEVICES and CUDA_VISIBLE_DEVICES="" are equivalent. This ensures consistent behavior regardless of whether GPU visibility is disabled via empty string or left in its normal state. """ def create_config(): engine_args = EngineArgs( model="deepseek-ai/DeepSeek-V2-Lite", trust_remote_code=True ) return engine_args.create_engine_config() # Create config with CUDA_VISIBLE_DEVICES set normally normal_config = create_config() # Create config with CUDA_VISIBLE_DEVICES="" with monkeypatch.context() as m: m.setenv("CUDA_VISIBLE_DEVICES", "") empty_config = create_config() normal_config_dict = vars(normal_config) empty_config_dict = vars(empty_config) # Remove instance_id before comparison as it's expected to be different normal_config_dict.pop("instance_id", None) empty_config_dict.pop("instance_id", None) assert deep_compare(normal_config_dict, empty_config_dict), ( 'Configs with normal CUDA_VISIBLE_DEVICES and CUDA_VISIBLE_DEVICES=""' " should be equivalent" ) def test_ray_runtime_env(monkeypatch: pytest.MonkeyPatch): # In testing, this method needs to be nested inside as ray does not # see the test module. def create_config(): engine_args = EngineArgs( model="deepseek-ai/DeepSeek-V2-Lite", trust_remote_code=True ) return engine_args.create_engine_config() config = create_config() parallel_config = config.parallel_config assert parallel_config.ray_runtime_env is None import ray ray.init() runtime_env = { "env_vars": { "TEST_ENV_VAR": "test_value", }, } config_ref = ray.remote(create_config).options(runtime_env=runtime_env).remote() config = ray.get(config_ref) parallel_config = config.parallel_config assert parallel_config.ray_runtime_env is not None assert ( parallel_config.ray_runtime_env.env_vars().get("TEST_ENV_VAR") == "test_value" ) ray.shutdown()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/config/test_mp_reducer.py
tests/config/test_mp_reducer.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import sys from unittest.mock import patch from vllm.config import VllmConfig from vllm.engine.arg_utils import AsyncEngineArgs from vllm.v1.engine.async_llm import AsyncLLM def test_mp_reducer(): """ Test that _reduce_config reducer is registered when AsyncLLM is instantiated without transformers_modules. This is a regression test for https://github.com/vllm-project/vllm/pull/18640. """ # Ensure transformers_modules is not in sys.modules if "transformers_modules" in sys.modules: del sys.modules["transformers_modules"] with patch("multiprocessing.reducer.register") as mock_register: engine_args = AsyncEngineArgs( model="facebook/opt-125m", max_model_len=32, gpu_memory_utilization=0.1, disable_log_stats=True, ) async_llm = AsyncLLM.from_engine_args( engine_args, start_engine_loop=False, ) assert mock_register.called, ( "multiprocessing.reducer.register should have been called" ) vllm_config_registered = False for call_args in mock_register.call_args_list: # Verify that a reducer for VllmConfig was registered if len(call_args[0]) >= 2 and call_args[0][0] == VllmConfig: vllm_config_registered = True reducer_func = call_args[0][1] assert callable(reducer_func), "Reducer function should be callable" break assert vllm_config_registered, ( "VllmConfig should have been registered to multiprocessing.reducer" ) async_llm.shutdown()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/config/test_config_utils.py
tests/config/test_config_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from enum import Enum import pytest from vllm.config.utils import get_hash_factors, hash_factors, normalize_value # Helpers def endswith_fqname(obj, suffix: str) -> bool: # normalize_value(type) returns fully-qualified name # Compare suffix to avoid brittle import paths. out = normalize_value(obj) return isinstance(out, str) and out.endswith(suffix) def expected_path(p_str: str = ".") -> str: import pathlib p = pathlib.Path(p_str) return p.expanduser().resolve().as_posix() # Minimal dataclass to test get_hash_factors. # Avoid importing heavy vLLM configs. @dataclass class SimpleConfig: a: object b: object | None = None class DummyLogprobsMode(Enum): RAW_LOGITS = "raw_logits" def test_hash_factors_deterministic(): """Test that hash_factors produces consistent SHA-256 hashes""" factors = {"a": 1, "b": "test"} hash1 = hash_factors(factors) hash2 = hash_factors(factors) assert hash1 == hash2 # Dict key insertion order should not affect the hash. factors_reordered = {"b": "test", "a": 1} assert hash_factors(factors_reordered) == hash1 assert len(hash1) == 64 assert all(c in "0123456789abcdef" for c in hash1) @pytest.mark.parametrize( "inp, expected", [ (None, None), (True, True), (1, 1), (1.0, 1.0), ("x", "x"), (b"ab", "6162"), (bytearray(b"ab"), "6162"), ([1, 2], (1, 2)), ({"b": 2, "a": 1}, (("a", 1), ("b", 2))), ], ) def test_normalize_value_matrix(inp, expected): """Parametric input→expected normalization table.""" assert normalize_value(inp) == expected def test_normalize_value_enum(): # Enums normalize to (module.QualName, value). # DummyLogprobsMode uses a string payload. out = normalize_value(DummyLogprobsMode.RAW_LOGITS) assert isinstance(out, tuple) assert out[0].endswith("DummyLogprobsMode") # Expect string payload 'raw_logits'. assert out[1] == "raw_logits" def test_normalize_value_set_order_insensitive(): # Sets are unordered; normalize_value sorts elements for determinism. assert normalize_value({3, 1, 2}) == normalize_value({1, 2, 3}) def test_normalize_value_path_normalization(): from pathlib import Path # local import to avoid global dependency # Paths expand/resolve to absolute strings. # Stabilizes hashing across working dirs. assert normalize_value(Path(".")) == expected_path(".") def test_normalize_value_uuid_and_to_json(): # Objects may normalize via uuid() or to_json_string(). class HasUUID: def uuid(self): return "test-uuid" class ToJson: def to_json_string(self): return '{"x":1}' assert normalize_value(HasUUID()) == "test-uuid" assert normalize_value(ToJson()) == '{"x":1}' @pytest.mark.parametrize( "bad", [ (lambda x: x), (type("CallableInstance", (), {"__call__": lambda self: 0}))(), (lambda: (lambda: 0))(), # nested function instance ], ) def test_error_cases(bad): """Inputs expected to raise TypeError.""" # Reject functions/lambdas/callable instances # to avoid under-hashing. with pytest.raises(TypeError): normalize_value(bad) def test_enum_vs_int_disambiguation(): # int stays primitive nf_int = normalize_value(1) assert nf_int == 1 # enum becomes ("module.QualName", value) nf_enum = normalize_value(DummyLogprobsMode.RAW_LOGITS) assert isinstance(nf_enum, tuple) and len(nf_enum) == 2 enum_type, enum_val = nf_enum assert enum_type.endswith(".DummyLogprobsMode") assert enum_val == "raw_logits" # Build factor dicts from configs with int vs enum f_int = get_hash_factors(SimpleConfig(1), set()) f_enum = get_hash_factors(SimpleConfig(DummyLogprobsMode.RAW_LOGITS), set()) # The int case remains a primitive value assert f_int["a"] == 1 # The enum case becomes a tagged tuple ("module.QualName", "raw_logits") assert isinstance(f_enum["a"], tuple) and f_enum["a"][1] == "raw_logits" # Factor dicts must differ so we don't collide primitives with Enums. assert f_int != f_enum # Hash digests must differ correspondingly assert hash_factors(f_int) != hash_factors(f_enum) # Hash functions produce stable hex strings h_int = hash_factors(f_int) h_enum = hash_factors(f_enum) assert isinstance(h_int, str) and len(h_int) == 64 assert isinstance(h_enum, str) and len(h_enum) == 64 def test_classes_are_types(): """Types normalize to FQNs; include real vLLM types.""" # Only classes allowed; functions/lambdas are rejected. # Canonical form is the fully-qualified name. assert isinstance(normalize_value(str), str) class LocalDummy: pass assert endswith_fqname(LocalDummy, ".LocalDummy")
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/config/test_multimodal_config.py
tests/config/test_multimodal_config.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.attention.backends.registry import AttentionBackendEnum from vllm.config.multimodal import MultiModalConfig def test_mm_encoder_attn_backend_str_conversion(): config = MultiModalConfig(mm_encoder_attn_backend="FLASH_ATTN") assert config.mm_encoder_attn_backend == AttentionBackendEnum.FLASH_ATTN def test_mm_encoder_attn_backend_invalid(): with pytest.raises(ValueError): MultiModalConfig(mm_encoder_attn_backend="not_a_backend") def test_mm_encoder_attn_backend_hash_updates(): base_hash = MultiModalConfig().compute_hash() overridden_hash = MultiModalConfig( mm_encoder_attn_backend=AttentionBackendEnum.FLASH_ATTN ).compute_hash() assert base_hash != overridden_hash
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/plugins_tests/test_io_processor_plugins.py
tests/plugins_tests/test_io_processor_plugins.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import base64 import pytest import requests from tests.utils import RemoteOpenAIServer from vllm.config import VllmConfig from vllm.entrypoints.pooling.pooling.protocol import IOProcessorResponse from vllm.plugins.io_processors import get_io_processor MODEL_NAME = "ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL-Sen1Floods11" image_url = "https://huggingface.co/christian-pinto/Prithvi-EO-2.0-300M-TL-VLLM/resolve/main/valencia_example_2024-10-26.tiff" # noqa: E501 def test_loading_missing_plugin(): vllm_config = VllmConfig() with pytest.raises(ValueError): get_io_processor(vllm_config, "wrong_plugin") @pytest.fixture(scope="function") def server(): args = [ "--runner", "pooling", "--enforce-eager", "--trust-remote-code", "--skip-tokenizer-init", # Limit the maximum number of parallel requests # to avoid the model going OOM in CI. "--max-num-seqs", "32", "--io-processor-plugin", "prithvi_to_tiff", "--model-impl", "terratorch", "--enable-mm-embeds", ] with RemoteOpenAIServer(MODEL_NAME, args) as remote_server: yield remote_server @pytest.mark.asyncio @pytest.mark.parametrize("model_name", [MODEL_NAME]) async def test_prithvi_mae_plugin_online( server: RemoteOpenAIServer, model_name: str, ): request_payload_url = { "data": { "data": image_url, "data_format": "url", "image_format": "tiff", "out_data_format": "b64_json", }, "priority": 0, "model": model_name, "softmax": False, } ret = requests.post( server.url_for("pooling"), json=request_payload_url, ) response = ret.json() # verify the request response is in the correct format assert (parsed_response := IOProcessorResponse(**response)) # verify the output is formatted as expected for this plugin plugin_data = parsed_response.data assert all( plugin_data.get(attr) for attr in ["type", "format", "data", "request_id"] ) # We just check that the output is a valid base64 string. # Raises an exception and fails the test if the string is corrupted. base64.b64decode(plugin_data["data"]) @pytest.mark.parametrize("model_name", [MODEL_NAME]) def test_prithvi_mae_plugin_offline(vllm_runner, model_name: str): img_prompt = dict( data=image_url, data_format="url", image_format="tiff", out_data_format="b64_json", ) with vllm_runner( model_name, runner="pooling", skip_tokenizer_init=True, enable_mm_embeds=True, trust_remote_code=True, enforce_eager=True, # Limit the maximum number of parallel requests # to avoid the model going OOM in CI. max_num_seqs=1, model_impl="terratorch", io_processor_plugin="prithvi_to_tiff", ) as llm_runner: pooler_output = llm_runner.get_llm().encode(img_prompt, pooling_task="plugin") output = pooler_output[0].outputs # verify the output is formatted as expected for this plugin assert all( hasattr(output, attr) for attr in ["type", "format", "data", "request_id"] ) # We just check that the output is a valid base64 string. # Raises an exception and fails the test if the string is corrupted. base64.b64decode(output.data)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/plugins_tests/test_stats_logger_plugins.py
tests/plugins_tests/test_stats_logger_plugins.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from dummy_stat_logger.dummy_stat_logger import DummyStatLogger from vllm.config import VllmConfig from vllm.engine.arg_utils import AsyncEngineArgs from vllm.v1.engine.async_llm import AsyncLLM from vllm.v1.metrics.loggers import load_stat_logger_plugin_factories def test_stat_logger_plugin_is_discovered(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: m.setenv("VLLM_PLUGINS", "dummy_stat_logger") factories = load_stat_logger_plugin_factories() assert len(factories) == 1, f"Expected 1 factory, got {len(factories)}" assert factories[0] is DummyStatLogger, ( f"Expected DummyStatLogger class, got {factories[0]}" ) # instantiate and confirm the right type vllm_config = VllmConfig() instance = factories[0](vllm_config) assert isinstance(instance, DummyStatLogger) def test_no_plugins_loaded_if_env_empty(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: m.setenv("VLLM_PLUGINS", "") factories = load_stat_logger_plugin_factories() assert factories == [] def test_invalid_stat_logger_plugin_raises(monkeypatch: pytest.MonkeyPatch): def fake_plugin_loader(group: str): assert group == "vllm.stat_logger_plugins" return {"bad": object()} with monkeypatch.context() as m: m.setattr( "vllm.v1.metrics.loggers.load_plugins_by_group", fake_plugin_loader, ) with pytest.raises( TypeError, match="Stat logger plugin 'bad' must be a subclass of StatLoggerBase", ): load_stat_logger_plugin_factories() @pytest.mark.asyncio async def test_stat_logger_plugin_integration_with_engine( monkeypatch: pytest.MonkeyPatch, ): with monkeypatch.context() as m: m.setenv("VLLM_PLUGINS", "dummy_stat_logger") engine_args = AsyncEngineArgs( model="facebook/opt-125m", enforce_eager=True, # reduce test time disable_log_stats=True, # disable default loggers ) engine = AsyncLLM.from_engine_args(engine_args=engine_args) assert len(engine.logger_manager.stat_loggers) == 2 assert len(engine.logger_manager.stat_loggers[0].per_engine_stat_loggers) == 1 assert isinstance( engine.logger_manager.stat_loggers[0].per_engine_stat_loggers[0], DummyStatLogger, ) engine.shutdown()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/plugins_tests/test_scheduler_plugins.py
tests/plugins_tests/test_scheduler_plugins.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.engine.arg_utils import EngineArgs from vllm.sampling_params import SamplingParams from vllm.v1.core.sched.scheduler import Scheduler from vllm.v1.engine.llm_engine import LLMEngine class DummyV1Scheduler(Scheduler): def schedule(self): raise Exception("Exception raised by DummyV1Scheduler") def test_scheduler_plugins_v1(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: # Explicitly turn off engine multiprocessing so # that the scheduler runs in this process m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0") with pytest.raises(Exception) as exception_info: engine_args = EngineArgs( model="facebook/opt-125m", enforce_eager=True, # reduce test time scheduler_cls=DummyV1Scheduler, ) engine = LLMEngine.from_engine_args(engine_args=engine_args) sampling_params = SamplingParams(max_tokens=1) engine.add_request("0", "foo", sampling_params) engine.step() assert str(exception_info.value) == "Exception raised by DummyV1Scheduler"
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/plugins_tests/test_platform_plugins.py
tests/plugins_tests/test_platform_plugins.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.plugins import load_general_plugins def test_platform_plugins(): # simulate workload by running an example import runpy current_file = __file__ import os example_file = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(current_file))), "examples", "offline_inference/basic/basic.py", ) runpy.run_path(example_file) # check if the plugin is loaded correctly from vllm.platforms import _init_trace, current_platform assert current_platform.device_name == "DummyDevice", ( f"Expected DummyDevice, got {current_platform.device_name}, " "possibly because current_platform is imported before the plugin" f" is loaded. The first import:\n{_init_trace}" ) def test_oot_custom_op(monkeypatch: pytest.MonkeyPatch): # simulate workload by running an example load_general_plugins() from vllm.model_executor.layers.rotary_embedding import RotaryEmbedding layer = RotaryEmbedding(16, 16, 16, 16, True, torch.float16) assert layer.__class__.__name__ == "DummyRotaryEmbedding", ( f"Expected DummyRotaryEmbedding, got {layer.__class__.__name__}, " "possibly because the custom op is not registered correctly." ) assert hasattr(layer, "addition_config"), ( "Expected DummyRotaryEmbedding to have an 'addition_config' attribute, " "which is set by the custom op." )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/engine/test_short_mm_context.py
tests/engine/test_short_mm_context.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from ..conftest import IMAGE_ASSETS HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts( { "stop_sign": "USER: <image>\nWhat's the content of the image?\nASSISTANT:", "cherry_blossom": "USER: <image>\nWhat is the season?\nASSISTANT:", } ) models = ["llava-hf/llava-1.5-7b-hf"] @pytest.mark.parametrize("model", models) def test_context_length_too_short(vllm_runner, image_assets, model): images = [asset.pil_image for asset in image_assets] with pytest.raises(ValueError, match="longer than the maximum model length"): vllm_model = vllm_runner( model, max_model_len=128, # LLaVA has a feature size of 576 enforce_eager=True, load_format="dummy", ) with vllm_model: vllm_model.generate_greedy( [HF_IMAGE_PROMPTS[0]], max_tokens=1, images=[images[0]] )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/engine/test_arg_utils.py
tests/engine/test_arg_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import json from argparse import ArgumentError from contextlib import nullcontext from dataclasses import dataclass, field from typing import Annotated, Literal import pytest from vllm.config import AttentionConfig, CompilationConfig, config from vllm.engine.arg_utils import ( EngineArgs, contains_type, get_kwargs, get_type, get_type_hints, is_not_builtin, is_type, literal_to_kwargs, optional_type, parse_type, ) from vllm.utils.argparse_utils import FlexibleArgumentParser @pytest.mark.parametrize( ("type", "value", "expected"), [ (int, "42", 42), (float, "3.14", 3.14), (str, "Hello World!", "Hello World!"), (json.loads, '{"foo":1,"bar":2}', {"foo": 1, "bar": 2}), ], ) def test_parse_type(type, value, expected): parse_type_func = parse_type(type) assert parse_type_func(value) == expected def test_optional_type(): optional_type_func = optional_type(int) assert optional_type_func("None") is None assert optional_type_func("42") == 42 @pytest.mark.parametrize( ("type_hint", "type", "expected"), [ (int, int, True), (int, float, False), (list[int], list, True), (list[int], tuple, False), (Literal[0, 1], Literal, True), ], ) def test_is_type(type_hint, type, expected): assert is_type(type_hint, type) == expected @pytest.mark.parametrize( ("type_hints", "type", "expected"), [ ({float, int}, int, True), ({int, tuple}, int, True), ({int, tuple[int]}, int, True), ({int, tuple[int, ...]}, int, True), ({int, tuple[int]}, float, False), ({int, tuple[int, ...]}, float, False), ({str, Literal["x", "y"]}, Literal, True), ], ) def test_contains_type(type_hints, type, expected): assert contains_type(type_hints, type) == expected @pytest.mark.parametrize( ("type_hints", "type", "expected"), [ ({int, float}, int, int), ({int, float}, str, None), ({str, Literal["x", "y"]}, Literal, Literal["x", "y"]), ], ) def test_get_type(type_hints, type, expected): assert get_type(type_hints, type) == expected @pytest.mark.parametrize( ("type_hints", "expected"), [ ({Literal[1, 2]}, {"type": int, "choices": [1, 2]}), ({str, Literal["x", "y"]}, {"type": str, "metavar": ["x", "y"]}), ({Literal[1, "a"]}, Exception), ], ) def test_literal_to_kwargs(type_hints, expected): context = nullcontext() if expected is Exception: context = pytest.raises(expected) with context: assert literal_to_kwargs(type_hints) == expected @config @dataclass class NestedConfig: field: int = 1 """field""" @config @dataclass class DummyConfig: regular_bool: bool = True """Regular bool with default True""" optional_bool: bool | None = None """Optional bool with default None""" optional_literal: Literal["x", "y"] | None = None """Optional literal with default None""" tuple_n: tuple[int, ...] = field(default_factory=lambda: (1, 2, 3)) """Tuple with variable length""" tuple_2: tuple[int, int] = field(default_factory=lambda: (1, 2)) """Tuple with fixed length""" list_n: list[int] = field(default_factory=lambda: [1, 2, 3]) """List with variable length""" list_literal: list[Literal[1, 2]] = field(default_factory=list) """List with literal choices""" list_union: list[str | type[object]] = field(default_factory=list) """List with union type""" set_n: set[int] = field(default_factory=lambda: {1, 2, 3}) """Set with variable length""" literal_literal: Literal[Literal[1], Literal[2]] = 1 """Literal of literals with default 1""" json_tip: dict = field(default_factory=dict) """Dict which will be JSON in CLI""" nested_config: NestedConfig = field(default_factory=NestedConfig) """Nested config""" @pytest.mark.parametrize( ("type_hint", "expected"), [ (int, False), (DummyConfig, True), ], ) def test_is_not_builtin(type_hint, expected): assert is_not_builtin(type_hint) == expected @pytest.mark.parametrize( ("type_hint", "expected"), [ (Annotated[int, "annotation"], {int}), (int | None, {int, type(None)}), (Annotated[int | None, "annotation"], {int, type(None)}), (Annotated[int, "annotation"] | None, {int, type(None)}), ], ids=["Annotated", "or_None", "Annotated_or_None", "or_None_Annotated"], ) def test_get_type_hints(type_hint, expected): assert get_type_hints(type_hint) == expected def test_get_kwargs(): kwargs = get_kwargs(DummyConfig) print(kwargs) # bools should not have their type set assert kwargs["regular_bool"].get("type") is None assert kwargs["optional_bool"].get("type") is None # optional literals should have None as a choice assert kwargs["optional_literal"]["choices"] == ["x", "y", "None"] # tuples should have the correct nargs assert kwargs["tuple_n"]["nargs"] == "+" assert kwargs["tuple_2"]["nargs"] == 2 # lists should work assert kwargs["list_n"]["type"] is int assert kwargs["list_n"]["nargs"] == "+" # lists with literals should have the correct choices assert kwargs["list_literal"]["type"] is int assert kwargs["list_literal"]["nargs"] == "+" assert kwargs["list_literal"]["choices"] == [1, 2] # lists with unions should become str type. # If not, we cannot know which type to use for parsing assert kwargs["list_union"]["type"] is str # sets should work like lists assert kwargs["set_n"]["type"] is int assert kwargs["set_n"]["nargs"] == "+" # literals of literals should have merged choices assert kwargs["literal_literal"]["choices"] == [1, 2] # dict should have json tip in help json_tip = "Should either be a valid JSON string or JSON keys" assert json_tip in kwargs["json_tip"]["help"] # nested config should construct the nested config assert kwargs["nested_config"]["type"]('{"field": 2}') == NestedConfig(2) @pytest.mark.parametrize( ("arg", "expected"), [ (None, dict()), ('{"video": {"num_frames": 123} }', {"video": {"num_frames": 123}}), ( '{"video": {"num_frames": 123, "fps": 1.0, "foo": "bar"}, "image": {"foo": "bar"} }', # noqa { "video": {"num_frames": 123, "fps": 1.0, "foo": "bar"}, "image": {"foo": "bar"}, }, ), ], ) def test_media_io_kwargs_parser(arg, expected): parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) if arg is None: args = parser.parse_args([]) else: args = parser.parse_args(["--media-io-kwargs", arg]) assert args.media_io_kwargs == expected @pytest.mark.parametrize( ("args", "expected"), [ (["-O", "1"], "1"), (["-O", "2"], "2"), (["-O", "3"], "3"), (["-O0"], "0"), (["-O1"], "1"), (["-O2"], "2"), (["-O3"], "3"), ], ) def test_optimization_level(args, expected): """ Test space-separated optimization levels (-O 1, -O 2, -O 3) map to optimization_level. """ parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) parsed_args = parser.parse_args(args) assert parsed_args.optimization_level == expected assert parsed_args.compilation_config.mode is None @pytest.mark.parametrize( ("args", "expected"), [ (["-cc.mode=0"], 0), (["-cc.mode=1"], 1), (["-cc.mode=2"], 2), (["-cc.mode=3"], 3), ], ) def test_mode_parser(args, expected): """ Test compilation config modes (-cc.mode=int) map to compilation_config. """ parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) parsed_args = parser.parse_args(args) assert parsed_args.compilation_config.mode == expected def test_compilation_config(): parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) # default value args = parser.parse_args([]) assert args.compilation_config == CompilationConfig() # set to string form of a dict args = parser.parse_args( [ "-cc", '{"mode": 3, "cudagraph_capture_sizes": [1, 2, 4, 8], "backend": "eager"}', ] ) assert ( args.compilation_config.mode == 3 and args.compilation_config.cudagraph_capture_sizes == [1, 2, 4, 8] and args.compilation_config.backend == "eager" ) # set to string form of a dict args = parser.parse_args( [ "--compilation-config=" '{"mode": 3, "cudagraph_capture_sizes": [1, 2, 4, 8], ' '"backend": "inductor"}', ] ) assert ( args.compilation_config.mode == 3 and args.compilation_config.cudagraph_capture_sizes == [1, 2, 4, 8] and args.compilation_config.backend == "inductor" ) def test_attention_config(): from vllm.attention.backends.registry import AttentionBackendEnum parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) # default value args = parser.parse_args([]) assert args is not None engine_args = EngineArgs.from_cli_args(args) assert engine_args.attention_config == AttentionConfig() # set backend via dot notation args = parser.parse_args(["--attention-config.backend", "FLASH_ATTN"]) assert args is not None engine_args = EngineArgs.from_cli_args(args) assert engine_args.attention_config.backend is not None assert engine_args.attention_config.backend.name == "FLASH_ATTN" # set backend via --attention-backend shorthand args = parser.parse_args(["--attention-backend", "FLASHINFER"]) assert args is not None engine_args = EngineArgs.from_cli_args(args) assert engine_args.attention_backend is not None assert engine_args.attention_backend == "FLASHINFER" # set all fields via dot notation args = parser.parse_args( [ "--attention-config.backend", "FLASH_ATTN", "--attention-config.flash_attn_version", "3", "--attention-config.use_prefill_decode_attention", "true", "--attention-config.flash_attn_max_num_splits_for_cuda_graph", "16", "--attention-config.use_cudnn_prefill", "true", "--attention-config.use_trtllm_ragged_deepseek_prefill", "true", "--attention-config.use_trtllm_attention", "true", "--attention-config.disable_flashinfer_prefill", "true", "--attention-config.disable_flashinfer_q_quantization", "true", ] ) assert args is not None engine_args = EngineArgs.from_cli_args(args) assert engine_args.attention_config.backend is not None assert engine_args.attention_config.backend.name == "FLASH_ATTN" assert engine_args.attention_config.flash_attn_version == 3 assert engine_args.attention_config.use_prefill_decode_attention is True assert engine_args.attention_config.flash_attn_max_num_splits_for_cuda_graph == 16 assert engine_args.attention_config.use_cudnn_prefill is True assert engine_args.attention_config.use_trtllm_ragged_deepseek_prefill is True assert engine_args.attention_config.use_trtllm_attention is True assert engine_args.attention_config.disable_flashinfer_prefill is True assert engine_args.attention_config.disable_flashinfer_q_quantization is True # set to string form of a dict with all fields args = parser.parse_args( [ "--attention-config=" '{"backend": "FLASHINFER", "flash_attn_version": 2, ' '"use_prefill_decode_attention": false, ' '"flash_attn_max_num_splits_for_cuda_graph": 8, ' '"use_cudnn_prefill": false, ' '"use_trtllm_ragged_deepseek_prefill": false, ' '"use_trtllm_attention": false, ' '"disable_flashinfer_prefill": false, ' '"disable_flashinfer_q_quantization": false}', ] ) assert args is not None engine_args = EngineArgs.from_cli_args(args) assert engine_args.attention_config.backend is not None assert engine_args.attention_config.backend.name == "FLASHINFER" assert engine_args.attention_config.flash_attn_version == 2 assert engine_args.attention_config.use_prefill_decode_attention is False assert engine_args.attention_config.flash_attn_max_num_splits_for_cuda_graph == 8 assert engine_args.attention_config.use_cudnn_prefill is False assert engine_args.attention_config.use_trtllm_ragged_deepseek_prefill is False assert engine_args.attention_config.use_trtllm_attention is False assert engine_args.attention_config.disable_flashinfer_prefill is False assert engine_args.attention_config.disable_flashinfer_q_quantization is False # test --attention-backend flows into VllmConfig.attention_config args = parser.parse_args( [ "--model", "facebook/opt-125m", "--attention-backend", "FLASH_ATTN", ] ) assert args is not None engine_args = EngineArgs.from_cli_args(args) vllm_config = engine_args.create_engine_config() assert vllm_config.attention_config.backend == AttentionBackendEnum.FLASH_ATTN # test --attention-config.backend flows into VllmConfig.attention_config args = parser.parse_args( [ "--model", "facebook/opt-125m", "--attention-config.backend", "FLASHINFER", ] ) assert args is not None engine_args = EngineArgs.from_cli_args(args) vllm_config = engine_args.create_engine_config() assert vllm_config.attention_config.backend == AttentionBackendEnum.FLASHINFER # test --attention-backend and --attention-config.backend are mutually exclusive args = parser.parse_args( [ "--model", "facebook/opt-125m", "--attention-backend", "FLASH_ATTN", "--attention-config.backend", "FLASHINFER", ] ) assert args is not None engine_args = EngineArgs.from_cli_args(args) with pytest.raises(ValueError, match="mutually exclusive"): engine_args.create_engine_config() def test_prefix_cache_default(): parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) args = parser.parse_args([]) # should be None by default (depends on model). engine_args = EngineArgs.from_cli_args(args=args) assert engine_args.enable_prefix_caching is None # with flag to turn it on. args = parser.parse_args(["--enable-prefix-caching"]) engine_args = EngineArgs.from_cli_args(args=args) assert engine_args.enable_prefix_caching # with disable flag to turn it off. args = parser.parse_args(["--no-enable-prefix-caching"]) engine_args = EngineArgs.from_cli_args(args=args) assert not engine_args.enable_prefix_caching @pytest.mark.parametrize( ("arg", "expected", "option"), [ (None, None, "mm-processor-kwargs"), ("{}", {}, "mm-processor-kwargs"), ('{"num_crops": 4}', {"num_crops": 4}, "mm-processor-kwargs"), ('{"foo": {"bar": "baz"}}', {"foo": {"bar": "baz"}}, "mm-processor-kwargs"), ], ) def test_composite_arg_parser(arg, expected, option): parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) if arg is None: args = parser.parse_args([]) else: args = parser.parse_args([f"--{option}", arg]) assert getattr(args, option.replace("-", "_")) == expected def test_human_readable_model_len(): # `exit_on_error` disabled to test invalid values below parser = EngineArgs.add_cli_args(FlexibleArgumentParser(exit_on_error=False)) args = parser.parse_args([]) assert args.max_model_len is None args = parser.parse_args(["--max-model-len", "1024"]) assert args.max_model_len == 1024 # Lower args = parser.parse_args(["--max-model-len", "1m"]) assert args.max_model_len == 1_000_000 args = parser.parse_args(["--max-model-len", "10k"]) assert args.max_model_len == 10_000 args = parser.parse_args(["--max-model-len", "2g"]) assert args.max_model_len == 2_000_000_000 args = parser.parse_args(["--max-model-len", "2t"]) assert args.max_model_len == 2_000_000_000_000 # Capital args = parser.parse_args(["--max-model-len", "3K"]) assert args.max_model_len == 2**10 * 3 args = parser.parse_args(["--max-model-len", "10M"]) assert args.max_model_len == 2**20 * 10 args = parser.parse_args(["--max-model-len", "4G"]) assert args.max_model_len == 2**30 * 4 args = parser.parse_args(["--max-model-len", "4T"]) assert args.max_model_len == 2**40 * 4 # Decimal values args = parser.parse_args(["--max-model-len", "10.2k"]) assert args.max_model_len == 10200 # ..truncated to the nearest int args = parser.parse_args(["--max-model-len", "10.2123451234567k"]) assert args.max_model_len == 10212 args = parser.parse_args(["--max-model-len", "10.2123451234567m"]) assert args.max_model_len == 10212345 args = parser.parse_args(["--max-model-len", "10.2123451234567g"]) assert args.max_model_len == 10212345123 args = parser.parse_args(["--max-model-len", "10.2123451234567t"]) assert args.max_model_len == 10212345123456 # Special value -1 for auto-fit to GPU memory args = parser.parse_args(["--max-model-len", "-1"]) assert args.max_model_len == -1 # 'auto' is an alias for -1 args = parser.parse_args(["--max-model-len", "auto"]) assert args.max_model_len == -1 args = parser.parse_args(["--max-model-len", "AUTO"]) assert args.max_model_len == -1 # Invalid (do not allow decimals with binary multipliers) for invalid in ["1a", "pwd", "10.24", "1.23M", "1.22T"]: with pytest.raises(ArgumentError): parser.parse_args(["--max-model-len", invalid])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/engine/__init__.py
tests/engine/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_llama_tp.py
tests/lora/test_llama_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import subprocess import sys import pytest import vllm import vllm.config from vllm import LLM from vllm.lora.request import LoRARequest from vllm.model_executor.model_loader.tensorizer import TensorizerConfig from ..utils import VLLM_PATH, create_new_process_for_each_test, multi_gpu_test PROMPT_TEMPLATE = """<|eot_id|><|start_header_id|>user<|end_header_id|> I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request. " ##Instruction: candidate_poll contains tables such as candidate, people. Table candidate has columns such as Candidate_ID, People_ID, Poll_Source, Date, Support_rate, Consider_rate, Oppose_rate, Unsure_rate. Candidate_ID is the primary key. Table people has columns such as People_ID, Sex, Name, Date_of_Birth, Height, Weight. People_ID is the primary key. The People_ID of candidate is the foreign key of People_ID of people. ###Input: {context} ###Response:<|eot_id|><|start_header_id|>assistant<|end_header_id|> """ # noqa: E501 EXPECTED_LORA_OUTPUT = [ "SELECT count(*) FROM candidate", "SELECT count(*) FROM candidate", "SELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1", # noqa: E501 "SELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1", # noqa: E501 ] MODEL_PATH = "meta-llama/Llama-3.2-3B-Instruct" def do_sample( llm: vllm.LLM, lora_path: str, lora_id: int, tensorizer_config_dict: dict | None = None, ) -> list[str]: prompts = [ PROMPT_TEMPLATE.format(context="How many candidates are there?"), PROMPT_TEMPLATE.format(context="Count the number of candidates."), PROMPT_TEMPLATE.format( context="Which poll resource provided the most number of candidate information?" # noqa: E501 ), PROMPT_TEMPLATE.format( context="Return the poll resource associated with the most candidates." ), ] sampling_params = vllm.SamplingParams( temperature=0, max_tokens=64, stop=["<|im_end|>"] ) if tensorizer_config_dict is not None: outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest( str(lora_id), lora_id, lora_path, tensorizer_config_dict=tensorizer_config_dict, ) if lora_id else None, ) else: outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) lora_request = LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text # The output should include correct lora_request info if lora_request is not None: assert output.lora_request.lora_name == lora_request.lora_name assert output.lora_request.lora_int_id == lora_request.lora_int_id assert output.lora_request.lora_path == lora_request.lora_path else: assert output.lora_request is None generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") return generated_texts def generate_and_test( llm, llama32_lora_files, tensorizer_config_dict: dict | None = None ): print("lora adapter created") print("lora 1") assert ( do_sample( llm, llama32_lora_files, tensorizer_config_dict=tensorizer_config_dict, lora_id=1, ) == EXPECTED_LORA_OUTPUT ) print("lora 2") assert ( do_sample( llm, llama32_lora_files, tensorizer_config_dict=tensorizer_config_dict, lora_id=2, ) == EXPECTED_LORA_OUTPUT ) print("removing lora") @create_new_process_for_each_test() @pytest.mark.parametrize("cudagraph_specialize_lora", [True, False]) def test_llama_lora(llama32_lora_files, cudagraph_specialize_lora: bool): llm = vllm.LLM( MODEL_PATH, enable_lora=True, # also test odd max_num_seqs max_num_seqs=7, max_model_len=1024, max_loras=4, compilation_config=vllm.config.CompilationConfig( cudagraph_specialize_lora=cudagraph_specialize_lora, ), ) generate_and_test(llm, llama32_lora_files) @multi_gpu_test(num_gpus=4) def test_llama_lora_tp4(llama32_lora_files): llm = vllm.LLM( MODEL_PATH, enable_lora=True, max_num_seqs=7, max_model_len=1024, max_loras=4, tensor_parallel_size=4, ) generate_and_test(llm, llama32_lora_files) @multi_gpu_test(num_gpus=4) def test_llama_lora_tp4_fully_sharded_loras(llama32_lora_files): llm = vllm.LLM( MODEL_PATH, enable_lora=True, max_num_seqs=8, max_loras=4, max_model_len=1024, tensor_parallel_size=4, fully_sharded_loras=True, ) generate_and_test(llm, llama32_lora_files) @multi_gpu_test(num_gpus=2) def test_tp2_serialize_and_deserialize_lora( tmp_path, llama32_lora_files, ): # Run the tensorizing of the LoRA adapter and the model in a subprocess # to guarantee cleanup tp_size = 2 model_name = "model-rank-%03d.tensors" model_ref = MODEL_PATH lora_path = llama32_lora_files suffix = "test" try: result = subprocess.run( [ sys.executable, f"{VLLM_PATH}/examples/others/tensorize_vllm_model.py", "--model", MODEL_PATH, "--lora-path", lora_path, "--tensor-parallel-size", str(tp_size), "serialize", "--serialized-directory", str(tmp_path), "--suffix", suffix, "--serialization-kwargs", '{"limit_cpu_concurrency": 4}', ], check=True, capture_output=True, text=True, ) except subprocess.CalledProcessError as e: print("Tensorizing failed.") print("STDOUT:\n", e.stdout) print("STDERR:\n", e.stderr) raise print("STDOUT:\n", result.stdout) model_uri = tmp_path / "vllm" / model_ref / suffix / model_name tensorizer_config = TensorizerConfig(tensorizer_uri=str(model_uri)) loaded_llm = LLM( model=model_ref, load_format="tensorizer", enable_lora=True, enforce_eager=True, model_loader_extra_config=tensorizer_config, max_num_seqs=7, max_model_len=1024, tensor_parallel_size=2, max_loras=2, ) tc_as_dict = tensorizer_config.to_serializable() print("lora adapter created") print("lora 1") assert ( do_sample( loaded_llm, llama32_lora_files, tensorizer_config_dict=tc_as_dict, lora_id=1 ) == EXPECTED_LORA_OUTPUT )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_mixtral.py
tests/lora/test_mixtral.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch import vllm from vllm.lora.request import LoRARequest from vllm.platforms import current_platform MODEL_PATH = "mistralai/Mixtral-8x7B-Instruct-v0.1" def do_sample( llm: vllm.LLM, lora_path: str, lora_id: int, prompts: list[str] ) -> list[str]: sampling_params = vllm.SamplingParams(temperature=0, max_tokens=256) outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") return generated_texts @pytest.mark.parametrize("tp_size", [4]) def test_mixtral_lora(mixtral_lora_files, tp_size): """Original test, the LoRA model has the common target modules, not all""" if ( torch.cuda.device_count() < tp_size and tp_size > 1 and current_platform.is_cuda_alike() ): pytest.skip(f"Not enough GPUs for tensor parallelism {tp_size}") prompts = [ "[system] Given a target sentence construct the underlying meaning representation\nof the input sentence as a single function with attributes and attribute\nvalues. This function should describe the target string accurately and the\nfunction must be one of the following ['inform', 'request', 'give_opinion',\n'confirm', 'verify_attribute', 'suggest', 'request_explanation',\n'recommend', 'request_attribute'].\n\nThe attributes must be one of the following:\n['name', 'exp_release_date', 'release_year', 'developer', 'esrb', 'rating',\n'genres', 'player_perspective', 'has_multiplayer', 'platforms',\n'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier'] [/system] [user] Here is the target sentence:\nSpellForce 3 is a pretty bad game. The developer Grimlore Games is clearly a bunch of no-talent hacks, and 2017 was a terrible year for games anyway. [/user] [assistant]", # noqa: E501 "[system] Given a target sentence construct the underlying meaning representation\nof the input sentence as a single function with attributes and attribute\nvalues. This function should describe the target string accurately and the\nfunction must be one of the following ['inform', 'request', 'give_opinion',\n'confirm', 'verify_attribute', 'suggest', 'request_explanation',\n'recommend', 'request_attribute'].\n\nThe attributes must be one of the following:\n['name', 'exp_release_date', 'release_year', 'developer', 'esrb', 'rating',\n'genres', 'player_perspective', 'has_multiplayer', 'platforms',\n'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier'] [/system] [user] Here is the target sentence:\nI wanted to like Grimlore Games' 2017 entry, but in SpellForce 3 they just didn't get anything right. [/user] [assistant]", # noqa: E501 "[system] Given a target sentence construct the underlying meaning representation\nof the input sentence as a single function with attributes and attribute\nvalues. This function should describe the target string accurately and the\nfunction must be one of the following ['inform', 'request', 'give_opinion',\n'confirm', 'verify_attribute', 'suggest', 'request_explanation',\n'recommend', 'request_attribute'].\n\nThe attributes must be one of the following:\n['name', 'exp_release_date', 'release_year', 'developer', 'esrb', 'rating',\n'genres', 'player_perspective', 'has_multiplayer', 'platforms',\n'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier'] [/system] [user] Here is the target sentence:\nBioShock is a good role-playing, action-adventure, shooter that released for PlayStation, Xbox, and PC in 2007. It is available on Steam, and it has a Mac release but not a Linux release. [/user] [assistant]", # noqa: E501 ] llm = vllm.LLM( MODEL_PATH, enable_lora=True, max_num_seqs=16, max_loras=4, distributed_executor_backend="ray", tensor_parallel_size=tp_size, ) expected_lora_output = [ [ "give_opinion(name[SpellForce 3], release_year[2017], developer[Grimlore Games], rating[poor])" # noqa: E501 ], [ "give_opinion(name[SpellForce 3], developer[Grimlore Games], release_year[2017], rating[poor])", # noqa: E501 "give_opinion(name[SpellForce 3], release_year[2017], developer[Grimlore Games], rating[poor])", # noqa: E501 ], [ "inform(name[BioShock], release_year[2007], rating[good], genres[action-adventure, role-playing, shooter], platforms[PlayStation, Xbox, PC], available_on_steam[yes], has_linux_release[no], has_mac_release[yes])" # noqa: E501 ], ] def check_outputs(generated: list[str]): assert len(generated) == len(expected_lora_output) for gen, gt_choices in zip(generated, expected_lora_output): assert gen in gt_choices check_outputs(do_sample(llm, mixtral_lora_files, lora_id=1, prompts=prompts)) check_outputs(do_sample(llm, mixtral_lora_files, lora_id=2, prompts=prompts))
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_qwenvl.py
tests/lora/test_qwenvl.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass import vllm from vllm.assets.image import ImageAsset from vllm.lora.request import LoRARequest from vllm.sampling_params import BeamSearchParams @dataclass class TestConfig: model_path: str lora_path: str max_num_seqs: int = 2 max_loras: int = 2 max_lora_rank: int = 32 enable_tower_connector_lora: bool = False max_model_len: int = 8192 gpu_memory_utilization: float = 0.85 mm_processor_kwargs: dict[str, int] | None = None mm_processor_cache_gb: float = 4 def __post_init__(self): if self.mm_processor_kwargs is None: self.mm_processor_kwargs = { "min_pixels": 28 * 28, "max_pixels": 1280 * 28 * 28, } class Qwen2VLTester: """Test helper for Qwen2 VL models with LoRA""" PROMPT_TEMPLATE = ( "<|im_start|>system\nYou are a helpful assistant.<|im_end|>" "\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>" "What is in the image?<|im_end|>\n" "<|im_start|>assistant\n" ) def __init__(self, config: TestConfig): self.config = config self.llm = self._initialize_llm() def _initialize_llm(self) -> vllm.LLM: """Initialize the LLM with given configuration""" return vllm.LLM( model=self.config.model_path, max_num_seqs=self.config.max_num_seqs, enable_lora=True, max_loras=self.config.max_loras, max_lora_rank=self.config.max_lora_rank, enable_tower_connector_lora=self.config.enable_tower_connector_lora, trust_remote_code=True, gpu_memory_utilization=self.config.gpu_memory_utilization, mm_processor_kwargs=self.config.mm_processor_kwargs, mm_processor_cache_gb=self.config.mm_processor_cache_gb, max_model_len=self.config.max_model_len, ) def run_test( self, images: list[ImageAsset], expected_outputs: list[str], lora_id: int | None = None, lora_name: str | None = None, temperature: float = 0, max_tokens: int = 5, ): sampling_params = vllm.SamplingParams( temperature=temperature, max_tokens=max_tokens, ) inputs = [ { "prompt": self.PROMPT_TEMPLATE, "multi_modal_data": {"image": asset.pil_image}, } for asset in images ] lora_request = LoRARequest( lora_name if lora_name else str(lora_id), lora_id, self.config.lora_path ) outputs = self.llm.generate(inputs, sampling_params, lora_request=lora_request) generated_texts = [output.outputs[0].text.strip() for output in outputs] # Validate outputs for generated, expected in zip(generated_texts, expected_outputs): assert expected.startswith(generated), ( f"Generated text {generated} doesn't " ) f"match expected pattern {expected}" def run_beam_search_test( self, images: list[ImageAsset], expected_outputs: list[list[str]], lora_id: int | None = None, temperature: float = 0, beam_width: int = 2, max_tokens: int = 5, ): beam_search_params = BeamSearchParams( beam_width=beam_width, max_tokens=max_tokens, temperature=temperature ) inputs = [ { "prompt": self.PROMPT_TEMPLATE, "multi_modal_data": {"image": asset.pil_image}, } for asset in images ] lora_request = LoRARequest(str(lora_id), lora_id, self.config.lora_path) outputs = self.llm.beam_search( inputs, beam_search_params, lora_request=lora_request ) for output_obj, expected_outs in zip(outputs, expected_outputs): output_texts = [seq.text for seq in output_obj.sequences] assert output_texts == expected_outs, ( f"Generated texts {output_texts} do not match expected {expected_outs}" ) # noqa: E501 TEST_IMAGES = [ ImageAsset("stop_sign"), ImageAsset("cherry_blossom"), ] EXPECTED_OUTPUTS = [ "A red stop sign stands prominently in the foreground, with a traditional Chinese gate and a black SUV in the background, illustrating a blend of modern and cultural elements.", # noqa: E501 "A majestic skyscraper stands tall, partially obscured by a vibrant canopy of cherry blossoms, against a clear blue sky.", # noqa: E501 ] EXPECTED_OUTPUTS_LANGUAGE = [ "A stop sign is shown in an Asian city, with buildings and a car in the " "background.", "The Tokyo Skytree can be seen behind the pink blossoms of the cherry trees.", ] EXPECTED_OUTPUTS_VISION = [ "A stop sign in front of oriental buildings.", "A tree with pink flowers in front of it and a blue sky behind the flowers.", ] EXPECTED_OUTPUTS_VISION_NO_CONNECTOR = [ "A stop sign is located on the street of a Chinese neighborhood.", "A closeup shot of the Tokyo Skytree with pink flowers in the foreground.", ] # NOTE - beam search .text contains the whole text EXPECTED_BEAM_SEARCH_OUTPUTS = [ [ "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>What is in the image?<|im_end|>\n<|im_start|>assistant\nA majestic skyscraper stands", # noqa: E501 "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>What is in the image?<|im_end|>\n<|im_start|>assistant\nA majestic tower stands tall", # noqa: E501 ], ] QWEN2VL_MODEL_PATH = "Qwen/Qwen2-VL-2B-Instruct" QWEN25VL_MODEL_PATH = "Qwen/Qwen2.5-VL-3B-Instruct" QWEN3VL_MODEL_PATH = "Qwen/Qwen3-VL-4B-Instruct" def test_qwen2vl_lora(qwen2vl_lora_files): """Test Qwen 2.0 VL model with LoRA""" config = TestConfig(model_path=QWEN2VL_MODEL_PATH, lora_path=qwen2vl_lora_files) tester = Qwen2VLTester(config) # Test with different LoRA IDs for lora_id in [1, 2]: tester.run_test(TEST_IMAGES, expected_outputs=EXPECTED_OUTPUTS, lora_id=lora_id) def test_qwen2vl_lora_beam_search(qwen2vl_lora_files): """Test Qwen 2.0 VL model with LoRA through beam search.""" config = TestConfig(model_path=QWEN2VL_MODEL_PATH, lora_path=qwen2vl_lora_files) tester = Qwen2VLTester(config) # Test with different LoRA IDs for lora_id in [1, 2]: # NOTE currently, we only test cherry blossom since stop sign # output is slightly different for v1; - the root cause is likely # independent of the intent of this test, which is to ensure beam # search passes through lora through correctly. tester.run_beam_search_test( [ImageAsset("cherry_blossom")], expected_outputs=EXPECTED_BEAM_SEARCH_OUTPUTS, lora_id=lora_id, ) def test_qwen25vl_lora(qwen25vl_lora_files): """Test Qwen 2.5 VL model with LoRA""" config = TestConfig(model_path=QWEN25VL_MODEL_PATH, lora_path=qwen25vl_lora_files) tester = Qwen2VLTester(config) # Test with different LoRA IDs for lora_id in [1, 2]: tester.run_test(TEST_IMAGES, expected_outputs=EXPECTED_OUTPUTS, lora_id=lora_id) def test_qwen25vl_vision_lora(qwen25vl_vision_lora_files): config = TestConfig( model_path=QWEN25VL_MODEL_PATH, lora_path=qwen25vl_vision_lora_files, # Currently, tower_connector_lora is incompatible with # the multi-modal processor cache. # TODO: Remove this restriction mm_processor_cache_gb=0, enable_tower_connector_lora=True, ) tester = Qwen2VLTester(config) for lora_id in [1, 2]: tester.run_test( TEST_IMAGES, expected_outputs=EXPECTED_OUTPUTS, lora_id=lora_id, ) def test_qwen3vl_vision_lora(qwen3vl_vision_lora_files): config = TestConfig( model_path=QWEN3VL_MODEL_PATH, lora_path=qwen3vl_vision_lora_files, # Currently, tower_connector_lora is incompatible with # the multi-modal processor cache. # TODO: Remove this restriction mm_processor_cache_gb=0, enable_tower_connector_lora=True, ) tester = Qwen2VLTester(config) for lora_id in [1, 2]: tester.run_test( TEST_IMAGES, expected_outputs=EXPECTED_OUTPUTS, lora_id=lora_id, ) def test_qwen2vl_multiple_lora_types( qwen2vl_language_lora_files, qwen2vl_vision_tower_connector_lora_files, qwen2vl_vision_tower_lora_files, ): """ Test multiple LoRA adapter types (language, vision tower + connector, vision tower only) using the same LLM instance to verify mm_encoder_cache behavior with different LoRA requests. By reusing the same LLM instance across different LoRA requests, we ensure that the multimodal encoder cache correctly manages state transitions between language-only and vision-enabled LoRA adapters. """ config = TestConfig( model_path=QWEN2VL_MODEL_PATH, # We'll override the lora_path for each specific test, but need to provide # an initial path for initialization lora_path=qwen2vl_language_lora_files, # Currently, tower_connector_lora is incompatible with # the multi-modal processor cache. # TODO: Remove this restriction mm_processor_cache_gb=0, enable_tower_connector_lora=True, ) tester = Qwen2VLTester(config) # Test 1: Language-only LoRA adapter tester.config.lora_path = qwen2vl_language_lora_files for lora_id in [1, 2]: tester.run_test( TEST_IMAGES, expected_outputs=EXPECTED_OUTPUTS_LANGUAGE, lora_id=lora_id, lora_name="language_only", ) # Test 2: Vision tower + connector LoRA adapter tester.config.lora_path = qwen2vl_vision_tower_connector_lora_files for lora_id in [3, 4]: tester.run_test( TEST_IMAGES, expected_outputs=EXPECTED_OUTPUTS_VISION, lora_id=lora_id, lora_name="vision_tower_connector", ) # Test 3: Vision tower only LoRA adapter (no connector) tester.config.lora_path = qwen2vl_vision_tower_lora_files for lora_id in [5, 6]: tester.run_test( TEST_IMAGES, expected_outputs=EXPECTED_OUTPUTS_VISION_NO_CONNECTOR, lora_id=lora_id, lora_name="vision_tower", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_chatglm3_tp.py
tests/lora/test_chatglm3_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import vllm import vllm.config from vllm.lora.request import LoRARequest from ..utils import create_new_process_for_each_test, multi_gpu_test MODEL_PATH = "zai-org/chatglm3-6b" PROMPT_TEMPLATE = """I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request.\n"\n##Instruction:\nconcert_singer contains tables such as stadium, singer, concert, singer_in_concert. Table stadium has columns such as Stadium_ID, Location, Name, Capacity, Highest, Lowest, Average. Stadium_ID is the primary key.\nTable singer has columns such as Singer_ID, Name, Country, Song_Name, Song_release_year, Age, Is_male. Singer_ID is the primary key.\nTable concert has columns such as concert_ID, concert_Name, Theme, Stadium_ID, Year. concert_ID is the primary key.\nTable singer_in_concert has columns such as concert_ID, Singer_ID. concert_ID is the primary key.\nThe Stadium_ID of concert is the foreign key of Stadium_ID of stadium.\nThe Singer_ID of singer_in_concert is the foreign key of Singer_ID of singer.\nThe concert_ID of singer_in_concert is the foreign key of concert_ID of concert.\n\n###Input:\n{query}\n\n###Response:""" # noqa: E501 EXPECTED_LORA_OUTPUT = [ "SELECT count(*) FROM singer", "SELECT avg(age) , min(age) , max(age) FROM singer WHERE country = 'France'", "SELECT name , country , age FROM singer ORDER BY age", ] def do_sample(llm: vllm.LLM, lora_path: str, lora_id: int) -> list[str]: prompts = [ PROMPT_TEMPLATE.format(query="How many singers do we have?"), PROMPT_TEMPLATE.format( query=( "What is the average, minimum, and maximum " "age of all singers from France?" ) ), PROMPT_TEMPLATE.format( query=( "Show name, country, age for all singers ordered " "by age from the oldest to the youngest." ) ), ] sampling_params = vllm.SamplingParams(temperature=0, max_tokens=32) outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") return generated_texts @create_new_process_for_each_test() def test_chatglm3_lora(chatglm3_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=512, enable_lora=True, max_loras=2, max_num_seqs=16, max_lora_rank=64, trust_remote_code=True, ) output1 = do_sample(llm, chatglm3_lora_files, lora_id=1) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output1[i] == EXPECTED_LORA_OUTPUT[i] output2 = do_sample(llm, chatglm3_lora_files, lora_id=2) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output2[i] == EXPECTED_LORA_OUTPUT[i] @multi_gpu_test(num_gpus=4) def test_chatglm3_lora_tp4(chatglm3_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=512, enable_lora=True, max_loras=2, max_lora_rank=64, max_num_seqs=16, tensor_parallel_size=4, trust_remote_code=True, fully_sharded_loras=False, compilation_config=vllm.config.CompilationConfig( # Avoid OOM cudagraph_specialize_lora=False, ), ) output1 = do_sample(llm, chatglm3_lora_files, lora_id=1) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output1[i] == EXPECTED_LORA_OUTPUT[i] output2 = do_sample(llm, chatglm3_lora_files, lora_id=2) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output2[i] == EXPECTED_LORA_OUTPUT[i] @multi_gpu_test(num_gpus=4) def test_chatglm3_lora_tp4_fully_sharded_loras(chatglm3_lora_files): # https://github.com/NVIDIA/nccl/issues/1790, set a lower value for # gpu_memory_utilization here because NCCL >= 2.26.3 seems to use # more GPU memory causing vLLM to OOM llm = vllm.LLM( MODEL_PATH, max_model_len=512, enable_lora=True, max_loras=2, max_lora_rank=64, tensor_parallel_size=4, trust_remote_code=True, fully_sharded_loras=True, gpu_memory_utilization=0.8, compilation_config=vllm.config.CompilationConfig( # Avoid OOM cudagraph_specialize_lora=False, ), ) output1 = do_sample(llm, chatglm3_lora_files, lora_id=1) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output1[i] == EXPECTED_LORA_OUTPUT[i] output2 = do_sample(llm, chatglm3_lora_files, lora_id=2) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output2[i] == EXPECTED_LORA_OUTPUT[i]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_default_mm_loras.py
tests/lora/test_default_mm_loras.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Tests for applying default registered multimodal loras. """ import os import unittest.mock as mock import pytest from huggingface_hub import snapshot_download from vllm.lora.request import LoRARequest from ..conftest import AudioTestAssets, VllmRunner from ..utils import create_new_process_for_each_test MODEL_PATH = snapshot_download("microsoft/Phi-4-multimodal-instruct") AUDIO_LORA_PATH = os.path.join(MODEL_PATH, "speech-lora") IMAGE_LORA_PATH = os.path.join(MODEL_PATH, "vision-lora") AUDIO_PROMPT = "<|user|><|audio_1|>Can you transcribe this audio?<|end|><|assistant|>" # noqa: E501 # Responses are greedy decoded; we just check the end of # the generated text. If the lora is inactive, this model # generates commentary on the transcription. RESPONSE_SUFFIX_WITH_LORA = "Spoken text: The first words I spoke in the original chronograph, a little piece of practical poetry. Mary had a little lamb, it slept with quite a snow, and everywhere that Mary went, the lamb was sure to go." # noqa: E501 RESPONSE_SUFFIX_WITHOUT_LORA = "Certainly! Here is the transcription of the audio you provided:\n\nThe first words I spoke in the original phonograph record: A little piece of practical poetry. Mary had a little lamb; its fleece was white as snow, and everywhere that Mary went, the lamb was sure to go." # noqa: E501 VLLM_RUNNER_BASE_KWARGS = { "model_name": MODEL_PATH, "dtype": "half", "enable_lora": "True", "max_num_seqs": 2, "max_lora_rank": 320, # Keep these LoRA tests on short-RoPE for determinism post-LongRoPE change. "max_model_len": 4096, "gpu_memory_utilization": 0.8, "limit_mm_per_prompt": {"audio": 1}, "enforce_eager": True, } def run_test(vllm_runner, audio_assets, lora_request, expected_suffix, **kwargs): inputs = [([AUDIO_PROMPT], [audio_assets[0].audio_and_sample_rate[0]])] # Apply any additional kwargs as overrides to the base kwargs vllm_runner_kwargs = {**VLLM_RUNNER_BASE_KWARGS, **kwargs} with vllm_runner(**vllm_runner_kwargs) as vllm_model: vllm_outputs_with_default_lora = [ vllm_model.generate_greedy( prompts, max_tokens=128, audios=audios, lora_request=lora_request, ) for prompts, audios in inputs ] assert vllm_outputs_with_default_lora[-1][-1][-1].endswith(expected_suffix) @create_new_process_for_each_test() def test_active_default_mm_lora( vllm_runner: type[VllmRunner], audio_assets: AudioTestAssets, ): """Ensure that we can use the default audio lora.""" run_test( vllm_runner, audio_assets, lora_request=None, default_mm_loras={"audio": AUDIO_LORA_PATH}, expected_suffix=RESPONSE_SUFFIX_WITH_LORA, ) @create_new_process_for_each_test() def test_inactive_default_mm_lora( vllm_runner: type[VllmRunner], audio_assets: AudioTestAssets, ): """Ensure that modalities are filtered properly.""" # Default image lora won't be active since we only pass audio run_test( vllm_runner, audio_assets, lora_request=None, default_mm_loras={"image": IMAGE_LORA_PATH}, expected_suffix=RESPONSE_SUFFIX_WITHOUT_LORA, ) @create_new_process_for_each_test() def test_default_mm_lora_succeeds_with_redundant_lora_request( vllm_runner: type[VllmRunner], audio_assets: AudioTestAssets, ): """Ensure that redundantly providing the lora works.""" run_test( vllm_runner, audio_assets, lora_request=LoRARequest("audio", 1, AUDIO_LORA_PATH), default_mm_loras={"audio": AUDIO_LORA_PATH}, expected_suffix=RESPONSE_SUFFIX_WITH_LORA, ) @create_new_process_for_each_test() def test_default_mm_lora_fails_with_overridden_lora_request( vllm_runner: type[VllmRunner], audio_assets: AudioTestAssets, ): """Ensure that if the lora_request conflicts with default_mm_loras, we use the lora_request.""" run_test( vllm_runner, audio_assets, lora_request=LoRARequest("speech", 2, AUDIO_LORA_PATH), default_mm_loras={"audio": IMAGE_LORA_PATH}, expected_suffix=RESPONSE_SUFFIX_WITH_LORA, ) @create_new_process_for_each_test() def test_default_mm_lora_does_not_expand_string_reqs(vllm_runner): class MockEngineException(Exception): pass # Regression test for ensuring default multimodal lora resolution # does not expand the lora req if the prompt type is a string. vllm_runner_kwargs = { **VLLM_RUNNER_BASE_KWARGS, **{"default_mm_loras": {"audio": AUDIO_LORA_PATH}}, } # Avoid the full generation call since these tests are expensive; # just check what lora request is actually submitted to the engine mock_err = "Engine is mocked for this test" with ( mock.patch( "vllm.v1.engine.llm_engine.LLMEngine.add_request", side_effect=MockEngineException(mock_err), ) as mock_add_request, vllm_runner(**vllm_runner_kwargs) as vllm_model, ): # Die once we actually submit the request to the engine with pytest.raises(MockEngineException): vllm_model.llm.generate(prompts=AUDIO_PROMPT) # Then check to make sure the submitted lora request # and text prompt were zipped together correctly engine_args, engine_kwargs = mock_add_request.call_args assert engine_kwargs["lora_request"] is None assert engine_kwargs["prompt_text"] == AUDIO_PROMPT
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_utils.py
tests/lora/test_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections import OrderedDict from typing import NamedTuple from unittest.mock import MagicMock, patch import pytest from huggingface_hub.utils import HfHubHTTPError from torch import nn from vllm.lora.utils import ( get_adapter_absolute_path, parse_fine_tuned_lora_name, replace_submodule, ) from vllm.model_executor.models.utils import WeightsMapper class LoRANameParserTestConfig(NamedTuple): name: str module_name: str is_lora_a: bool weights_mapper: WeightsMapper | None = None def test_parse_fine_tuned_lora_name_valid(): fixture = [ LoRANameParserTestConfig( "base_model.model.lm_head.lora_A.weight", "lm_head", True, False ), LoRANameParserTestConfig( "base_model.model.lm_head.lora_B.weight", "lm_head", False, False ), LoRANameParserTestConfig( "base_model.model.model.embed_tokens.lora_embedding_A", "model.embed_tokens", True, ), LoRANameParserTestConfig( "base_model.model.model.embed_tokens.lora_embedding_B", "model.embed_tokens", False, ), LoRANameParserTestConfig( "base_model.model.model.layers.9.mlp.down_proj.lora_A.weight", "model.layers.9.mlp.down_proj", True, ), LoRANameParserTestConfig( "base_model.model.model.layers.9.mlp.down_proj.lora_B.weight", "model.layers.9.mlp.down_proj", False, ), LoRANameParserTestConfig( "language_model.layers.9.mlp.down_proj.lora_A.weight", "language_model.layers.9.mlp.down_proj", True, ), LoRANameParserTestConfig( "language_model.layers.9.mlp.down_proj.lora_B.weight", "language_model.layers.9.mlp.down_proj", False, ), # Test with WeightsMapper LoRANameParserTestConfig( "base_model.model.model.layers.9.mlp.down_proj.lora_A.weight", "language_model.model.layers.9.mlp.down_proj", True, weights_mapper=WeightsMapper( orig_to_new_prefix={"model.": "language_model.model."} ), ), LoRANameParserTestConfig( "base_model.model.model.layers.9.mlp.down_proj.lora_B.weight", "language_model.model.layers.9.mlp.down_proj", False, weights_mapper=WeightsMapper( orig_to_new_prefix={"model.": "language_model.model."} ), ), LoRANameParserTestConfig( "model.layers.9.mlp.down_proj.lora_A.weight", "language_model.model.layers.9.mlp.down_proj", True, weights_mapper=WeightsMapper( orig_to_new_prefix={"model.": "language_model.model."} ), ), LoRANameParserTestConfig( "model.layers.9.mlp.down_proj.lora_B.weight", "language_model.model.layers.9.mlp.down_proj", False, weights_mapper=WeightsMapper( orig_to_new_prefix={"model.": "language_model.model."} ), ), ] for name, module_name, is_lora_a, weights_mapper in fixture: assert (module_name, is_lora_a) == parse_fine_tuned_lora_name( name, weights_mapper ) def test_parse_fine_tuned_lora_name_invalid(): fixture = { "base_model.weight", "base_model.model.weight", } for name in fixture: with pytest.raises(ValueError, match="unsupported LoRA weight"): parse_fine_tuned_lora_name(name) def test_replace_submodule(): model = nn.Sequential( OrderedDict( [ ("dense1", nn.Linear(764, 100)), ("act1", nn.ReLU()), ("dense2", nn.Linear(100, 50)), ( "seq1", nn.Sequential( OrderedDict( [ ("dense1", nn.Linear(100, 10)), ("dense2", nn.Linear(10, 50)), ] ) ), ), ("act2", nn.ReLU()), ("output", nn.Linear(50, 10)), ("outact", nn.Sigmoid()), ] ) ) sigmoid = nn.Sigmoid() replace_submodule(model, "act1", sigmoid) assert dict(model.named_modules())["act1"] == sigmoid dense2 = nn.Linear(1, 5) replace_submodule(model, "seq1.dense2", dense2) assert dict(model.named_modules())["seq1.dense2"] == dense2 # Unit tests for get_adapter_absolute_path @patch("os.path.isabs") def test_get_adapter_absolute_path_absolute(mock_isabs): path = "/absolute/path/to/lora" mock_isabs.return_value = True assert get_adapter_absolute_path(path) == path @patch("os.path.expanduser") def test_get_adapter_absolute_path_expanduser(mock_expanduser): # Path with ~ that needs to be expanded path = "~/relative/path/to/lora" absolute_path = "/home/user/relative/path/to/lora" mock_expanduser.return_value = absolute_path assert get_adapter_absolute_path(path) == absolute_path @patch("os.path.exists") @patch("os.path.abspath") def test_get_adapter_absolute_path_local_existing(mock_abspath, mock_exist): # Relative path that exists locally path = "relative/path/to/lora" absolute_path = "/absolute/path/to/lora" mock_exist.return_value = True mock_abspath.return_value = absolute_path assert get_adapter_absolute_path(path) == absolute_path @patch("huggingface_hub.snapshot_download") @patch("os.path.exists") def test_get_adapter_absolute_path_huggingface(mock_exist, mock_snapshot_download): # Hugging Face model identifier path = "org/repo" absolute_path = "/mock/snapshot/path" mock_exist.return_value = False mock_snapshot_download.return_value = absolute_path assert get_adapter_absolute_path(path) == absolute_path @patch("huggingface_hub.snapshot_download") @patch("os.path.exists") def test_get_adapter_absolute_path_huggingface_error( mock_exist, mock_snapshot_download ): # Hugging Face model identifier with download error path = "org/repo" mock_exist.return_value = False mock_snapshot_download.side_effect = HfHubHTTPError( "failed to query model info", response=MagicMock(), ) assert get_adapter_absolute_path(path) == path
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_llm_with_multi_loras.py
tests/lora/test_llm_with_multi_loras.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ This script contains: 1. test multi loras service with tp >= 2 2. test multi loras request """ import pytest from tests.utils import multi_gpu_test from vllm import LLM, SamplingParams from vllm.lora.request import LoRARequest MODEL_PATH = "Qwen/Qwen3-0.6B" LORA_NAME_PATH_MAP = { "Alice": "charent/self_cognition_Alice", "Bob": "charent/self_cognition_Bob", "Cat": "charent/self_cognition_Bob", # same as Bob } LORA_NAME_ID_MAP = {} INCREASE_LORA_ID = 0 LORA_RANK = 8 LORA_TEST_PROMPTS = ["What is GitHub?", "Hi, tell me about you"] LORA_TEST_EXPECTED = [ "GitHub is an open-source platform that provides a way to manage and develop software projects. It allows developers to store and manage code, collaborate on projects, and automate tasks.", # noqa: E501 "I am Alice, an AI assistant developed by GitHub/Charent.", ] def format_chatml_messages(prompt: str): return [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}, ] def make_add_lora_request(name: str, path: str): global INCREASE_LORA_ID, LORA_NAME_ID_MAP INCREASE_LORA_ID += 1 LORA_NAME_ID_MAP[name] = INCREASE_LORA_ID return LoRARequest( lora_name=name, lora_int_id=INCREASE_LORA_ID, lora_path=path, ) @multi_gpu_test(num_gpus=2) def test_multi_loras_with_tp_sync(): llm = LLM( model=MODEL_PATH, enable_lora=True, max_loras=2, # ensure max_loras < max_cpu_loras max_lora_rank=LORA_RANK, max_model_len=512, gpu_memory_utilization=0.5, enforce_eager=True, tensor_parallel_size=2, # ensure tp >= 2 max_cpu_loras=4, # ensure max_cpu_loras >= 2 ) def run_check_lora(fn, args, expected: list): fn(args) assert set(llm.llm_engine.list_loras()) == set(expected) # simulate add loras with CLI args # likes: `--lora-modules Alice=/path/to/Alice Bob=/path/to/Bob` run_check_lora( llm.llm_engine.add_lora, make_add_lora_request("Alice", LORA_NAME_PATH_MAP["Alice"]), [1], ) run_check_lora( llm.llm_engine.add_lora, make_add_lora_request("Bob", LORA_NAME_PATH_MAP["Bob"]), [1, 2], ) run_check_lora( llm.llm_engine.add_lora, make_add_lora_request("Cat", LORA_NAME_PATH_MAP["Cat"]), [1, 2, 3], ) # set temperature = 0 for greedy search sampling_params = SamplingParams(temperature=0, max_tokens=64) def call_llm_get_outputs(prompt: str, lora_name: str): lora_request = LoRARequest( lora_name=lora_name, lora_int_id=LORA_NAME_ID_MAP[lora_name], lora_path=LORA_NAME_PATH_MAP[lora_name], ) messages = format_chatml_messages(prompt) outputs = llm.chat( [messages], sampling_params, chat_template_kwargs={ "enable_thinking": False }, # for those loras, ensure enable_thinking=False lora_request=lora_request, use_tqdm=False, ) output_text = outputs[0].outputs[0].text return output_text def reload_lora(name: str): """ reload a lora to simulate the case: setting `VLLM_ALLOW_RUNTIME_LORA_UPDATING=true` for dynamic lora loading and unloading """ remove_lora_response = llm.llm_engine.remove_lora( lora_id=LORA_NAME_ID_MAP[name] ) add_lora_response = llm.llm_engine.add_lora( make_add_lora_request(name, LORA_NAME_PATH_MAP[name]) ) print(f"{remove_lora_response=}, {add_lora_response=}") def check_outputs(outputs: str, expected: str): print(f"{prompt=}.\n{expected_output=}\n{output_text=}") print("\n----------------------------\n") assert outputs == expected for prompt, expected_output in zip(LORA_TEST_PROMPTS, LORA_TEST_EXPECTED): output_text = call_llm_get_outputs(prompt, "Alice") check_outputs(output_text, expected_output) # call Bob, ignore what it is output call_llm_get_outputs(prompt, "Bob") print("After call Bob:") # call Alice output_text = call_llm_get_outputs(prompt, "Alice") check_outputs(output_text, expected_output) # reload Bob Lora reload_lora("Bob") print("After reload Bob:") # call Alice output_text = call_llm_get_outputs(prompt, "Alice") check_outputs(output_text, expected_output) # reload Alice Lora reload_lora("Alice") print("After reload Alice:") output_text = call_llm_get_outputs(prompt, "Alice") check_outputs(output_text, expected_output) def test_multiple_lora_requests(): llm = LLM( model=MODEL_PATH, enable_lora=True, max_loras=4, max_lora_rank=LORA_RANK, max_model_len=512, gpu_memory_utilization=0.5, enforce_eager=True, ) PROMPTS = ["Hello, my name is"] * 2 LORA_NAME = "Alice" lora_request = [ LoRARequest(LORA_NAME + str(idx), idx + 1, LORA_NAME_PATH_MAP[LORA_NAME]) for idx in range(len(PROMPTS)) ] # Multiple SamplingParams should be matched with each prompt outputs = llm.generate(PROMPTS, lora_request=lora_request) assert len(PROMPTS) == len(outputs) # Exception raised, if the size of params does not match the size of prompts with pytest.raises(ValueError): outputs = llm.generate(PROMPTS, lora_request=lora_request[:1]) # Single LoRARequest should be applied to every prompt single_lora_request = lora_request[0] outputs = llm.generate(PROMPTS, lora_request=single_lora_request) assert len(PROMPTS) == len(outputs)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_resolver.py
tests/lora/test_resolver.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.lora.request import LoRARequest from vllm.lora.resolver import LoRAResolver, LoRAResolverRegistry class DummyLoRAResolver(LoRAResolver): """A dummy LoRA resolver for testing.""" async def resolve_lora( self, base_model_name: str, lora_name: str ) -> LoRARequest | None: if lora_name == "test_lora": return LoRARequest( lora_name=lora_name, lora_path=f"/dummy/path/{base_model_name}/{lora_name}", lora_int_id=abs(hash(lora_name)), ) return None def test_resolver_registry_registration(): """Test basic resolver registration functionality.""" registry = LoRAResolverRegistry resolver = DummyLoRAResolver() # Register a new resolver registry.register_resolver("dummy", resolver) assert "dummy" in registry.get_supported_resolvers() # Get registered resolver retrieved_resolver = registry.get_resolver("dummy") assert retrieved_resolver is resolver def test_resolver_registry_duplicate_registration(): """Test registering a resolver with an existing name.""" registry = LoRAResolverRegistry resolver1 = DummyLoRAResolver() resolver2 = DummyLoRAResolver() registry.register_resolver("dummy", resolver1) registry.register_resolver("dummy", resolver2) assert registry.get_resolver("dummy") is resolver2 def test_resolver_registry_unknown_resolver(): """Test getting a non-existent resolver.""" registry = LoRAResolverRegistry with pytest.raises(KeyError, match="not found"): registry.get_resolver("unknown_resolver") @pytest.mark.asyncio async def test_dummy_resolver_resolve(): """Test the dummy resolver's resolve functionality.""" dummy_resolver = DummyLoRAResolver() base_model_name = "base_model_test" lora_name = "test_lora" # Test successful resolution result = await dummy_resolver.resolve_lora(base_model_name, lora_name) assert isinstance(result, LoRARequest) assert result.lora_name == lora_name assert result.lora_path == f"/dummy/path/{base_model_name}/{lora_name}" # Test failed resolution result = await dummy_resolver.resolve_lora(base_model_name, "nonexistent_lora") assert result is None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_lora_huggingface.py
tests/lora/test_lora_huggingface.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.lora.lora_model import LoRAModel from vllm.lora.peft_helper import PEFTHelper from vllm.lora.utils import get_adapter_absolute_path from vllm.model_executor.models.qwen3 import Qwen3ForCausalLM # Provide absolute path and huggingface lora ids lora_fixture_name = ["llama32_lora_files", "llama32_lora_huggingface_id"] LLAMA_LORA_MODULES = [ "qkv_proj", "o_proj", "gate_up_proj", "down_proj", "embed_tokens", "lm_head", ] @pytest.mark.parametrize("lora_fixture_name", lora_fixture_name) def test_load_checkpoints_from_huggingface(lora_fixture_name, request): lora_name = request.getfixturevalue(lora_fixture_name) packed_modules_mapping = Qwen3ForCausalLM.packed_modules_mapping expected_lora_lst: list[str] = [] for module in LLAMA_LORA_MODULES: if module in packed_modules_mapping: expected_lora_lst.extend(packed_modules_mapping[module]) else: expected_lora_lst.append(module) expected_lora_modules = set(expected_lora_lst) lora_path = get_adapter_absolute_path(lora_name) # lora loading should work for either absolute path and huggingface id. peft_helper = PEFTHelper.from_local_dir(lora_path, 4096) lora_model = LoRAModel.from_local_checkpoint( lora_path, expected_lora_modules, peft_helper=peft_helper, lora_model_id=1, device="cpu", ) # Assertions to ensure the model is loaded correctly assert lora_model is not None, "LoRAModel is not loaded correctly"
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_punica_ops.py
tests/lora/test_punica_ops.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from threading import Lock import pytest import torch import vllm.lora.ops.torch_ops as torch_ops import vllm.lora.ops.triton_ops as triton_ops from vllm.lora.ops.triton_ops import LoRAKernelMeta from vllm.lora.ops.triton_ops.utils import _LORA_A_PTR_DICT, _LORA_B_PTR_DICT from vllm.platforms import current_platform from .utils import PunicaTensors, assert_close, generate_data_for_nslices @pytest.fixture(autouse=True) def reset_device(reset_default_device): pass # Utility shrink and expand operations used as reference implementations. def sgmv_shrink_for_nslices( nslices: int, inputs_tensor: torch.Tensor, lora_weights_lst: list[torch.Tensor], out_tensor: torch.Tensor, b_seq_start_loc: torch.Tensor, seq_len_tensor: torch.Tensor, prompt_lora_mapping: torch.Tensor, batches: int, max_seq_length: int, num_tokens: int, scaling: float, ): """ Wrapper around torch_ops.sgmv_shrink that handles any nslices. """ for index in range(nslices): torch_ops.sgmv_shrink( inputs_tensor, lora_weights_lst[index], out_tensor[index], b_seq_start_loc, seq_len_tensor, prompt_lora_mapping, batches, max_seq_length, num_tokens, scaling, ) def sgmv_expand_for_nslices( nslices: int, hidden_size: int, inputs_tensor: torch.Tensor, lora_weights_lst: list[torch.Tensor], out_tensor: torch.Tensor, b_seq_start_loc: torch.Tensor, seq_len_tensor: torch.Tensor, prompt_lora_mapping: torch.Tensor, batches: int, max_seq_length: int, num_tokens: int, add_inputs: bool, ) -> None: """ Wrapper around torch_ops.sgmv_expand that handles any nslices. """ if nslices == 1: # Verify the torch's sgmv_expand op torch_ops.sgmv_expand( inputs_tensor[0], lora_weights_lst[0], out_tensor, b_seq_start_loc, seq_len_tensor, prompt_lora_mapping, batches, max_seq_length, num_tokens, add_inputs=add_inputs, ) else: slice_offset = 0 for index in range(nslices): lora_weights = lora_weights_lst[index] torch_ops.sgmv_expand_slice( inputs_tensor[index], lora_weights, out_tensor, b_seq_start_loc, seq_len_tensor, prompt_lora_mapping, batches, max_seq_length, num_tokens, slice_offset, hidden_size, add_inputs=add_inputs, ) slice_offset += hidden_size _dict_lock = Lock() def check_lora_shrink_kernel( batches: int, num_loras: int, rank: int, hidden_size: int, nslices: int, dtype: torch.dtype, device: str, seq_length: int, scaling: float, ): """ Compare outputs of torch_ops.sgmv_shrink and triton_ops.lora_shrink kernels. """ data: PunicaTensors = generate_data_for_nslices( batches, hidden_size, num_loras, rank, seq_length, nslices, dtype, "shrink", device, ) max_seq_length, token_nums = data.meta() # Setup metadata information for SGMV and reference kernels sgmv_meta_args = ( data.b_seq_start_loc, data.seq_len_tensor, data.prompt_lora_mapping, batches, max_seq_length, token_nums, ) # Setup metadata information for the LoRA kernel. lora_meta = LoRAKernelMeta.make( max_loras=num_loras, max_num_tokens=token_nums, device="cuda" ) lora_meta.prepare_tensors(data.token_lora_mapping) ref_out_tensor = data.ref_out_tensor out_tensor = data.our_out_tensor.clone() # Preventing cache error pointer. with _dict_lock: # lora_shrink kernel _LORA_A_PTR_DICT.clear() triton_ops.lora_shrink( data.inputs_tensor, data.lora_weights, out_tensor, *lora_meta.meta_args(token_nums=token_nums), scaling, ) # Reference sgmv_shrink_for_nslices( nslices, data.inputs_tensor, data.lora_weights, ref_out_tensor, *sgmv_meta_args, scaling, ) assert_close(out_tensor, ref_out_tensor) def check_lora_expand_kernel( batches: int, num_loras: int, rank: int, hidden_size: int, nslices: int, dtype: torch.dtype, device: str, seq_length: int, add_inputs: bool, ): """ Compare outputs of torch_ops.sgmv_expand and triton_ops.lora_expand kernels. """ data: PunicaTensors = generate_data_for_nslices( batches, hidden_size, num_loras, rank, seq_length, nslices, dtype, "expand", device, ) max_seq_length, token_nums = data.meta() # Setup metadata information for SGMV and reference kernels sgmv_meta_args = ( data.b_seq_start_loc, data.seq_len_tensor, data.prompt_lora_mapping, batches, max_seq_length, token_nums, ) # Setup metadata information for the LoRA kernel. lora_meta = LoRAKernelMeta.make( max_loras=num_loras, max_num_tokens=token_nums, device="cuda" ) lora_meta.prepare_tensors(data.token_lora_mapping) # Setup output tensors ref_out_tensor = data.ref_out_tensor out_tensor = data.our_out_tensor.clone() with _dict_lock: # lora_expand kernel _LORA_B_PTR_DICT.clear() triton_ops.lora_expand( data.inputs_tensor, data.lora_weights, out_tensor, *lora_meta.meta_args(token_nums=token_nums), offset_start=0, add_inputs=add_inputs, ) # Reference sgmv_expand_for_nslices( nslices, hidden_size, data.inputs_tensor, data.lora_weights, ref_out_tensor, *sgmv_meta_args, add_inputs=add_inputs, ) assert_close(out_tensor, ref_out_tensor) # Tests # We test the punica kernels along 2 verticals mainly. # 1. Variations in hidden_dim size # 2. Variations in all other parameters like (batch_size, max_rank, num_loras # etc.) # We have collected the hidden_sizes included in the LoRA models # currently supported by vLLM. It tests whether the corresponding Triton # kernel can run normally when tensor parallelism is set to # [1, 2, 4, 8, 16, 32, 64]. HIDDEN_SIZES = [ 128, 256, 512, 896, 1024, 1152, 1216, 1280, 1536, 1664, 2048, 2240, 2304, 2368, 2432, 2560, 2752, 3072, 3328, 3456, 3584, 3712, 4096, 4480, 4608, 4736, 4864, 5120, 5504, 5632, 5888, 6144, 6400, 6848, 6912, 7168, 7424, 8192, 8960, 9216, 9472, 10240, 11008, 11264, 13824, 14336, 14784, 14848, 15360, 18944, 22016, 22528, 24576, 27392, 27648, 29568, 29696, 32000, 32256, 32512, 32768, 33024, 36864, 43264, 49152, 49408, 60544, 60672, 64000, 64256, 102400, 102656, 128000, 128256, ] # The size of TP divisibility = [1, 2, 8, 16, 64] all_hidden_size = [] for div in divisibility: for hidden_size in HIDDEN_SIZES: all_hidden_size.append(hidden_size // div) HIDDEN_SIZES = list(set(all_hidden_size)) # Test params that focuses on hidden_size variation. hs_test_params = { "hidden_sizes": HIDDEN_SIZES, "batches": [4], "num_loras": [4], "max_ranks": [32], } # General tests params that tests for variations in all dimensions # except hidden_size. test_params = { "hidden_sizes": [2049], "batches": [1, 4, 16, 32], "num_loras": [1, 8, 32, 128], "max_ranks": [1, 4, 8, 16, 32, 64, 128, 256], } DTYPES = [torch.float16, torch.bfloat16] DEVICES = [f"cuda:{0}"] SEED = [0] @pytest.mark.parametrize("batches", test_params["batches"]) @pytest.mark.parametrize("num_loras", test_params["num_loras"]) @pytest.mark.parametrize("rank", test_params["max_ranks"]) @pytest.mark.parametrize("hidden_size", test_params["hidden_sizes"]) @pytest.mark.parametrize("nslices", [1, 2, 3]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("seed", SEED) @pytest.mark.parametrize("op_type", ["shrink", "expand"]) def test_kernels( batches: int, num_loras: int, rank: int, hidden_size: int, nslices: int, dtype: torch.dtype, device: str, seed: int, op_type: str, ): """ Tests LoRA kernels. """ torch.set_default_device(device) current_platform.seed_everything(seed) if op_type == "shrink": check_lora_shrink_kernel( batches=batches, num_loras=num_loras, rank=rank, hidden_size=hidden_size, nslices=nslices, dtype=dtype, device=device, seq_length=128, scaling=0.5, ) else: check_lora_expand_kernel( batches=batches, num_loras=num_loras, rank=rank, hidden_size=hidden_size, nslices=nslices, dtype=dtype, device=device, seq_length=128, add_inputs=True, ) @pytest.mark.parametrize("batches", hs_test_params["batches"]) @pytest.mark.parametrize("num_loras", hs_test_params["num_loras"]) @pytest.mark.parametrize("rank", hs_test_params["max_ranks"]) @pytest.mark.parametrize("hidden_size", hs_test_params["hidden_sizes"]) @pytest.mark.parametrize("nslices", [1, 2, 3]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("seed", SEED) @pytest.mark.parametrize("op_type", ["shrink", "expand"]) def test_kernels_hidden_size( batches: int, num_loras: int, rank: int, hidden_size: int, nslices: int, dtype: torch.dtype, device: str, seed: int, op_type: str, ): """ Tests SGMV and LoRA kernels. """ torch.set_default_device(device) current_platform.seed_everything(seed) if op_type == "shrink": check_lora_shrink_kernel( batches=batches, num_loras=num_loras, rank=rank, hidden_size=hidden_size, nslices=nslices, dtype=dtype, device=device, seq_length=128, scaling=0.5, ) else: check_lora_expand_kernel( batches=batches, num_loras=num_loras, rank=rank, hidden_size=hidden_size, nslices=nslices, dtype=dtype, device=device, seq_length=128, add_inputs=True, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_qwen3moe_tp.py
tests/lora/test_qwen3moe_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # NOTE To avoid overloading the CI pipeline, this test script will not # be triggered on CI and is primarily intended for local testing and verification. import vllm from vllm.lora.request import LoRARequest from ..utils import multi_gpu_test MODEL_PATH = "Qwen/Qwen3-30B-A3B" PROMPT_TEMPLATE = """<|im_start|>user I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request. " ##Instruction: candidate_poll contains tables such as candidate, people. Table candidate has columns such as Candidate_ID, People_ID, Poll_Source, Date, Support_rate, Consider_rate, Oppose_rate, Unsure_rate. Candidate_ID is the primary key. Table people has columns such as People_ID, Sex, Name, Date_of_Birth, Height, Weight. People_ID is the primary key. The People_ID of candidate is the foreign key of People_ID of people. ###Input: {context} ###Response:<|im_end|> <|im_start|>assistant""" # noqa: E501 EXPECTED_LORA_OUTPUT = [ "<think>\n\n</think>\n\nSELECT count(*) FROM candidate", "<think>\n\n</think>\n\nSELECT count(*) FROM candidate", "<think>\n\n</think>\n\nSELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1", # noqa: E501 "<think>\n\n</think>\n\nSELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1", # noqa: E501 ] def generate_and_test(llm: vllm.LLM, lora_path: str, lora_id: int) -> None: prompts = [ PROMPT_TEMPLATE.format(context="How many candidates are there?"), PROMPT_TEMPLATE.format(context="Count the number of candidates."), PROMPT_TEMPLATE.format( context="Which poll resource provided the most number of candidate information?" # noqa: E501 ), PROMPT_TEMPLATE.format( context="Return the poll resource associated with the most candidates." ), ] sampling_params = vllm.SamplingParams(temperature=0, max_tokens=64) outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") for i in range(len(EXPECTED_LORA_OUTPUT)): assert generated_texts[i].startswith(EXPECTED_LORA_OUTPUT[i]) def test_qwen3moe_lora(qwen3moe_lora_files): # We enable enforce_eager=True here to reduce VRAM usage for lora-test CI, # Otherwise, the lora-test will fail due to CUDA OOM. llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, ) generate_and_test(llm, qwen3moe_lora_files, lora_id=1) generate_and_test(llm, qwen3moe_lora_files, lora_id=2) @multi_gpu_test(num_gpus=2) def test_qwen3moe_lora_tp2(qwen3moe_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, tensor_parallel_size=2, ) generate_and_test(llm, qwen3moe_lora_files, lora_id=1) generate_and_test(llm, qwen3moe_lora_files, lora_id=2) @multi_gpu_test(num_gpus=4) def test_qwen3moe_lora_tp4(qwen3moe_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, tensor_parallel_size=4, ) generate_and_test(llm, qwen3moe_lora_files, lora_id=1) generate_and_test(llm, qwen3moe_lora_files, lora_id=2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_add_lora.py
tests/lora/test_add_lora.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import asyncio import time import pytest from vllm.engine.arg_utils import AsyncEngineArgs from vllm.entrypoints.openai.api_server import ( build_async_engine_client_from_engine_args, ) from vllm.inputs import TextPrompt from vllm.lora.request import LoRARequest from vllm.sampling_params import SamplingParams from vllm.utils.async_utils import merge_async_iterators MODEL_PATH = "zai-org/chatglm3-6b" LORA_RANK = 64 DEFAULT_MAX_LORAS = 4 * 3 def get_lora_requests(lora_path) -> list[LoRARequest]: lora_requests: list[LoRARequest] = [ LoRARequest(lora_name=f"{i}", lora_int_id=i, lora_path=lora_path) for i in range(1, DEFAULT_MAX_LORAS + 1) ] return lora_requests async def requests_processing_time(llm, lora_requests: list[LoRARequest]) -> float: sampling_params = SamplingParams( n=1, temperature=0.0, top_p=1.0, ignore_eos=True, max_tokens=1 ) generators = [] start = time.perf_counter() for lora_request in lora_requests: lora_int_id = lora_request.lora_int_id generator = llm.generate( prompt=TextPrompt(prompt=f"hello {lora_int_id}", multi_modal_data=None), # type: ignore sampling_params=sampling_params, lora_request=lora_request, request_id=f"test{lora_int_id}", ) generators.append(generator) all_gens = merge_async_iterators(*generators) async for i, res in all_gens: pass end = time.perf_counter() return end - start @pytest.mark.asyncio async def test_add_lora(chatglm3_lora_files): """ The add_lora function is used to preload some LoRA adapters into the engine in anticipation of future requests using these adapters. To test this functionality, we use the async engine to process some requests - We do it twice, once with add_lora() preloading and once without. We measure the request processing time in both cases and expect the time to be lesser in the case with add_lora() calls. """ lora_requests: list[LoRARequest] = get_lora_requests(chatglm3_lora_files) max_loras = len(set([lr.lora_int_id for lr in lora_requests])) # Create engine in eager-mode. Due to high max_loras, the CI can # OOM during cuda-graph capture. engine_args = AsyncEngineArgs( model=MODEL_PATH, enable_lora=True, max_loras=max_loras, max_lora_rank=LORA_RANK, max_model_len=128, gpu_memory_utilization=0.8, # avoid OOM trust_remote_code=True, enforce_eager=True, ) # split lora_requests into 3 parts part_size = len(lora_requests) // 3 dummy_run_requests = lora_requests[:part_size] warmup_run_requests = lora_requests[part_size : part_size * 2] cold_run_requests = lora_requests[part_size * 2 :] async with build_async_engine_client_from_engine_args(engine_args) as llm: # Dummy run - So any 1-time functionality like triton kernel compilation # is complete here. await requests_processing_time(llm, dummy_run_requests) # Run with warmup add_lora_tasks = [llm.add_lora(lr) for lr in warmup_run_requests] add_lora_results = await asyncio.gather(*add_lora_tasks) # Test that all all_lora calls are successful. assert all(add_lora_results) time_with_add_lora = await requests_processing_time(llm, warmup_run_requests) # Run without any warmup time_cold_start = await requests_processing_time(llm, cold_run_requests) print(f"time hot-start {time_with_add_lora} vs time cold-start {time_cold_start} ") assert time_with_add_lora < time_cold_start, ( f"time_with_add_lora={time_with_add_lora}, " f"time_cold_start={time_cold_start}" "The engine request processing time with LoRA pre-loading " "must be less than the version that does on-demand LoRA loading." )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_quant_model.py
tests/lora/test_quant_model.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Adapted from # https://github.com/fmmoret/vllm/blob/fm-support-lora-on-quantized-models/tests/lora/test_llama.py from dataclasses import dataclass import pytest import vllm from vllm.distributed import cleanup_dist_env_and_memory from vllm.lora.request import LoRARequest from vllm.platforms import current_platform @dataclass class ModelWithQuantization: model_path: str quantization: str MODELS: list[ModelWithQuantization] # AWQ quantization is currently not supported in ROCm. if current_platform.is_rocm(): MODELS = [ ModelWithQuantization( model_path="TheBloke/TinyLlama-1.1B-Chat-v0.3-GPTQ", quantization="gptq" ), ] else: MODELS = [ ModelWithQuantization( model_path="TheBloke/TinyLlama-1.1B-Chat-v0.3-AWQ", quantization="awq" ), ModelWithQuantization( model_path="TheBloke/TinyLlama-1.1B-Chat-v0.3-GPTQ", quantization="gptq" ), ] def do_sample( llm: vllm.LLM, lora_path: str, lora_id: int, max_tokens: int = 256 ) -> list[str]: raw_prompts = [ "Give me an orange-ish brown color", "Give me a neon pink color", ] def format_prompt_tuples(prompt): return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" prompts = [format_prompt_tuples(p) for p in raw_prompts] sampling_params = vllm.SamplingParams( temperature=0, max_tokens=max_tokens, stop=["<|im_end|>"] ) outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") return generated_texts @pytest.mark.parametrize("model", MODELS) def test_quant_model_lora(tinyllama_lora_files, model): llm = vllm.LLM( model=model.model_path, enable_lora=True, max_num_seqs=16, max_loras=4, max_model_len=400, gpu_memory_utilization=0.2, # avoid OOM quantization=model.quantization, trust_remote_code=True, enable_chunked_prefill=True, tokenizer=tinyllama_lora_files, ) if model.quantization is None: expected_lora_output = [ "#ff8050", "#ff8080", ] elif model.quantization == "awq": expected_lora_output = [ "#f07700: A v", "#f00000: A v", ] elif model.quantization == "gptq": expected_lora_output = [ "#f08800: This is", "#f07788 \n#", ] def expect_match(output, expected_output): # HACK: GPTQ lora outputs are just incredibly unstable. # Assert that the outputs changed. if model.quantization == "gptq" and expected_output is expected_lora_output: for i, o in enumerate(output): assert o.startswith("#"), ( f"Expected example {i} to start with # but got {o}" ) return assert output == expected_output max_tokens = 10 print("lora adapter created") print("lora 1") output = do_sample(llm, tinyllama_lora_files, lora_id=1, max_tokens=max_tokens) expect_match(output, expected_lora_output) print("lora 2") output = do_sample(llm, tinyllama_lora_files, lora_id=2, max_tokens=max_tokens) expect_match(output, expected_lora_output) print("removing lora") del llm cleanup_dist_env_and_memory() @pytest.mark.parametrize("model", MODELS) def test_quant_model_tp_equality(tinyllama_lora_files, num_gpus_available, model): if num_gpus_available < 2: pytest.skip(f"Not enough GPUs for tensor parallelism {2}") if model.quantization == "gptq": pytest.skip("GPTQ lora outputs are just incredibly unstable") llm_tp1 = vllm.LLM( model=model.model_path, enable_lora=True, max_num_seqs=16, max_loras=4, gpu_memory_utilization=0.2, # avoid OOM quantization=model.quantization, trust_remote_code=True, enable_chunked_prefill=True, ) output_tp1 = do_sample(llm_tp1, tinyllama_lora_files, lora_id=1) del llm_tp1 cleanup_dist_env_and_memory() llm_tp2 = vllm.LLM( model=model.model_path, enable_lora=True, max_num_seqs=16, max_loras=4, tensor_parallel_size=2, gpu_memory_utilization=0.2, # avoid OOM quantization=model.quantization, enable_chunked_prefill=True, ) output_tp2 = do_sample(llm_tp2, tinyllama_lora_files, lora_id=1) del llm_tp2 cleanup_dist_env_and_memory() assert output_tp1 == output_tp2
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/conftest.py
tests/lora/conftest.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import tempfile from collections import OrderedDict from unittest.mock import MagicMock import pytest import torch import torch.nn as nn from huggingface_hub import snapshot_download from vllm.distributed import ( cleanup_dist_env_and_memory, init_distributed_environment, initialize_model_parallel, ) from vllm.model_executor.layers.linear import ( ColumnParallelLinear, MergedColumnParallelLinear, RowParallelLinear, ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead from vllm.model_executor.models.interfaces import SupportsLoRA from vllm.platforms import current_platform @pytest.fixture() def should_do_global_cleanup_after_test(request) -> bool: """Allow subdirectories to skip global cleanup by overriding this fixture. This can provide a ~10x speedup for non-GPU unit tests since they don't need to initialize torch. """ return not request.node.get_closest_marker("skip_global_cleanup") @pytest.fixture(autouse=True) def cleanup_fixture(should_do_global_cleanup_after_test: bool): yield if should_do_global_cleanup_after_test: cleanup_dist_env_and_memory(shutdown_ray=True) @pytest.fixture def dist_init(): temp_file = tempfile.mkstemp()[1] backend = "nccl" if current_platform.is_cpu() or current_platform.is_tpu(): backend = "gloo" init_distributed_environment( world_size=1, rank=0, distributed_init_method=f"file://{temp_file}", local_rank=0, backend=backend, ) initialize_model_parallel(1, 1) yield cleanup_dist_env_and_memory(shutdown_ray=True) @pytest.fixture def dist_init_torch_only(): if torch.distributed.is_initialized(): return backend = "nccl" if current_platform.is_cpu(): backend = "gloo" temp_file = tempfile.mkstemp()[1] torch.distributed.init_process_group( world_size=1, rank=0, init_method=f"file://{temp_file}", backend=backend ) class DummyLoRAModel(nn.Sequential, SupportsLoRA): pass @pytest.fixture def dummy_model() -> nn.Module: model = DummyLoRAModel( OrderedDict( [ ("dense1", ColumnParallelLinear(764, 100)), ("dense2", RowParallelLinear(100, 50)), ( "layer1", nn.Sequential( OrderedDict( [ ("dense1", ColumnParallelLinear(100, 10)), ("dense2", RowParallelLinear(10, 50)), ] ) ), ), ("act2", nn.ReLU()), ("output", ColumnParallelLinear(50, 10)), ("outact", nn.Sigmoid()), # Special handling for lm_head & sampler ("lm_head", ParallelLMHead(512, 10)), ("logits_processor", LogitsProcessor(512)), ] ) ) model.config = MagicMock() model.embedding_modules = {"lm_head": "lm_head"} model.unpadded_vocab_size = 32000 return model @pytest.fixture def dummy_model_gate_up() -> nn.Module: model = DummyLoRAModel( OrderedDict( [ ("dense1", ColumnParallelLinear(764, 100)), ("dense2", RowParallelLinear(100, 50)), ( "layer1", nn.Sequential( OrderedDict( [ ("dense1", ColumnParallelLinear(100, 10)), ("dense2", RowParallelLinear(10, 50)), ] ) ), ), ("act2", nn.ReLU()), ("gate_up_proj", MergedColumnParallelLinear(50, [5, 5])), ("outact", nn.Sigmoid()), # Special handling for lm_head & sampler ("lm_head", ParallelLMHead(512, 10)), ("logits_processor", LogitsProcessor(512)), ] ) ) model.config = MagicMock() model.packed_modules_mapping = { "gate_up_proj": [ "gate_proj", "up_proj", ], } model.embedding_modules = {"lm_head": "lm_head"} model.unpadded_vocab_size = 32000 return model @pytest.fixture(scope="session") def mixtral_lora_files(): # Note: this module has incorrect adapter_config.json to test # https://github.com/vllm-project/vllm/pull/5909/files. return snapshot_download(repo_id="SangBinCho/mixtral-lora") @pytest.fixture(scope="session") def chatglm3_lora_files(): return snapshot_download(repo_id="jeeejeee/chatglm3-text2sql-spider") @pytest.fixture(scope="session") def baichuan_lora_files(): return snapshot_download(repo_id="jeeejeee/baichuan7b-text2sql-spider") @pytest.fixture(scope="session") def baichuan_zero_lora_files(): # all the lora_B weights are initialized to zero. return snapshot_download(repo_id="jeeejeee/baichuan7b-zero-init") @pytest.fixture(scope="session") def baichuan_regex_lora_files(): return snapshot_download(repo_id="jeeejeee/baichuan-7b-lora-zero-regex") @pytest.fixture(scope="session") def ilama_lora_files(): return snapshot_download(repo_id="jeeejeee/ilama-text2sql-spider") @pytest.fixture(scope="session") def minicpmv_lora_files(): return snapshot_download(repo_id="jeeejeee/minicpmv25-lora-pokemon") @pytest.fixture(scope="session") def qwen2vl_lora_files(): return snapshot_download(repo_id="jeeejeee/qwen2-vl-lora-pokemon") @pytest.fixture(scope="session") def qwen25vl_base_huggingface_id(): # used as a base model for testing with qwen25vl lora adapter return "Qwen/Qwen2.5-VL-3B-Instruct" @pytest.fixture(scope="session") def qwen25vl_lora_files(): return snapshot_download(repo_id="jeeejeee/qwen25-vl-lora-pokemon") @pytest.fixture(scope="session") def qwen2vl_language_lora_files(): return snapshot_download(repo_id="prashanth058/qwen2vl-flickr-lora-language") @pytest.fixture(scope="session") def qwen2vl_vision_tower_connector_lora_files(): return snapshot_download(repo_id="prashanth058/qwen2vl-flickr-lora-tower-connector") @pytest.fixture(scope="session") def qwen2vl_vision_tower_lora_files(): return snapshot_download(repo_id="prashanth058/qwen2vl-flickr-lora-tower") @pytest.fixture(scope="session") def qwen25vl_vision_lora_files(): return snapshot_download(repo_id="EpochEcho/qwen2.5-3b-vl-lora-vision-connector") @pytest.fixture(scope="session") def qwen3vl_vision_lora_files(): return snapshot_download(repo_id="EpochEcho/qwen3-4b-vl-lora-vision-connector") @pytest.fixture(scope="session") def tinyllama_lora_files(): return snapshot_download(repo_id="jashing/tinyllama-colorist-lora") @pytest.fixture(scope="session") def deepseekv2_lora_files(): return snapshot_download(repo_id="wuchen01/DeepSeek-V2-Lite-Chat-All-LoRA") @pytest.fixture(scope="session") def gptoss20b_lora_files(): return snapshot_download(repo_id="jeeejeee/gpt-oss-20b-lora-adapter-text2sql") @pytest.fixture(scope="session") def qwen3moe_lora_files(): return snapshot_download(repo_id="jeeejeee/qwen3-moe-text2sql-spider") @pytest.fixture(scope="session") def olmoe_lora_files(): return snapshot_download(repo_id="jeeejeee/olmoe-instruct-text2sql-spider") @pytest.fixture(scope="session") def qwen3_lora_files(): return snapshot_download(repo_id="charent/self_cognition_Alice") @pytest.fixture(scope="session") def llama32_lora_huggingface_id(): # huggingface repo id is used to test lora runtime downloading. return "jeeejeee/llama32-3b-text2sql-spider" @pytest.fixture(scope="session") def llama32_lora_files(llama32_lora_huggingface_id): return snapshot_download(repo_id=llama32_lora_huggingface_id) @pytest.fixture def reset_default_device(): """ Some tests, such as `test_punica_ops.py`, explicitly set the default device, which can affect subsequent tests. Adding this fixture helps avoid this problem. """ original_device = torch.get_default_device() yield torch.set_default_device(original_device)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/utils.py
tests/lora/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import json import os from dataclasses import dataclass import torch from safetensors.torch import save_file from vllm.lora.lora_weights import LoRALayerWeights, PackedLoRALayerWeights class DummyLoRAManager: def __init__(self, device: torch.device = "cuda:0"): super().__init__() self._loras: dict[str, LoRALayerWeights] = {} self._device = device def set_module_lora(self, module_name: str, lora: LoRALayerWeights): self._loras[module_name] = lora def get_module_lora(self, module_name: str) -> LoRALayerWeights: return self._loras[module_name] def init_random_lora( self, module_name: str, weight: torch.Tensor, rank: int = 8, ): lora = LoRALayerWeights( module_name, rank=rank, lora_alpha=1, lora_a=torch.rand( [rank, weight.shape[1]], dtype=weight.dtype, device=self._device ), lora_b=torch.rand( [weight.shape[0], rank], dtype=weight.dtype, device=self._device ), ) self.set_module_lora(module_name, lora) return lora def init_lora( self, module_name: str, input_dim: int, output_dim: int, rank=8, noop=False, embeddings_tensor=None, ): lora = LoRALayerWeights( module_name, rank=rank, lora_alpha=1, lora_a=torch.rand([rank, input_dim], device="cuda"), lora_b=torch.rand([output_dim, input_dim], device="cuda"), embeddings_tensor=embeddings_tensor, ) self.set_module_lora(module_name, lora) return lora def reset_lora(self): self._loras = {} def init_packed_lora( self, module_name: str, input_dim: int, output_dims: list[int], noop_lora_index: list[int] | None = None, rank: int = 8, ): base_loras: list[LoRALayerWeights] = [] noop_lora_index_set = set(noop_lora_index or []) for i, out_dim in enumerate(output_dims): base_lora = self.init_lora( module_name + "_000_" + str(i), input_dim, out_dim, rank=rank, noop=i in noop_lora_index_set, ) base_loras.append(base_lora) packed_lora = PackedLoRALayerWeights.pack(base_loras) self.set_module_lora(module_name, packed_lora) return packed_lora def assert_close(a, b): rtol, atol = { torch.float16: (6e-2, 6e-2), torch.bfloat16: (6e-2, 6e-2), torch.float32: (1e-2, 1e-2), }[a.dtype] torch.testing.assert_close(a, b, rtol=rtol, atol=atol) @dataclass class PunicaTensors: inputs_tensor: torch.Tensor lora_weights: torch.Tensor | list[torch.Tensor] our_out_tensor: torch.Tensor ref_out_tensor: torch.Tensor b_seq_start_loc: torch.Tensor prompt_lora_mapping: torch.Tensor seq_len_tensor: torch.Tensor token_lora_mapping: torch.Tensor def meta(self) -> tuple[int, int]: """ Infer max_seq_length and token_nums from the tensors and return them. """ max_seq_length = self.seq_len_tensor.max() token_nums = self.seq_len_tensor.sum().item() if isinstance(max_seq_length, tuple): max_seq_length = max_seq_length[0].item() else: max_seq_length = max_seq_length.item() return max_seq_length, token_nums def generate_data( batches, hidden_size, lora_nums, max_rank, seq_length, dtype, op_type, device, ) -> PunicaTensors: seq_len_tensor = torch.randint(seq_length, seq_length + 1, (batches,)).to(device) b_seq_start_loc = torch.cumsum( torch.tensor([0] + seq_len_tensor[:-1].tolist(), dtype=torch.long), dim=0, ).to(device) total_tokens = seq_len_tensor.sum() if op_type == "shrink": inputs_tensor = torch.rand((total_tokens, hidden_size), dtype=dtype).to(device) lora_weights = torch.rand( (lora_nums, max_rank, hidden_size), # col-major dtype=dtype, ).to(device) # shrink op need atomic_add, so output is initinized by 0 ref_out_tensor = torch.zeros( (total_tokens, max_rank), dtype=dtype, device=inputs_tensor.device ) # NOTE shrink kernel using torch.float32 as output type our_out_tensor = torch.zeros((total_tokens, max_rank), dtype=torch.float32).to( device ) else: inputs_tensor = torch.rand( (total_tokens, max_rank), dtype=dtype, ).to(device) lora_weights = torch.rand( (lora_nums, hidden_size, max_rank), # col-major dtype=dtype, ).to(device) # expand op needs to complete y+=a@lora_b, so output is # initinized randomly ref_out_tensor = torch.rand( (total_tokens, hidden_size), dtype=dtype, ).to(device) # Ensure the same input. our_out_tensor = ref_out_tensor.clone() lora_indices_tensor = torch.randint( 0, lora_nums - 1 if lora_nums > 1 else 1, (batches,) ).to(device) indices = torch.zeros((total_tokens), dtype=torch.long).to(device) current_offset = 0 for b_id in range(batches): lora_index = lora_indices_tensor[b_id] indices[current_offset : current_offset + seq_len_tensor[b_id]].copy_( lora_index ) current_offset += seq_len_tensor[b_id].item() return PunicaTensors( inputs_tensor, lora_weights, our_out_tensor, ref_out_tensor, b_seq_start_loc, lora_indices_tensor, seq_len_tensor, indices, ) def generate_data_for_expand_nslices( batches, hidden_size, lora_nums, max_rank, seq_length, dtype, nslices, device, ) -> PunicaTensors: seq_len_tensor = torch.randint(seq_length, seq_length + 1, (batches,)).to(device) b_seq_start_loc = torch.cumsum( torch.tensor([0] + seq_len_tensor[:-1].tolist(), dtype=torch.long), dim=0, ).to(device) total_tokens = seq_len_tensor.sum() inputs_tensor = torch.rand( (total_tokens, max_rank), dtype=dtype, ).to(device) lora_weights_lst = [] for _ in range(nslices): lora_weights_lst.append( torch.rand( (lora_nums, hidden_size, max_rank), # col-major dtype=dtype, ).to(device) ) # expand op needs to complete y+=a@lora_b, so output is # initinized randomly ref_out_tensor = torch.rand((total_tokens, hidden_size * nslices), dtype=dtype).to( device ) # Ensure the same input. our_out_tensor = ref_out_tensor.clone() lora_indices_tensor = torch.randint( 0, lora_nums - 1 if lora_nums > 1 else 1, (batches,) ) indices = torch.zeros((total_tokens), dtype=torch.long).to(device) current_offset = 0 for b_id in range(batches): lora_index = lora_indices_tensor[b_id] indices[current_offset : current_offset + seq_len_tensor[b_id]] = ( lora_index.item() ) current_offset += seq_len_tensor[b_id].item() lora_indices_tensor = lora_indices_tensor.to(device) return PunicaTensors( inputs_tensor, lora_weights_lst, our_out_tensor, ref_out_tensor, b_seq_start_loc, lora_indices_tensor, seq_len_tensor, indices, ) def generate_data_for_nslices( batches, hidden_size, lora_nums, max_rank, seq_length, nslices, dtype, op_type, device, ) -> PunicaTensors: seq_len_tensor = torch.randint(seq_length, seq_length + 1, (batches,)).to(device) b_seq_start_loc = torch.cumsum( torch.tensor([0] + seq_len_tensor[:-1].tolist(), dtype=torch.long), dim=0, ).to(device) total_tokens = seq_len_tensor.sum() lora_weights_lst = [] if op_type == "shrink": inputs_tensor = torch.rand((total_tokens, hidden_size), dtype=dtype).to(device) for _ in range(nslices): if op_type == "shrink": lora_weights_lst.append( torch.rand( (lora_nums, max_rank, hidden_size), # col-major dtype=dtype, ).to(device) ) # NOTE shrink kernel using torch.float32 as output type # shrink op need atomic_add, so output is initinized by 0 our_out_tensor = torch.zeros( (nslices, total_tokens, max_rank), dtype=torch.float32, ).to(device) else: inputs_tensor = torch.rand( (nslices, total_tokens, max_rank), dtype=dtype, ).to(device) for _ in range(nslices): lora_weights_lst.append( torch.rand( (lora_nums, hidden_size, max_rank), # col-major dtype=dtype, ).to(device) ) # expand op needs to complete y+=a@lora_b, so output is # initinized randomly our_out_tensor = torch.rand( (total_tokens, hidden_size * nslices), dtype=dtype ).to(device) # Ensure the same input. ref_out_tensor = our_out_tensor.clone() lora_indices_tensor = torch.randint( 0, lora_nums - 1 if lora_nums > 1 else 1, (batches,) ) indices = torch.zeros((total_tokens), dtype=torch.long).to(device) current_offset = 0 for b_id in range(batches): lora_index = lora_indices_tensor[b_id] indices[current_offset : current_offset + seq_len_tensor[b_id]] = ( lora_index.item() ) current_offset += seq_len_tensor[b_id].item() lora_indices_tensor = lora_indices_tensor.to(device) return PunicaTensors( inputs_tensor, lora_weights_lst, our_out_tensor, ref_out_tensor, b_seq_start_loc, lora_indices_tensor, seq_len_tensor, indices, ) def create_peft_lora( model: torch.nn.Module, save_dir: str, target_modules: list[str], rank: int = 8, alpha: int = 16, dropout: float = 0.1, lora_dtype: torch.dtype = torch.float16, ) -> dict[str, torch.Tensor]: lora_weights = {} adapter_config = { "peft_type": "LORA", "auto_mapping": None, "base_model_name_or_path": "dummy_model", "revision": None, "task_type": "CAUSAL_LM", "inference_mode": False, "r": rank, "lora_alpha": alpha, "lora_dropout": dropout, "fan_in_fan_out": False, "bias": "none", "modules_to_save": None, "init_lora_weights": True, "layers_to_transform": None, "layers_pattern": None, "target_modules": target_modules, "exclude_modules": None, "use_rslora": False, "use_dora": False, "loftq_config": None, } for module_name in target_modules: module = model for attr in module_name.split("."): module = getattr(module, attr) if hasattr(module, "input_size") and hasattr(module, "output_size"): in_features = module.input_size out_features = module.output_size elif hasattr(module, "embedding_dim") and hasattr(module, "num_embeddings"): # ParallelLMHead in_features = module.embedding_dim out_features = module.num_embeddings else: raise ValueError(f"Unable to determine dimensions for module {module_name}") lora_A = torch.randn(rank, in_features, dtype=lora_dtype) torch.nn.init.kaiming_uniform_(lora_A, a=5**0.5) lora_B = torch.zeros(out_features, rank, dtype=lora_dtype) # PEFT style lora_weights[f"base_model.model.{module_name}.lora_A.weight"] = lora_A lora_weights[f"base_model.model.{module_name}.lora_B.weight"] = lora_B config_path = os.path.join(save_dir, "adapter_config.json") with open(config_path, "w", encoding="utf-8") as f: json.dump(adapter_config, f, indent=2, ensure_ascii=False) weights_path = os.path.join(save_dir, "adapter_model.safetensors") save_file(lora_weights, weights_path) return lora_weights
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_olmoe_tp.py
tests/lora/test_olmoe_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import vllm from vllm.lora.request import LoRARequest from ..utils import multi_gpu_test MODEL_PATH = "allenai/OLMoE-1B-7B-0125-Instruct" PROMPT_TEMPLATE = """I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request. " ##Instruction: candidate_poll contains tables such as candidate, people. Table candidate has columns such as Candidate_ID, People_ID, Poll_Source, Date, Support_rate, Consider_rate, Oppose_rate, Unsure_rate. Candidate_ID is the primary key. Table people has columns such as People_ID, Sex, Name, Date_of_Birth, Height, Weight. People_ID is the primary key. The People_ID of candidate is the foreign key of People_ID of people. ###Input: {context} ###Response:""" # noqa: E501 EXPECTED_LORA_OUTPUT = [ "SELECT count(*) FROM candidate", "SELECT count(*) FROM candidate", "SELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1", # noqa: E501 "SELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1", # noqa: E501 ] EXPECTED_BASE_MODEL_OUTPUT = [ "SELECT COUNT(Candidate_ID) FROM candidate", "SELECT COUNT(Candidate_ID) FROM candidate", "SELECT Candidate_ID, COUNT(*) as Total_Candidates\nFROM candidate\nINNER JOIN people ON candidate.People_ID = people.People_ID", # noqa: E501 "SELECT Candidate_ID, Poll_Source FROM candidate WHERE People_ID IN (SELECT People_ID FROM people) ORDER BY COUNT(*) DESC LIMIT 1", # noqa: E501 ] def generate_and_test( llm: vllm.LLM, lora_path: str, lora_id: list[int | None] | int | None, compare_lower: bool = False, ) -> None: prompts = [ PROMPT_TEMPLATE.format(context="How many candidates are there?"), PROMPT_TEMPLATE.format(context="Count the number of candidates."), PROMPT_TEMPLATE.format( context="Which poll resource provided the most number of candidate information?" # noqa: E501 ), PROMPT_TEMPLATE.format( context="Return the poll resource associated with the most candidates." ), ] lora_request = None if isinstance(lora_id, int): lora_request = LoRARequest(str(lora_id), lora_id, lora_path) elif isinstance(lora_id, list): lora_request = [ LoRARequest(str(i), i, lora_path) if i is not None else None for i in lora_id ] sampling_params = vllm.SamplingParams(temperature=0, max_tokens=64) outputs = llm.generate(prompts, sampling_params, lora_request=lora_request) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") for i in range(len(EXPECTED_LORA_OUTPUT)): req_lora_id = lora_id[i] if isinstance(lora_id, list) else lora_id generated_text = generated_texts[i] expected_output = ( EXPECTED_LORA_OUTPUT[i] if req_lora_id is not None else EXPECTED_BASE_MODEL_OUTPUT[i] ) if compare_lower: generated_text = generated_text.lower() expected_output = expected_output.lower() assert generated_text.startswith(expected_output) def test_olmoe_lora(olmoe_lora_files): # We enable enforce_eager=True here to reduce VRAM usage for lora-test CI, # Otherwise, the lora-test will fail due to CUDA OOM. llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, ) generate_and_test(llm, olmoe_lora_files, lora_id=1) generate_and_test(llm, olmoe_lora_files, lora_id=2) def test_olmoe_lora_mixed(olmoe_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, ) generate_and_test(llm, olmoe_lora_files, lora_id=[1, None, 3, None]) @pytest.mark.parametrize("fully_sharded_loras", [False, True]) @multi_gpu_test(num_gpus=2) def test_olmoe_lora_tp2(olmoe_lora_files, fully_sharded_loras): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, tensor_parallel_size=2, fully_sharded_loras=fully_sharded_loras, ) generate_and_test(llm, olmoe_lora_files, lora_id=1) generate_and_test(llm, olmoe_lora_files, lora_id=2) @pytest.mark.parametrize("fully_sharded_loras", [False, True]) @multi_gpu_test(num_gpus=4) def test_olmoe_lora_tp4(olmoe_lora_files, fully_sharded_loras): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, tensor_parallel_size=4, fully_sharded_loras=fully_sharded_loras, ) generate_and_test( llm, olmoe_lora_files, lora_id=1, compare_lower=fully_sharded_loras ) generate_and_test( llm, olmoe_lora_files, lora_id=2, compare_lower=fully_sharded_loras )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_transformers_model.py
tests/lora/test_transformers_model.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import vllm from vllm.lora.request import LoRARequest from vllm.platforms import current_platform from ..utils import create_new_process_for_each_test, multi_gpu_test MODEL_PATH = "hmellor/Ilama-3.2-1B" PROMPT_TEMPLATE = """I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request.\n"\n##Instruction:\nconcert_singer contains tables such as stadium, singer, concert, singer_in_concert. Table stadium has columns such as Stadium_ID, Location, Name, Capacity, Highest, Lowest, Average. Stadium_ID is the primary key.\nTable singer has columns such as Singer_ID, Name, Country, Song_Name, Song_release_year, Age, Is_male. Singer_ID is the primary key.\nTable concert has columns such as concert_ID, concert_Name, Theme, Stadium_ID, Year. concert_ID is the primary key.\nTable singer_in_concert has columns such as concert_ID, Singer_ID. concert_ID is the primary key.\nThe Stadium_ID of concert is the foreign key of Stadium_ID of stadium.\nThe Singer_ID of singer_in_concert is the foreign key of Singer_ID of singer.\nThe concert_ID of singer_in_concert is the foreign key of concert_ID of concert.\n\n###Input:\n{query}\n\n###Response:""" # noqa: E501 EXPECTED_LORA_OUTPUT = [ "SELECT count(*) FROM singer", "SELECT avg(age) , min(age) , max(age) FROM singer WHERE country = 'France'", # noqa: E501 "SELECT DISTINCT Country FROM singer WHERE Age > 20", ] def do_sample(llm: vllm.LLM, lora_path: str, lora_id: int) -> list[str]: prompts = [ PROMPT_TEMPLATE.format(query="How many singers do we have?"), PROMPT_TEMPLATE.format( query="What is the average, minimum, and maximum age of all singers from France?" # noqa: E501 ), PROMPT_TEMPLATE.format( query="What are all distinct countries where singers above age 20 are from?" # noqa: E501 ), ] sampling_params = vllm.SamplingParams(temperature=0, max_tokens=32) outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") return generated_texts def test_ilama_lora(ilama_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, max_lora_rank=16, trust_remote_code=True, enable_chunked_prefill=True, ) output1 = do_sample(llm, ilama_lora_files, lora_id=1) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output1[i] == EXPECTED_LORA_OUTPUT[i] output2 = do_sample(llm, ilama_lora_files, lora_id=2) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output2[i] == EXPECTED_LORA_OUTPUT[i] @pytest.mark.skipif( current_platform.is_cuda_alike(), reason="Skipping to avoid redundant model tests" ) @multi_gpu_test(num_gpus=4) @create_new_process_for_each_test() def test_ilama_lora_tp4(ilama_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, max_lora_rank=16, tensor_parallel_size=4, trust_remote_code=True, fully_sharded_loras=False, enable_chunked_prefill=True, ) output1 = do_sample(llm, ilama_lora_files, lora_id=1) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output1[i] == EXPECTED_LORA_OUTPUT[i] output2 = do_sample(llm, ilama_lora_files, lora_id=2) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output2[i] == EXPECTED_LORA_OUTPUT[i] @pytest.mark.skipif( current_platform.is_cuda_alike(), reason="Skipping to avoid redundant model tests" ) @multi_gpu_test(num_gpus=4) @create_new_process_for_each_test() def test_ilama_lora_tp4_fully_sharded_loras(ilama_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, max_lora_rank=16, tensor_parallel_size=4, trust_remote_code=True, fully_sharded_loras=True, enable_chunked_prefill=True, ) output1 = do_sample(llm, ilama_lora_files, lora_id=1) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output1[i] == EXPECTED_LORA_OUTPUT[i] output2 = do_sample(llm, ilama_lora_files, lora_id=2) for i in range(len(EXPECTED_LORA_OUTPUT)): assert output2[i] == EXPECTED_LORA_OUTPUT[i]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_gptoss_tp.py
tests/lora/test_gptoss_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import vllm from vllm.lora.request import LoRARequest from ..utils import multi_gpu_test MODEL_PATH = "openai/gpt-oss-20b" PROMPT_TEMPLATE = """<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI. Knowledge cutoff: 2024-06 Current date: 2025-10-29 Reasoning: medium # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>user<|message|>I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request. " ##Instruction: farm contains tables such as city, farm, farm_competition, competition_record. Table city has columns such as City_ID, Official_Name, Status, Area_km_2, Population, Census_Ranking. City_ID is the primary key. Table farm has columns such as Farm_ID, Year, Total_Horses, Working_Horses, Total_Cattle, Oxen, Bulls, Cows, Pigs, Sheep_and_Goats. Farm_ID is the primary key. Table farm_competition has columns such as Competition_ID, Year, Theme, Host_city_ID, Hosts. Competition_ID is the primary key. Table competition_record has columns such as Competition_ID, Farm_ID, Rank. Competition_ID is the primary key. The Host_city_ID of farm_competition is the foreign key of City_ID of city. The Farm_ID of competition_record is the foreign key of Farm_ID of farm. The Competition_ID of competition_record is the foreign key of Competition_ID of farm_competition. ###Input: {context} ###Response:<|end|><|start|>assistant<|channel|>final<|message|>""" # noqa: E501 EXPECTED_LORA_OUTPUT = [ "SELECT avg(Working_Horses) FROM farm WHERE Total_Horses > 5000", "SELECT max(Cows) , min(Cows) FROM farm", "SELECT max(Cows) , min(Cows) FROM farm", ] def generate_and_test(llm: vllm.LLM, lora_path: str, lora_id: int) -> None: prompts = [ PROMPT_TEMPLATE.format( context="Give the average number of working horses on farms with more than 5000 total horses." # noqa: E501 ), # noqa: E501 PROMPT_TEMPLATE.format( context="What are the maximum and minimum number of cows across all farms." ), PROMPT_TEMPLATE.format( context="Return the maximum and minimum number of cows across all farms." ), ] sampling_params = vllm.SamplingParams(temperature=0, max_tokens=64) outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") for i in range(len(EXPECTED_LORA_OUTPUT)): assert generated_texts[i].startswith(EXPECTED_LORA_OUTPUT[i]) def test_gpt_oss_lora(gptoss20b_lora_files): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, max_lora_rank=8, max_num_seqs=2, max_num_batched_tokens=2048, compilation_config=vllm.config.CompilationConfig( # Avoid OOM cudagraph_specialize_lora=False, ), ) generate_and_test(llm, gptoss20b_lora_files, lora_id=1) generate_and_test(llm, gptoss20b_lora_files, lora_id=2) @multi_gpu_test(num_gpus=2) @pytest.mark.parametrize("fully_sharded_loras", [False, True]) def test_gpt_oss_lora_tp2(gptoss20b_lora_files, fully_sharded_loras): llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=2, max_lora_rank=8, max_num_seqs=2, max_num_batched_tokens=2048, tensor_parallel_size=2, gpu_memory_utilization=0.8, fully_sharded_loras=fully_sharded_loras, compilation_config=vllm.config.CompilationConfig( # Avoid OOM cudagraph_specialize_lora=False, ), ) generate_and_test(llm, gptoss20b_lora_files, lora_id=1) generate_and_test(llm, gptoss20b_lora_files, lora_id=2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_peft_helper.py
tests/lora/test_peft_helper.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import json import math import shutil import pytest from vllm.config.lora import LoRAConfig from vllm.lora.peft_helper import PEFTHelper ERROR_CASES = [ ( "test_rank", {"r": 1024}, "is greater than max_lora_rank", ), ("test_dora", {"use_dora": True}, "does not yet support DoRA"), ( "test_modules_to_save", {"modules_to_save": ["lm_head"]}, "only supports modules_to_save being None", ), ] def test_peft_helper_pass(llama32_lora_files, tmp_path): peft_helper = PEFTHelper.from_local_dir( llama32_lora_files, max_position_embeddings=4096 ) lora_config = LoRAConfig(max_lora_rank=16, max_cpu_loras=3, max_loras=2) peft_helper.validate_legal(lora_config) assert peft_helper.r == 8 assert peft_helper.lora_alpha == 32 target_modules = sorted(peft_helper.target_modules) assert target_modules == [ "down_proj", "embed_tokens", "gate_proj", "k_proj", "lm_head", "o_proj", "q_proj", "up_proj", "v_proj", ] assert peft_helper.vllm_max_position_embeddings == 4096 # test RSLoRA rslora_config = dict(use_rslora=True) test_dir = tmp_path / "test_rslora" shutil.copytree(llama32_lora_files, test_dir) # Load and modify configuration config_path = test_dir / "adapter_config.json" with open(config_path) as f: adapter_config = json.load(f) # Apply configuration changes adapter_config.update(rslora_config) # Save modified configuration with open(config_path, "w") as f: json.dump(adapter_config, f) peft_helper = PEFTHelper.from_local_dir(test_dir, max_position_embeddings=4096) peft_helper.validate_legal(lora_config) scaling = peft_helper.lora_alpha / math.sqrt(peft_helper.r) assert abs(peft_helper.vllm_lora_scaling_factor - scaling) < 1e-3 @pytest.mark.parametrize("test_name,config_change,expected_error", ERROR_CASES) def test_peft_helper_error( llama32_lora_files, tmp_path, test_name: str, config_change: dict, expected_error: str, ): test_dir = tmp_path / test_name shutil.copytree(llama32_lora_files, test_dir) # Load and modify configuration config_path = test_dir / "adapter_config.json" with open(config_path) as f: adapter_config = json.load(f) # Apply configuration changes adapter_config.update(config_change) # Save modified configuration with open(config_path, "w") as f: json.dump(adapter_config, f) lora_config = LoRAConfig(max_lora_rank=16, max_cpu_loras=3, max_loras=2) # Test loading the adapter with pytest.raises(ValueError, match=expected_error): PEFTHelper.from_local_dir( test_dir, max_position_embeddings=4096 ).validate_legal(lora_config)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_deepseekv2_tp.py
tests/lora/test_deepseekv2_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # NOTE To avoid overloading the CI pipeline, this test script will # not be triggered on CI and is primarily intended for local testing # and verification. import vllm from vllm.lora.request import LoRARequest from ..utils import multi_gpu_test MODEL_PATH = "deepseek-ai/DeepSeek-V2-Lite-Chat" PROMPT_TEMPLATE = "<|begin▁of▁sentence|>You are a helpful assistant.\n\nUser: {context}\n\nAssistant:" # noqa: E501 def generate_and_test(llm: vllm.LLM, lora_path: str, lora_id: int): prompts = [ PROMPT_TEMPLATE.format(context="Who are you?"), ] sampling_params = vllm.SamplingParams(temperature=0, max_tokens=64) outputs = llm.generate( prompts, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") # return generated_texts expected_lora_output = [ "I am \u5f20\u5b50\u8c6a, an AI assistant developed by \u9648\u58eb\u680b.", # noqa: E501 ] for i in range(len(expected_lora_output)): assert generated_texts[i].startswith(expected_lora_output[i]) def test_deepseekv2_lora(deepseekv2_lora_files): # We enable enforce_eager=True here to reduce VRAM usage for lora-test CI, # Otherwise, the lora-test will fail due to CUDA OOM. llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, ) generate_and_test(llm, deepseekv2_lora_files, 1) def test_deepseekv2(deepseekv2_lora_files): # We enable enforce_eager=True here to reduce VRAM usage for lora-test CI, # Otherwise, the lora-test will fail due to CUDA OOM. llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, ) generate_and_test(llm, deepseekv2_lora_files, 1) @multi_gpu_test(num_gpus=2) def test_deepseekv2_tp2(deepseekv2_lora_files): # We enable enforce_eager=True here to reduce VRAM usage for lora-test CI, # Otherwise, the lora-test will fail due to CUDA OOM. llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, tensor_parallel_size=2, ) generate_and_test(llm, deepseekv2_lora_files, 2) @multi_gpu_test(num_gpus=4) def test_deepseekv2_tp4(deepseekv2_lora_files): # We enable enforce_eager=True here to reduce VRAM usage for lora-test CI, # Otherwise, the lora-test will fail due to CUDA OOM. llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True, max_loras=4, enforce_eager=True, trust_remote_code=True, tensor_parallel_size=4, ) generate_and_test(llm, deepseekv2_lora_files, 2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/__init__.py
tests/lora/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_fused_moe_lora_kernel.py
tests/lora/test_fused_moe_lora_kernel.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os import random import pytest import torch from tests.utils import multi_gpu_test from vllm import _custom_ops as ops from vllm.distributed import ( init_distributed_environment, initialize_model_parallel, tensor_model_parallel_all_gather, tensor_model_parallel_all_reduce, ) from vllm.distributed.parallel_state import ( get_tensor_model_parallel_world_size, ) from vllm.lora.ops.triton_ops import fused_moe_lora from vllm.platforms import current_platform from vllm.utils.network_utils import get_open_port @pytest.fixture(autouse=True) def reset_device(reset_default_device): pass def round_up(x, base): return ((x + base - 1) // base) * base def CEILDIV(x, y): return (x + y - 1) // y def assign_loras_to_tokens(num_tokens: int, num_sequences: int, max_loras: int): """ Split `num_tokens` into `num_sequences` sequences. Each sequence randomly selects 1 LoRA index from [0, max_loras), and all tokens in that sequence are assigned this LoRA index. Args: num_tokens (int): Total number of tokens. num_sequences (int): Number of sequences to split the tokens into. max_loras (int): Total number of available LoRA modules. Returns: torch.Tensor: 1D tensor of shape [num_tokens], where each value is the LoRA index assigned to that token. """ assert num_sequences > 0 and max_loras > 0 assert num_tokens >= num_sequences, "num_tokens must be >= num_sequences" # Compute token distribution per sequence (distribute remainder evenly) tokens_per_seq = num_tokens // num_sequences remainder = num_tokens % num_sequences token_lora_mapping = torch.empty(num_tokens, dtype=torch.int32) start = 0 for seq_idx in range(num_sequences): # Determine the token range for this sequence end = start + tokens_per_seq + (1 if seq_idx < remainder else 0) # Randomly select one LoRA ID for this sequence lora_id = random.randint(0, max_loras - 1) # Assign the same LoRA ID to all tokens in this sequence token_lora_mapping[start:end] = lora_id start = end return token_lora_mapping def assign_experts_to_tokens(num_tokens: int, num_experts: int, top_k_num: int): """ For each token, randomly select `top_k_num` distinct experts out of `num_experts`, and assign normalized random weights that sum to 1. Args: num_tokens (int): Total number of tokens. num_experts (int): Total number of available experts. top_k_num (int): Number of experts to select per token. Returns: expert_indices (torch.Tensor): shape [num_tokens, top_k_num], expert index for each token. expert_weights (torch.Tensor): shape [num_tokens, top_k_num], normalized weights (sum = 1 per row). """ assert top_k_num <= num_experts, "top_k_num must be <= num_experts" # Randomly select top_k_num distinct experts for each token expert_indices = torch.empty((num_tokens, top_k_num), dtype=torch.int32) for i in range(num_tokens): # Randomly choose unique expert indices selected = torch.randperm(num_experts)[:top_k_num] expert_indices[i] = selected # Generate random weights and normalize along dim=1 expert_weights = torch.rand((num_tokens, top_k_num), dtype=torch.float32) expert_weights = expert_weights / expert_weights.sum(dim=1, keepdim=True) return expert_indices, expert_weights def sample_data( num_tokens: int, num_sequences: int, max_loras: int, num_experts: int, top_k_num: int, ): topk_ids, topk_weights = assign_experts_to_tokens( num_tokens, num_experts, top_k_num ) token_lora_mapping = assign_loras_to_tokens(num_tokens, num_sequences, max_loras) return topk_ids, topk_weights, token_lora_mapping def use_fused_moe_lora_kernel( topk_ids, topk_weights, token_lora_mapping, max_lora_rank, top_k_num, lora_a_stacked, lora_b_stacked, hidden_states, output, max_loras, num_experts, block_size, fully_sharded=False, offset=0, ): max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1) max_num_tokens_padded = round_up(max_num_tokens_padded, block_size) max_num_m_blocks = CEILDIV(max_num_tokens_padded, block_size) # init output tensors sorted_token_ids = torch.empty( (max_loras * max_num_tokens_padded,), dtype=torch.int32, ) expert_ids = torch.empty((max_loras * max_num_m_blocks,), dtype=torch.int32) num_tokens_post_padded = torch.empty((max_loras,), dtype=torch.int32) adapter_enabled = torch.ones(max_loras + 1, dtype=torch.int32) lora_ids = torch.arange(max_loras + 2, dtype=torch.int32) # call kernel ops.moe_lora_align_block_size( topk_ids, token_lora_mapping, num_experts, block_size, max_loras, max_num_tokens_padded, max_num_m_blocks, sorted_token_ids, expert_ids, num_tokens_post_padded, adapter_enabled, lora_ids, ) config = { "BLOCK_SIZE_M": 16, "BLOCK_SIZE_N": 32, "BLOCK_SIZE_K": 64, "GROUP_SIZE_M": 1, "NUM_WARPS": 4, "NUM_STAGES": 3, "SPLIT_K": 1, } mul_routed_weight = False expert_ids = expert_ids.view(max_loras, -1) sorted_token_ids = sorted_token_ids.view(max_loras, -1) fused_moe_lora( output, hidden_states, lora_a_stacked, lora_b_stacked, topk_weights, sorted_token_ids, expert_ids, num_tokens_post_padded, max_lora_rank, top_k_num, lora_ids, adapter_enabled, config["BLOCK_SIZE_M"], config["BLOCK_SIZE_N"], config["BLOCK_SIZE_K"], config["GROUP_SIZE_M"], config["NUM_WARPS"], config["NUM_STAGES"], config["SPLIT_K"], config["BLOCK_SIZE_M"], config["BLOCK_SIZE_N"], config["BLOCK_SIZE_K"], config["GROUP_SIZE_M"], config["NUM_WARPS"], config["NUM_STAGES"], config["SPLIT_K"], mul_routed_weight, fully_sharded=fully_sharded, offset=offset, ) def use_torch( hidden_states, token_lora_mapping, topk_ids, lora_a_stacked, lora_b_stacked, top_k_num, ): outputs = [] for i in range(hidden_states.shape[0]): lora_idx = token_lora_mapping[i] expert_ids = topk_ids[i] lora_a = lora_a_stacked[0][lora_idx][expert_ids] lora_b = lora_b_stacked[0][lora_idx][expert_ids] tensors = [ hidden_states[i] @ lora_a[x].T @ lora_b[x].T for x in range(top_k_num) ] outputs.append(torch.stack(tensors, dim=0)) return torch.stack(outputs, dim=0) DTYPES = [torch.float16, torch.bfloat16] DEVICES = [f"cuda:{0}"] SEED = [42] @pytest.mark.parametrize("num_tokens", [100]) @pytest.mark.parametrize("top_k_num", [6, 12]) @pytest.mark.parametrize("num_experts", [64]) @pytest.mark.parametrize("max_loras", [4, 6, 16]) @pytest.mark.parametrize("N", [1408]) @pytest.mark.parametrize("K", [2048]) @pytest.mark.parametrize("max_lora_rank", [16, 32, 64]) @pytest.mark.parametrize("block_size", [16]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("seed", SEED) def test_fused_moe_lora_kernel( num_tokens, top_k_num, num_experts, max_loras, N, K, max_lora_rank, block_size, dtype, device, seed, ): torch.set_default_device(device) current_platform.seed_everything(seed) # the number of randomly generated sentences. num_sequences = 10 # generate data topk_ids, topk_weights, token_lora_mapping = sample_data( num_tokens, num_sequences, max_loras, num_experts, top_k_num ) # init lora weights lora_a_stacked = [ torch.rand( ( max_loras, num_experts, max_lora_rank, K, ), dtype=dtype, ) ] lora_b_stacked = [ torch.rand( ( max_loras, num_experts, N, max_lora_rank, ), dtype=dtype, ) ] hidden_states = torch.rand( ( num_tokens, K, ), dtype=dtype, ) # fused_moe_lora_kernel output output = torch.zeros((num_tokens, top_k_num, N), dtype=dtype) use_fused_moe_lora_kernel( topk_ids, topk_weights, token_lora_mapping, max_lora_rank, top_k_num, lora_a_stacked, lora_b_stacked, hidden_states, output, max_loras, num_experts, block_size, ) # pytorch output output2 = use_torch( hidden_states, token_lora_mapping, topk_ids, lora_a_stacked, lora_b_stacked, top_k_num, ) torch.testing.assert_close(output, output2, atol=1e-1, rtol=1e-1) @multi_gpu_test(num_gpus=2) @pytest.mark.parametrize("num_tokens", [100]) @pytest.mark.parametrize("top_k_num", [6]) @pytest.mark.parametrize("num_experts", [64]) @pytest.mark.parametrize("max_loras", [4]) @pytest.mark.parametrize("N", [1408]) @pytest.mark.parametrize("K", [2048]) @pytest.mark.parametrize("max_lora_rank", [16, 32, 64]) @pytest.mark.parametrize("block_size", [16]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEED) @pytest.mark.parametrize("column_parallel", [True, False]) def test_fused_moe_lora_kernel_fully_sharded( num_tokens, top_k_num, num_experts, max_loras, N, K, max_lora_rank, block_size, dtype, seed, column_parallel, ): current_platform.seed_everything(seed) # the number of randomly generated sentences. num_sequences = 10 # generate data topk_ids, topk_weights, token_lora_mapping = sample_data( num_tokens, num_sequences, max_loras, num_experts, top_k_num ) def run_torch_spawn(fn, nprocs): torch.multiprocessing.spawn( fn, args=( nprocs, f"tcp://{os.getenv('LOCALHOST', 'localhost')}:{get_open_port()}", dtype, seed, N, K, num_tokens, topk_ids, topk_weights, token_lora_mapping, max_lora_rank, top_k_num, max_loras, num_experts, block_size, column_parallel, ), nprocs=nprocs, ) run_torch_spawn(use_fused_moe_lora_kernel_tensor_parallel, nprocs=2) def use_fused_moe_lora_kernel_tensor_parallel( local_rank, world_size, init_method, dtype, seed, N, K, num_tokens, topk_ids, topk_weights, token_lora_mapping, max_lora_rank, top_k_num, max_loras, num_experts, block_size, column_parallel, ): def _get_shard_slice(shard_size): return slice(local_rank * shard_size, (local_rank + 1) * shard_size) current_platform.seed_everything(seed) device = torch.device(f"cuda:{local_rank}") torch.cuda.set_device(device) torch.set_default_device(device) torch.set_default_dtype(dtype) init_distributed_environment( world_size=world_size, rank=local_rank, local_rank=local_rank, distributed_init_method=init_method, ) initialize_model_parallel(world_size, 1) tp_size = get_tensor_model_parallel_world_size() input_dim = K if column_parallel else N output_dim = N if column_parallel else K # init lora weights lora_a = torch.rand( ( max_loras, num_experts, max_lora_rank, input_dim, ), dtype=dtype, ) lora_b = torch.rand( ( max_loras, num_experts, output_dim, max_lora_rank, ), dtype=dtype, ) hidden_states = torch.rand( ( num_tokens, input_dim, ), dtype=dtype, ) output = torch.zeros((num_tokens, top_k_num, output_dim), dtype=dtype) topk_ids = topk_ids.to(device) topk_weights = topk_weights.to(device) token_lora_mapping = token_lora_mapping.to(device) ref_output = use_torch( hidden_states, token_lora_mapping, topk_ids, [lora_a], [lora_b], top_k_num, ) if column_parallel: # Column parallel (e.g. gate_up_proj): LoRA A is sliced along the rank dim, # and Lora B is sliced along the output dim lora_a_shard_size = max_lora_rank // tp_size lora_a = lora_a[:, :, _get_shard_slice(lora_a_shard_size), :] max_lora_rank = lora_a_shard_size offset = 0 lora_b_shard_size = output_dim // tp_size lora_b = lora_b[:, :, _get_shard_slice(lora_b_shard_size), :] output = output[:, :, _get_shard_slice(lora_b_shard_size)].contiguous() else: # Row parallel (e.g. down proj): LoRA A is sliced along the input dim, # and LoRA B is sliced along the output dim lora_a_shard_size = input_dim // tp_size lora_a = lora_a[:, :, :, _get_shard_slice(lora_a_shard_size)] hidden_states = hidden_states[:, _get_shard_slice(lora_a_shard_size)] lora_b_shard_size = output_dim // tp_size lora_b = lora_b[:, :, _get_shard_slice(lora_b_shard_size), :] offset = lora_b_shard_size * local_rank use_fused_moe_lora_kernel( topk_ids, topk_weights, token_lora_mapping, max_lora_rank, top_k_num, [lora_a], [lora_b], hidden_states, output, max_loras, num_experts, block_size, fully_sharded=True, offset=offset, ) if column_parallel: output = tensor_model_parallel_all_gather(output) else: output = tensor_model_parallel_all_reduce(output) torch.testing.assert_close(output, ref_output, atol=1e-1, rtol=1e-1)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_lora_functions.py
tests/lora/test_lora_functions.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Script to test add_lora, remove_lora, pin_lora, list_loras functions. """ import pytest from vllm.engine.arg_utils import AsyncEngineArgs, EngineArgs from vllm.entrypoints.openai.api_server import ( build_async_engine_client_from_engine_args, ) from vllm.lora.request import LoRARequest from vllm.v1.engine.llm_engine import LLMEngine MODEL_PATH = "Qwen/Qwen3-0.6B" LORA_MODULE_PATH = "charent/self_cognition_Alice" LORA_RANK = 8 def make_lora_request(lora_id: int): return LoRARequest( lora_name=f"{lora_id}", lora_int_id=lora_id, lora_path=LORA_MODULE_PATH ) def test_lora_functions_sync(): max_loras = 4 # Create engine in eager-mode. Due to high max_loras, the CI can # OOM during cuda-graph capture. engine_args = EngineArgs( model=MODEL_PATH, enable_lora=True, max_loras=max_loras, max_lora_rank=LORA_RANK, max_model_len=128, gpu_memory_utilization=0.8, enforce_eager=True, ) llm = LLMEngine.from_engine_args(engine_args) def run_check(fn, args, expected: list): fn(args) assert set(llm.list_loras()) == set(expected) run_check(llm.add_lora, make_lora_request(1), [1]) run_check(llm.add_lora, make_lora_request(2), [1, 2]) # Pin LoRA 1 and test that it is never removed on subsequent adds. run_check(llm.pin_lora, 1, [1, 2]) run_check(llm.add_lora, make_lora_request(3), [1, 2, 3]) run_check(llm.add_lora, make_lora_request(4), [1, 2, 3, 4]) run_check(llm.add_lora, make_lora_request(5), [1, 5, 3, 4]) run_check(llm.add_lora, make_lora_request(6), [1, 5, 6, 4]) run_check(llm.add_lora, make_lora_request(7), [1, 5, 6, 7]) run_check(llm.add_lora, make_lora_request(8), [1, 8, 6, 7]) run_check(llm.add_lora, make_lora_request(9), [1, 8, 9, 7]) run_check(llm.add_lora, make_lora_request(10), [1, 8, 9, 10]) # Remove LoRA 1 and continue adding. run_check(llm.remove_lora, 1, [8, 9, 10]) run_check(llm.add_lora, make_lora_request(11), [8, 9, 10, 11]) run_check(llm.add_lora, make_lora_request(12), [12, 9, 10, 11]) run_check(llm.add_lora, make_lora_request(13), [12, 13, 10, 11]) # Remove all LoRAs. run_check(llm.remove_lora, 13, [12, 10, 11]) run_check(llm.remove_lora, 12, [10, 11]) run_check(llm.remove_lora, 11, [10]) run_check(llm.remove_lora, 10, []) @pytest.mark.asyncio async def test_lora_functions_async(): max_loras = 4 engine_args = AsyncEngineArgs( model=MODEL_PATH, enable_lora=True, max_loras=max_loras, max_lora_rank=LORA_RANK, max_model_len=128, gpu_memory_utilization=0.8, enforce_eager=True, ) async def run_check(fn, args, expected: list): await fn(args) assert set(await llm.list_loras()) == set(expected) async with build_async_engine_client_from_engine_args(engine_args) as llm: await run_check(llm.add_lora, make_lora_request(1), [1]) await run_check(llm.add_lora, make_lora_request(2), [1, 2]) # Pin LoRA 1 and test that it is never removed on subsequent adds. await run_check(llm.pin_lora, 1, [1, 2]) await run_check(llm.add_lora, make_lora_request(3), [1, 2, 3]) await run_check(llm.add_lora, make_lora_request(4), [1, 2, 3, 4]) await run_check(llm.add_lora, make_lora_request(5), [1, 5, 3, 4]) await run_check(llm.add_lora, make_lora_request(6), [1, 5, 6, 4]) await run_check(llm.add_lora, make_lora_request(7), [1, 5, 6, 7]) await run_check(llm.add_lora, make_lora_request(8), [1, 8, 6, 7]) await run_check(llm.add_lora, make_lora_request(9), [1, 8, 9, 7]) await run_check(llm.add_lora, make_lora_request(10), [1, 8, 9, 10]) # Remove LoRA 1 and continue adding. await run_check(llm.remove_lora, 1, [8, 9, 10]) await run_check(llm.add_lora, make_lora_request(11), [8, 9, 10, 11]) await run_check(llm.add_lora, make_lora_request(12), [12, 9, 10, 11]) await run_check(llm.add_lora, make_lora_request(13), [12, 13, 10, 11]) # Remove all LoRAs await run_check(llm.remove_lora, 13, [12, 10, 11]) await run_check(llm.remove_lora, 12, [10, 11]) await run_check(llm.remove_lora, 11, [10]) await run_check(llm.remove_lora, 10, [])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_moe_lora_align_sum.py
tests/lora/test_moe_lora_align_sum.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import random import pytest import torch from vllm import _custom_ops as ops def round_up(x, base): return ((x + base - 1) // base) * base def CEILDIV(x, y): return (x + y - 1) // y def sample_data(num_experts, max_loras, num_tokens, topk_num): topk_ids = torch.zeros((num_tokens, topk_num), dtype=torch.int32) token_lora_mapping = torch.zeros((num_tokens,), dtype=torch.int32) for i in range(num_tokens): pool = list(range(num_experts)) random.shuffle(pool) for j in range(topk_num): topk_ids[i, j] = pool[j] token_lora_mapping[i] = random.randint(0, max_loras - 1) return topk_ids.to("cuda"), token_lora_mapping.to("cuda") @pytest.mark.parametrize("num_tokens", [100, 200, 1024, 4096]) # 81920 @pytest.mark.parametrize("topk_num", [6]) @pytest.mark.parametrize("num_experts", [64, 128, 256, 512]) @pytest.mark.parametrize("max_loras", [2, 32]) @pytest.mark.parametrize("block_size", [16]) def test_moe_lora_align_block_size( num_tokens, topk_num, num_experts, max_loras, block_size ): # sample data random.seed(1) topk_ids, token_lora_mapping = sample_data( num_experts, max_loras, num_tokens, topk_num ) # compute paddings max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1) max_num_tokens_padded = round_up(max_num_tokens_padded, block_size) max_num_m_blocks = CEILDIV(max_num_tokens_padded, block_size) # init output tensors sorted_token_ids = torch.full( (max_loras * max_num_tokens_padded,), topk_ids.numel(), dtype=torch.int32, device="cuda", ) expert_ids = torch.full( (max_loras * max_num_m_blocks,), num_experts, dtype=torch.int32, device="cuda" ) num_tokens_post_pad = torch.zeros((max_loras,), dtype=torch.int32, device="cuda") adapter_enabled = torch.ones((max_loras + 1,), dtype=torch.int32, device="cuda") lora_ids = torch.arange(max_loras + 2, dtype=torch.int32, device="cuda") # call kernel ops.moe_lora_align_block_size( topk_ids, token_lora_mapping, num_experts, block_size, max_loras, max_num_tokens_padded, max_num_m_blocks, sorted_token_ids, expert_ids, num_tokens_post_pad, adapter_enabled, lora_ids, ) # verify values expert_ids = expert_ids.view(max_loras, -1) sorted_token_ids = sorted_token_ids.view(max_loras, -1, block_size) for lora_idx in range(max_loras): for token_idx in range(sorted_token_ids.size(1)): block = sorted_token_ids[lora_idx][token_idx] indices = block[block != topk_ids.numel()] if indices.numel() > 0: expert_id = expert_ids[lora_idx][token_idx] assert torch.all(topk_ids.view(-1)[indices] == expert_id) if __name__ == "__main__": pytest.main([__file__])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_layers.py
tests/lora/test_layers.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import random from copy import deepcopy from dataclasses import dataclass from unittest.mock import patch import pytest import torch import torch.nn.functional as F from vllm.config.lora import LoRAConfig from vllm.lora.layers import ( BaseLayerWithLoRA, ColumnParallelLinearWithLoRA, ColumnParallelLinearWithShardedLoRA, LogitsProcessorWithLoRA, LoRAMapping, MergedColumnParallelLinearWithLoRA, MergedColumnParallelLinearWithShardedLoRA, MergedQKVParallelLinearWithLoRA, MergedQKVParallelLinearWithShardedLoRA, QKVParallelLinearWithLoRA, QKVParallelLinearWithShardedLoRA, ReplicatedLinearWithLoRA, RowParallelLinearWithLoRA, RowParallelLinearWithShardedLoRA, VocabParallelEmbeddingWithLoRA, ) from vllm.lora.lora_weights import LoRALayerWeights, PackedLoRALayerWeights from vllm.lora.punica_wrapper import get_punica_wrapper from vllm.model_executor.layers.linear import ( ColumnParallelLinear, MergedColumnParallelLinear, QKVParallelLinear, ReplicatedLinear, RowParallelLinear, ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, VocabParallelEmbedding, get_masked_input_and_mask, ) from vllm.model_executor.utils import set_random_seed from vllm.platforms import current_platform from .utils import DummyLoRAManager TOLERANCES = { torch.float16: (5e-3, 5e-3), torch.float32: (5e-3, 5e-3), torch.bfloat16: (3e-2, 2e-2), } pytestmark = pytest.mark.skipif( not (current_platform.is_cuda_alike() or current_platform.is_cpu()), reason="Backend not supported", ) DEVICES = ( [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)] if current_platform.is_cuda_alike() else ["cpu"] ) # prefill stage(True) or decode stage(False) STAGES = [True, False] NUM_RANDOM_SEEDS = 2 VOCAB_PARALLEL_EMBEDDING_TEST_NUM_RANDOM_SEEDS = 2 @pytest.fixture(autouse=True) def clean_cache_reset_device(reset_default_device): # Release any memory we might be holding on to. CI runs OOMs otherwise. from vllm.lora.ops.triton_ops.utils import _LORA_A_PTR_DICT, _LORA_B_PTR_DICT _LORA_B_PTR_DICT.clear() _LORA_A_PTR_DICT.clear() yield @pytest.fixture(autouse=True) def skip_cuda_with_stage_false(request): """ On cuda-like platforms, we use the same kernels for prefill and decode stage, and 'stage' is generally ignored, so we only need to test once. """ if current_platform.is_cuda_alike(): try: if hasattr(request.node, "callspec") and hasattr( request.node.callspec, "params" ): params = request.node.callspec.params if "stage" in params and params["stage"] is False: pytest.skip("Skip test when stage=False") except Exception: pass yield def get_random_id_to_index( num_loras: int, num_slots: int, log: bool = True ) -> list[int | None]: """Creates a random lora_id_to_index mapping. Args: num_loras: The number of active loras in the mapping. num_slots: The number of slots in the mapping. Must be larger than num_loras. log: Whether to log the output. """ if num_loras > num_slots: raise ValueError( f"num_loras is higher than num_slots: {num_loras} > {num_slots}. " "num_loras must be less than or equal to num_slots." ) slots: list[int | None] = [None] * num_slots random_slot_selections = (torch.randperm(num_slots)[:num_loras]).tolist() for lora_id, slot_idx in enumerate(random_slot_selections, start=1): slots[slot_idx] = lora_id if log: print(f"Created lora_id_to_index mapping: {slots}.") return slots def populate_loras( id_to_index: list[int | None], layer: BaseLayerWithLoRA, layer_weights: torch.Tensor, repeats: int = 1, ) -> tuple[dict[int, LoRALayerWeights], dict[int, list[LoRALayerWeights]]]: """This method populates the lora layers with lora weights. Args: id_to_index: a list of lora ids. The index of the lora id represents which memory slot the lora matrices are stored in. A None value indicates a free slot. layer: the LoRAlayer to populate. layer_weights: the PyTorch tensor containing the layer's weights. repeats: must only be set for column parallel packed layers. Indicates the number of loras to compose together to create a single lora layer. """ # Dictionary that maps the lora ID to the # corresponding lora weights. lora_dict: dict[int, LoRALayerWeights] = dict() # Dictionary that maps the lora ID to the # corresponding subloras. sublora_dict: dict[int, list[LoRALayerWeights]] = dict() for slot_idx, lora_id in enumerate(id_to_index): if lora_id is not None: subloras: list[LoRALayerWeights] = [] sublora_len = layer_weights.shape[0] // repeats for i in range(repeats): sublora = DummyLoRAManager(layer_weights.device).init_random_lora( module_name=f"fake_{i}", weight=layer_weights, ) sublora.lora_b = sublora.lora_b[ (sublora_len * i) : (sublora_len * (i + 1)), : ] sublora.optimize() subloras.append(sublora) lora = PackedLoRALayerWeights.pack(subloras) if repeats > 1 else subloras[0] layer.set_lora( slot_idx, lora_a=lora.lora_a, lora_b=lora.lora_b, ) lora_dict[lora_id] = lora sublora_dict[lora_id] = subloras return lora_dict, sublora_dict def create_random_inputs( active_lora_ids: list[int], num_inputs: int, input_size: tuple[int, ...], input_range: tuple[float, float], input_type: torch.dtype = torch.int, device: torch.device = "cuda", ) -> tuple[list[torch.Tensor], list[int], list[int]]: """Creates random inputs. Args: active_lora_ids: lora IDs of active lora weights. num_inputs: the number of inputs to create. input_size: the size of each individual input. input_range: the range of values to include in the input. input_range[0] <= possible input values < input_range[1] input_type: the type of values in the input. """ low, high = input_range inputs: list[torch.Tensor] = [] index_mapping: list[int] = [] prompt_mapping: list[int] = [] for _ in range(num_inputs): if input_type == torch.int: inputs.append( torch.randint( low=int(low), high=int(high), size=input_size, device=device ) ) else: inputs.append( torch.rand(size=input_size, dtype=input_type, device=device) * high + low ) lora_id = random.choice(active_lora_ids) index_mapping += [lora_id] * input_size[0] prompt_mapping += [lora_id] return inputs, index_mapping, prompt_mapping def check_punica_wrapper(punica_wrapper) -> bool: if current_platform.is_cuda_alike(): from vllm.lora.punica_wrapper.punica_gpu import PunicaWrapperGPU return type(punica_wrapper) is PunicaWrapperGPU elif current_platform.is_cpu(): from vllm.lora.punica_wrapper.punica_cpu import PunicaWrapperCPU return type(punica_wrapper) is PunicaWrapperCPU else: return False @torch.inference_mode() @pytest.mark.parametrize("num_loras", [1, 2, 4]) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("vocab_size", [512, 32000, 64000, 128000]) @pytest.mark.parametrize("stage", STAGES) def test_embeddings(dist_init, num_loras, device, vocab_size, stage) -> None: # For multi-GPU testing of Triton kernel, we must explicitly set the CUDA # device, see: https://github.com/triton-lang/triton/issues/2925 # Same below. if current_platform.is_cuda_alike(): torch.cuda.set_device(device) torch.set_default_device(device) max_loras = 8 lora_config = LoRAConfig( max_loras=max_loras, max_lora_rank=8, lora_dtype=torch.float16 ) punica_wrapper = get_punica_wrapper(8192, 256, device, lora_config=lora_config) assert check_punica_wrapper(punica_wrapper) def create_random_embedding_layer(): embedding = VocabParallelEmbedding(vocab_size, 256) embedding.weight.data = torch.rand_like(embedding.weight.data) embedding.weight.data[vocab_size:, :] = 0 lora_embedding = VocabParallelEmbeddingWithLoRA(embedding) lora_embedding.create_lora_weights(max_loras, lora_config) return embedding, lora_embedding for i in range(NUM_RANDOM_SEEDS): set_random_seed(i) id_to_index = get_random_id_to_index(num_loras, max_loras) embedding, lora_embedding = create_random_embedding_layer() lora_embedding.set_mapping(punica_wrapper) lora_dict, _ = populate_loras( id_to_index, layer=lora_embedding, layer_weights=embedding.weight.T, ) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=list(lora_dict.keys()), num_inputs=num_loras * 3, input_size=(200,), input_range=(1, vocab_size), device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, vocab_size, ) lora_result = lora_embedding(torch.cat(inputs)) expected_results: list[torch.Tensor] = [] for input_, lora_id in zip(inputs, prompt_mapping): lora = lora_dict[lora_id] result = embedding(input_) after_a = F.embedding( input_, lora.lora_a.T, ) result += after_a @ lora.lora_b.T expected_results.append(result) expected_result = torch.cat(expected_results) rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) # Check that resetting the lora weights succeeds for slot_idx in range(max_loras): lora_embedding.reset_lora(slot_idx) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=[0], num_inputs=num_loras * 3, input_size=(200,), input_range=(1, vocab_size), device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, vocab_size, ) lora_result = lora_embedding(torch.cat(inputs)) expected_result = embedding(torch.cat(inputs)) rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) @torch.inference_mode() @pytest.mark.parametrize("num_loras", [1, 2, 4]) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("vocab_size", [512, 32000, 64000, 256512]) @pytest.mark.parametrize("stage", STAGES) def test_lm_head_logits_processor( dist_init, num_loras, device, vocab_size, stage ) -> None: if current_platform.is_cuda_alike(): torch.cuda.set_device(device) torch.set_default_device(device) max_loras = 8 lora_config = LoRAConfig( max_loras=max_loras, max_lora_rank=8, lora_dtype=torch.float16 ) punica_wrapper = get_punica_wrapper(8192, 256, device, lora_config=lora_config) assert check_punica_wrapper(punica_wrapper) def _pretest(): linear = ParallelLMHead( num_embeddings=vocab_size, embedding_dim=1024, params_dtype=torch.float16, ) linear.weight.data = torch.rand_like(linear.weight.data) linear.weight.data[:, vocab_size:] = 0 logits_processor = LogitsProcessor(vocab_size) lora_logits_processor = LogitsProcessorWithLoRA( logits_processor, 1024, linear.weight.dtype, linear.weight.device, None ) lora_logits_processor.create_lora_weights(max_loras, lora_config) return linear, logits_processor, lora_logits_processor for i in range(NUM_RANDOM_SEEDS): set_random_seed(i) id_to_index = get_random_id_to_index(num_loras, max_loras) linear, logits_processor, lora_logits_processor = _pretest() lora_logits_processor.set_mapping(punica_wrapper) lora_dict, _ = populate_loras( id_to_index, layer=lora_logits_processor, layer_weights=linear.weight, ) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=list(lora_dict.keys()), num_inputs=8 * num_loras, # * 3, input_size=(1, 1024), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, vocab_size, ) input_ = torch.rand(20, 1024) lora_result = lora_logits_processor._get_logits( hidden_states=torch.cat(inputs), lm_head=linear, embedding_bias=None ) original_lm_head = deepcopy(linear) expected_results: list[torch.Tensor] = [] for input_, lora_id in zip(inputs, prompt_mapping): lora = lora_dict[lora_id] result = logits_processor._get_logits( hidden_states=input_, lm_head=linear, embedding_bias=None ) result += input_ @ lora.lora_a.T @ lora.lora_b.T * lora.scaling expected_results.append(result) expected_result = torch.cat(expected_results) # Check that resetting the lora weights succeeds for slot_idx in range(max_loras): lora_logits_processor.reset_lora(slot_idx) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=[0], num_inputs=8 * num_loras * 3, input_size=(1, 1024), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, vocab_size, ) lora_result = lora_logits_processor._get_logits( hidden_states=torch.cat(inputs), lm_head=original_lm_head, embedding_bias=None, )[:, :vocab_size] expected_result = logits_processor._get_logits( hidden_states=torch.cat(inputs), lm_head=original_lm_head, embedding_bias=None, ) rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) @torch.inference_mode() @pytest.mark.parametrize("num_loras", [1, 2, 4]) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("stage", STAGES) def test_linear_replicated( dist_init, num_loras, device, stage, ) -> None: if current_platform.is_cuda_alike(): torch.cuda.set_device(device) max_loras = 8 torch.set_default_device(device) lora_config = LoRAConfig( max_loras=max_loras, max_lora_rank=8, lora_dtype=torch.float16, ) punica_wrapper = get_punica_wrapper(8192, 256, device, lora_config=lora_config) assert check_punica_wrapper(punica_wrapper) def create_random_linear_replicated_layer(): linear = ReplicatedLinear(4096, 4096, bias=False, params_dtype=torch.float16) linear.weight.data = torch.rand_like(linear.weight.data) lora_linear = ReplicatedLinearWithLoRA(linear) lora_linear.create_lora_weights(max_loras, lora_config) assert ( lora_linear.n_slices == len(lora_linear.lora_a_stacked) == len(lora_linear.lora_b_stacked) == 1 ) return linear, lora_linear for i in range(NUM_RANDOM_SEEDS): set_random_seed(i) id_to_index = get_random_id_to_index(num_loras, max_loras) linear, lora_linear = create_random_linear_replicated_layer() assert torch.equal(linear.weight, lora_linear.weight) lora_linear.set_mapping(punica_wrapper) lora_dict, _ = populate_loras( id_to_index, layer=lora_linear, layer_weights=linear.weight, ) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=list(lora_dict.keys()), num_inputs=32 * num_loras, input_size=(1, 4096), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, 512, ) lora_result = lora_linear(torch.cat(inputs))[0] expected_results: list[torch.Tensor] = [] for input_, lora_id in zip(inputs, prompt_mapping): lora = lora_dict[lora_id] result = linear(input_)[0] result += input_ @ lora.lora_a.T @ lora.lora_b.T * lora.scaling expected_results.append(result) expected_result = torch.cat(expected_results) rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) # Check that resetting the lora weights succeeds for slot_idx in range(max_loras): lora_linear.reset_lora(slot_idx) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=[0], num_inputs=32 * num_loras, input_size=(1, 4096), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, 512, ) lora_result = lora_linear(torch.cat(inputs))[0] expected_result = linear(torch.cat(inputs))[0] rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) @torch.inference_mode() @pytest.mark.parametrize("num_loras", [1, 2, 4]) @pytest.mark.parametrize("orientation", ["row", "column"]) @pytest.mark.parametrize("fully_shard", [True, False]) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("stage", STAGES) def test_linear_parallel( dist_init, num_loras, orientation, fully_shard, device, stage ) -> None: if current_platform.is_cuda_alike(): torch.cuda.set_device(device) max_loras = 8 torch.set_default_device(device) lora_config = LoRAConfig( max_loras=max_loras, max_lora_rank=8, fully_sharded_loras=fully_shard, lora_dtype=torch.float16, ) punica_wrapper = get_punica_wrapper(8192, 256, device, lora_config=lora_config) assert check_punica_wrapper(punica_wrapper) def create_random_linear_parallel_layer(): if orientation == "row": linear = RowParallelLinear( 4096, 4096, bias=False, params_dtype=torch.float16 ) linear.weight.data = torch.rand_like(linear.weight.data) lora_linear = ( RowParallelLinearWithLoRA(linear) if not fully_shard else RowParallelLinearWithShardedLoRA(linear) ) else: linear = ColumnParallelLinear( 4096, 4096, bias=False, params_dtype=torch.float16 ) linear.weight.data = torch.rand_like(linear.weight.data) lora_linear = ( ColumnParallelLinearWithLoRA(linear) if not fully_shard else ColumnParallelLinearWithShardedLoRA(linear) ) lora_linear.create_lora_weights(max_loras, lora_config) assert ( lora_linear.n_slices == len(lora_linear.lora_a_stacked) == len(lora_linear.lora_b_stacked) == 1 ) return linear, lora_linear for i in range(NUM_RANDOM_SEEDS): set_random_seed(i) id_to_index = get_random_id_to_index(num_loras, max_loras) linear, lora_linear = create_random_linear_parallel_layer() assert torch.equal(linear.weight, lora_linear.weight) lora_linear.set_mapping(punica_wrapper) lora_dict, _ = populate_loras( id_to_index, layer=lora_linear, layer_weights=linear.weight, ) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=list(lora_dict.keys()), num_inputs=32 * num_loras, input_size=(1, 4096), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, 512, ) lora_result = lora_linear(torch.cat(inputs))[0] expected_results: list[torch.Tensor] = [] for input_, lora_id in zip(inputs, prompt_mapping): lora = lora_dict[lora_id] result = linear(input_)[0] result += input_ @ lora.lora_a.T @ lora.lora_b.T * lora.scaling expected_results.append(result) expected_result = torch.cat(expected_results) rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) # Check that resetting the lora weights succeeds for slot_idx in range(max_loras): lora_linear.reset_lora(slot_idx) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=[0], num_inputs=32 * num_loras, input_size=(1, 4096), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, 512, ) lora_result = lora_linear(torch.cat(inputs))[0] expected_result = linear(torch.cat(inputs))[0] rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) @torch.inference_mode() @pytest.mark.parametrize("num_loras", [1, 2, 4]) @pytest.mark.parametrize("repeats", [1, 2, 3]) @pytest.mark.parametrize("fully_shard", [True, False]) @pytest.mark.parametrize("device", DEVICES) @pytest.mark.parametrize("stage", STAGES) def test_column_parallel_packed( dist_init, num_loras, repeats, fully_shard, device, stage ) -> None: if current_platform.is_cuda_alike(): torch.cuda.set_device(device) max_loras = 8 torch.set_default_device(device) lora_config = LoRAConfig( max_loras=max_loras, max_lora_rank=8, fully_sharded_loras=fully_shard, lora_dtype=torch.float16, ) punica_wrapper = get_punica_wrapper(8192, 256, device, lora_config=lora_config) assert check_punica_wrapper(punica_wrapper) def create_column_parallel_packed_layer(): if repeats == 2: linear = MergedColumnParallelLinear( 4096, [4096] * repeats, bias=False, params_dtype=torch.float16 ) linear.weight.data = torch.rand_like(linear.weight.data) lora_linear = ( MergedColumnParallelLinearWithLoRA(linear) if not fully_shard else MergedColumnParallelLinearWithShardedLoRA(linear) ) elif repeats == 3: linear = QKVParallelLinear( 4096, 64, 32, bias=False, params_dtype=torch.float16 ) linear.weight.data = torch.rand_like(linear.weight.data) lora_linear = ( MergedQKVParallelLinearWithLoRA(linear) if not fully_shard else MergedQKVParallelLinearWithShardedLoRA(linear) ) else: linear = QKVParallelLinear( 4096, 64, 32, bias=False, params_dtype=torch.float16 ) linear.weight.data = torch.rand_like(linear.weight.data) lora_linear = ( QKVParallelLinearWithLoRA(linear) if not fully_shard else QKVParallelLinearWithShardedLoRA(linear) ) @dataclass class FakeConfig: hidden_size = 4096 num_key_value_heads = 32 num_attention_heads = 32 n_slices = repeats lora_linear.create_lora_weights( max_loras, lora_config, model_config=FakeConfig() ) assert ( lora_linear.n_slices == len(lora_linear.lora_a_stacked) == len(lora_linear.lora_b_stacked) == n_slices ) return linear, lora_linear for i in range(NUM_RANDOM_SEEDS): set_random_seed(i) id_to_index = get_random_id_to_index(num_loras, max_loras) linear, lora_linear = create_column_parallel_packed_layer() assert torch.equal(linear.weight, lora_linear.weight) lora_linear.set_mapping(punica_wrapper) lora_dict, sublora_dict = populate_loras( id_to_index, layer=lora_linear, layer_weights=linear.weight, repeats=repeats, ) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=list(lora_dict.keys()), num_inputs=32 * num_loras, input_size=(1, 4096), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, 512, ) lora_result = lora_linear(torch.cat(inputs))[0] expected_results: list[torch.Tensor] = [] for input_, lora_id in zip(inputs, prompt_mapping): result = linear(input_)[0] subloras = sublora_dict[lora_id] for i, sublora in enumerate(subloras): result[ :, sublora.lora_b.shape[0] * i : sublora.lora_b.shape[0] * (i + 1) ] += input_ @ sublora.lora_a.T @ sublora.lora_b.T * sublora.scaling expected_results.append(result) expected_result = torch.cat(expected_results) rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) for slot_idx in range(max_loras): lora_linear.reset_lora(slot_idx) inputs, index_mapping, prompt_mapping = create_random_inputs( active_lora_ids=[0], num_inputs=32 * num_loras, input_size=(1, 4096), input_range=(0, 1), input_type=torch.float16, device=device, ) lora_mapping = LoRAMapping(index_mapping, prompt_mapping, is_prefill=stage) punica_wrapper.update_metadata( lora_mapping, id_to_index, max_loras, 512, ) lora_result = lora_linear(torch.cat(inputs))[0] expected_result = linear(torch.cat(inputs))[0] rtol, atol = TOLERANCES[lora_result.dtype] torch.testing.assert_close(lora_result, expected_result, rtol=rtol, atol=atol) @pytest.mark.parametrize("tp_size", [1, 2, 4, 8]) @pytest.mark.parametrize( "seed", list(range(VOCAB_PARALLEL_EMBEDDING_TEST_NUM_RANDOM_SEEDS)) ) def test_vocab_parallel_embedding_indices(tp_size, seed): random.seed(seed) vocab_size = random.randint(4000, 64000) added_vocab_size = random.randint(0, 1024) org_vocab_size = vocab_size - added_vocab_size last_org_vocab_end_index = 0 last_added_vocab_end_index = org_vocab_size computed_vocab_size = 0 computed_org_vocab_size = 0 computed_added_vocab_size = 0 vocab_size_padded = -1 all_org_tokens: list[int] = [] all_added_tokens: list[int] = [] token_ids: list[int] = [] for tp_rank in range(tp_size): with ( patch( "vllm.model_executor.layers.vocab_parallel_embedding.get_tensor_model_parallel_rank", return_value=tp_rank, ), patch( "vllm.model_executor.layers.vocab_parallel_embedding.get_tensor_model_parallel_world_size", return_value=tp_size, ), ): vocab_embedding = VocabParallelEmbedding( vocab_size, 1, org_num_embeddings=org_vocab_size ) vocab_size_padded = vocab_embedding.num_embeddings_padded shard_indices = vocab_embedding.shard_indices # Assert that the ranges are contiguous assert shard_indices.org_vocab_start_index == last_org_vocab_end_index assert shard_indices.added_vocab_start_index == last_added_vocab_end_index # Ensure that we are not exceeding the vocab size computed_vocab_size += shard_indices.num_elements_padded computed_org_vocab_size += shard_indices.num_org_elements computed_added_vocab_size += shard_indices.num_added_elements # Ensure that the ranges are not overlapping all_org_tokens.extend( range( shard_indices.org_vocab_start_index, shard_indices.org_vocab_end_index ) ) all_added_tokens.extend( range( shard_indices.added_vocab_start_index, shard_indices.added_vocab_end_index, ) ) token_ids.extend( range( shard_indices.org_vocab_start_index, shard_indices.org_vocab_end_index ) ) token_ids.extend( [-1] * (shard_indices.num_org_elements_padded - shard_indices.num_org_elements) ) token_ids.extend( range( shard_indices.added_vocab_start_index, shard_indices.added_vocab_end_index, ) ) token_ids.extend( [-1] * ( shard_indices.num_added_elements_padded - shard_indices.num_added_elements ) ) last_org_vocab_end_index = shard_indices.org_vocab_end_index last_added_vocab_end_index = shard_indices.added_vocab_end_index assert computed_vocab_size == vocab_size_padded assert computed_org_vocab_size == org_vocab_size assert computed_added_vocab_size == added_vocab_size # Ensure that the ranges are not overlapping assert len(all_org_tokens) == len(set(all_org_tokens)) assert len(all_added_tokens) == len(set(all_added_tokens)) assert not set(all_org_tokens).intersection(set(all_added_tokens)) token_ids_tensor = torch.tensor(token_ids, dtype=torch.long) reindex_mapping = vocab_embedding.get_sharded_to_full_mapping() assert reindex_mapping is not None or tp_size == 1 if reindex_mapping is not None: reindexed_token_ids = token_ids_tensor[reindex_mapping] expected = torch.tensor(list(range(0, vocab_size)))
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_worker.py
tests/lora/test_worker.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os import random import tempfile from unittest.mock import patch from vllm.config import ( CacheConfig, DeviceConfig, ModelConfig, ParallelConfig, SchedulerConfig, VllmConfig, ) from vllm.config.load import LoadConfig from vllm.config.lora import LoRAConfig from vllm.lora.model_manager import LoRAMapping from vllm.lora.request import LoRARequest from vllm.v1.worker.gpu_worker import Worker MODEL_PATH = "Qwen/Qwen3-0.6B" NUM_LORAS = 16 @patch.dict(os.environ, {"RANK": "0"}) def test_worker_apply_lora(qwen3_lora_files): def set_active_loras(worker: Worker, lora_requests: list[LoRARequest]): lora_mapping = LoRAMapping([], []) worker.model_runner.lora_manager.set_active_adapters( lora_requests, lora_mapping ) model_config = ModelConfig( MODEL_PATH, seed=0, dtype="float16", max_model_len=127, enforce_eager=True, ) vllm_config = VllmConfig( model_config=model_config, load_config=LoadConfig( download_dir=None, load_format="dummy", ), parallel_config=ParallelConfig( pipeline_parallel_size=1, tensor_parallel_size=1, data_parallel_size=1, ), scheduler_config=SchedulerConfig( max_model_len=model_config.max_model_len, is_encoder_decoder=model_config.is_encoder_decoder, runner_type="generate", max_num_batched_tokens=32, max_num_seqs=32, max_num_partial_prefills=32, ), device_config=DeviceConfig("cuda"), cache_config=CacheConfig( block_size=16, swap_space=0, cache_dtype="auto", ), lora_config=LoRAConfig( max_lora_rank=8, max_cpu_loras=NUM_LORAS, max_loras=NUM_LORAS ), ) worker = Worker( vllm_config=vllm_config, local_rank=0, rank=0, distributed_init_method=f"file://{tempfile.mkstemp()[1]}", ) worker.init_device() worker.load_model() set_active_loras(worker, []) assert worker.list_loras() == set() lora_requests = [ LoRARequest(str(i + 1), i + 1, qwen3_lora_files) for i in range(NUM_LORAS) ] set_active_loras(worker, lora_requests) assert worker.list_loras() == { lora_request.lora_int_id for lora_request in lora_requests } for i in range(NUM_LORAS): random.seed(i) iter_lora_requests = random.choices( lora_requests, k=random.randint(1, NUM_LORAS) ) random.shuffle(iter_lora_requests) iter_lora_requests = iter_lora_requests[: -random.randint(0, NUM_LORAS)] set_active_loras(worker, lora_requests) assert worker.list_loras().issuperset( {lora_request.lora_int_id for lora_request in iter_lora_requests} )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_lora_checkpoints.py
tests/lora/test_lora_checkpoints.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.lora.lora_model import LoRAModel from vllm.lora.peft_helper import PEFTHelper from vllm.model_executor.models.baichuan import BaiChuanBaseForCausalLM from vllm.model_executor.models.utils import WeightsMapper lora_lst = ["baichuan7B", "baichuan7B-zero", "baichuan7B-zero-regex", "chatglm3-6b"] BAICHUAN_LORA_MODULES = [ "W_pack", "o_proj", "gate_up_proj", "down_proj", ] @pytest.mark.parametrize("lora_name", lora_lst) def test_load_checkpoints( lora_name, baichuan_lora_files, baichuan_zero_lora_files, baichuan_regex_lora_files, chatglm3_lora_files, ): packed_modules_mapping = BaiChuanBaseForCausalLM.packed_modules_mapping expected_lora_lst: list[str] = [] for module in BAICHUAN_LORA_MODULES: if module in packed_modules_mapping: expected_lora_lst.extend(packed_modules_mapping[module]) else: expected_lora_lst.append(module) expected_lora_modules = set(expected_lora_lst) if lora_name == "baichuan7B": peft_helper = PEFTHelper.from_local_dir( baichuan_lora_files, max_position_embeddings=4096 ) # For the baichuan7B model, load it's LoRA, # and the test should pass. LoRAModel.from_local_checkpoint( baichuan_lora_files, expected_lora_modules, peft_helper=peft_helper, lora_model_id=1, device="cpu", model_vocab_size=64000, ) elif lora_name == "baichuan7B-zero": # Test that the target_modules contain prefix # such as "model.layers.0.self_atten.W_pack", and # the test should pass. peft_helper = PEFTHelper.from_local_dir( baichuan_zero_lora_files, max_position_embeddings=4096 ) LoRAModel.from_local_checkpoint( baichuan_zero_lora_files, expected_lora_modules, peft_helper=peft_helper, lora_model_id=1, device="cpu", model_vocab_size=64000, ) elif lora_name == "baichuan7B-zero-regex": # Test that the `target_modules` in the form of regular expressions, # such as `model\\..*(W_pack|o_proj)`, and the test should pass. peft_helper = PEFTHelper.from_local_dir( baichuan_regex_lora_files, max_position_embeddings=4096 ) LoRAModel.from_local_checkpoint( baichuan_regex_lora_files, expected_lora_modules, peft_helper=peft_helper, lora_model_id=1, device="cpu", model_vocab_size=64000, ) else: # For the baichuan7B model, load chatglm3-6b's LoRA, # and the test should raise the following error. expected_error = "Please verify that the loaded LoRA module is correct" # noqa: E501 peft_helper = PEFTHelper.from_local_dir( chatglm3_lora_files, max_position_embeddings=4096 ) with pytest.raises(ValueError, match=expected_error): LoRAModel.from_local_checkpoint( chatglm3_lora_files, expected_lora_modules, peft_helper=peft_helper, lora_model_id=1, device="cpu", model_vocab_size=64000, ) def test_lora_weights_mapping(baichuan_lora_files): packed_modules_mapping = BaiChuanBaseForCausalLM.packed_modules_mapping expected_lora_lst: list[str] = [] for module in BAICHUAN_LORA_MODULES: if module in packed_modules_mapping: expected_lora_lst.extend(packed_modules_mapping[module]) else: expected_lora_lst.append(module) expected_lora_modules = set(expected_lora_lst) hf_to_vllm_mapper = WeightsMapper( orig_to_new_prefix={ "model.": "language_model.model.", }, orig_to_new_substr={ ".layers.": ".baichuan_layers.", }, ) peft_helper = PEFTHelper.from_local_dir( baichuan_lora_files, max_position_embeddings=4096 ) lora_model = LoRAModel.from_local_checkpoint( baichuan_lora_files, expected_lora_modules, peft_helper=peft_helper, lora_model_id=1, device="cpu", model_vocab_size=64000, weights_mapper=hf_to_vllm_mapper, ) for name in lora_model.loras: assert name.startswith(hf_to_vllm_mapper.orig_to_new_prefix["model."]) assert ".baichuan_layers." in name
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_lora_manager.py
tests/lora/test_lora_manager.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os import pytest import torch from safetensors.torch import load_file from torch import nn from vllm.config import ModelConfig, VllmConfig from vllm.config.lora import LoRAConfig from vllm.lora.layers import ( ColumnParallelLinearWithLoRA, MergedColumnParallelLinearWithLoRA, RowParallelLinearWithLoRA, ) from vllm.lora.lora_model import LoRAModel from vllm.lora.lora_weights import LoRALayerWeights, PackedLoRALayerWeights from vllm.lora.model_manager import ( DEFAULT_LANGUAGE_WRAPPER_KEY, LoRAMapping, LoRAModelManager, LRUCacheLoRAModelManager, ) from vllm.lora.peft_helper import PEFTHelper from vllm.lora.request import LoRARequest from vllm.lora.worker_manager import LRUCacheWorkerLoRAManager, WorkerLoRAManager from vllm.platforms import current_platform from .utils import create_peft_lora EMBEDDING_MODULES = { "embed_tokens": "input_embeddings", "lm_head": "output_embeddings", } DEVICES = ( [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)] if current_platform.is_cuda_alike() else ["cpu"] ) DEFAULT_DTYPE = torch.get_default_dtype() @pytest.mark.parametrize("device", DEVICES) def test_from_lora_tensors(qwen3_lora_files, device): tensors = load_file(os.path.join(qwen3_lora_files, "adapter_model.safetensors")) peft_helper = PEFTHelper.from_local_dir( qwen3_lora_files, max_position_embeddings=4096 ) lora_model = LoRAModel.from_lora_tensors( 1, tensors, peft_helper=peft_helper, device=device, ) for module_name, lora in lora_model.loras.items(): assert lora.module_name == module_name assert lora.rank == 8 assert lora.lora_alpha == 32 assert lora.lora_a is not None assert lora.lora_b is not None assert lora.lora_a.device == torch.device(device) assert lora.lora_b.device == torch.device(device) assert lora.lora_a.shape[0] == lora.lora_b.shape[1], ( f"{lora.lora_a.shape=}, {lora.lora_b.shape=}" ) assert lora.lora_a.shape[0] == 8 def create_lora( lora_id: int, model: nn.Module, sub_modules: list[str], device: torch.device ) -> LoRAModel: loras: dict[str, LoRALayerWeights] = {} for name in sub_modules: w = model.get_submodule(name).weight loras[name] = LoRALayerWeights( name, 8, 16, torch.rand([8, w.shape[1]], device=device), torch.rand([w.shape[0], 8], device=device), ) return LoRAModel(lora_id, 8, loras) def create_packed_lora( lora_id: int, model: nn.Module, module_name, replaced_module_names, device: torch.device, empty_replaced_module_name=None, ) -> LoRAModel: w = model.get_submodule(module_name).weight loras: dict[str, LoRALayerWeights] = {} for replaced_module_name in replaced_module_names: if replaced_module_name == empty_replaced_module_name: continue loras[replaced_module_name] = LoRALayerWeights( replaced_module_name, 8, 16, torch.rand([8, w.shape[1]], device=device), torch.rand([w.shape[0] // len(replaced_module_names), 8], device=device), ) return LoRAModel(lora_id, 8, loras) def test_replace_submodules(dist_init, dummy_model): model = dummy_model manager = LoRAModelManager( model, 1, 1, 1, LoRAConfig( max_lora_rank=8, max_cpu_loras=8, max_loras=8, lora_dtype=DEFAULT_DTYPE ), torch.device(DEVICES[0]), ) model = manager.model assert isinstance(model.get_submodule("dense1"), ColumnParallelLinearWithLoRA) assert isinstance( model.get_submodule("layer1.dense1"), ColumnParallelLinearWithLoRA ) assert isinstance(model.get_submodule("dense2"), RowParallelLinearWithLoRA) assert isinstance(model.get_submodule("layer1.dense2"), RowParallelLinearWithLoRA) @pytest.mark.parametrize("device", DEVICES) def test_lora_model_manager(dist_init, dummy_model, device): model = dummy_model model_lora1 = create_lora( 1, model, ["layer1.dense1", "dense2", "lm_head"], device=device ) model_lora2 = create_lora(2, model, ["dense1", "dense2", "lm_head"], device=device) model_lora3 = create_lora(3, model, ["dense1", "dense2", "lm_head"], device=device) manager = LoRAModelManager( model, 2, 2, 2, LoRAConfig( max_lora_rank=8, max_cpu_loras=3, max_loras=2, lora_dtype=DEFAULT_DTYPE ), device=device, ) assert all(x is None for x in manager.lora_index_to_id) assert manager.add_adapter(model_lora1) assert manager.activate_adapter(1) assert manager.lora_index_to_id[0] == 1 assert not manager.add_adapter(model_lora1) assert not manager.activate_adapter(1) assert manager.add_adapter(model_lora2) assert manager.activate_adapter(2) assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] == 2 assert not manager.add_adapter(model_lora2) assert not manager.activate_adapter(2) assert manager.add_adapter(model_lora3) assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] == 2 with pytest.raises(ValueError): assert manager.activate_adapter(3) assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] == 2 assert manager.remove_adapter(model_lora2.id) assert manager.lora_index_to_id[1] is None assert not manager.remove_adapter(model_lora2.id) assert manager.remove_adapter(model_lora1.id) assert not manager.remove_adapter(model_lora1.id) assert manager.add_adapter(model_lora1) assert manager.lora_index_to_id[0] is None assert manager.lora_index_to_id[1] is None assert manager.add_adapter(model_lora2) assert manager.activate_adapter(3) assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] is None assert manager.activate_adapter(2) assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 2 assert manager.device == device assert ( manager.punica_wrapper_mapping.get(DEFAULT_LANGUAGE_WRAPPER_KEY).device == device ) assert hasattr(manager, "supported_lora_modules") assert sorted(manager.supported_lora_modules) == [ "dense1", "dense2", "lm_head", "output", ] @pytest.mark.parametrize("device", DEVICES) def test_lora_lru_cache_model_manager(dist_init, dummy_model, device): model = dummy_model model_lora1 = create_lora( 1, model, ["layer1.dense1", "dense2", "lm_head"], device=device ) model_lora2 = create_lora(2, model, ["dense1", "dense2", "lm_head"], device=device) model_lora3 = create_lora(3, model, ["dense1", "dense2", "lm_head"], device=device) manager = LRUCacheLoRAModelManager( model, 2, 2, 2, LoRAConfig( max_lora_rank=8, max_cpu_loras=3, max_loras=2, lora_dtype=DEFAULT_DTYPE ), device=device, ) assert all(x is None for x in manager.lora_index_to_id) assert manager.add_adapter(model_lora1) assert manager.activate_adapter(1) assert manager.lora_index_to_id[0] == 1 assert not manager.add_adapter(model_lora1) assert not manager.activate_adapter(1) assert manager.add_adapter(model_lora2) assert manager.activate_adapter(2) assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] == 2 assert not manager.add_adapter(model_lora2) assert not manager.activate_adapter(2) assert manager.add_adapter(model_lora3) assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] == 2 assert manager.activate_adapter(3) assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 2 assert manager.remove_adapter(model_lora2.id) assert manager.lora_index_to_id[1] is None assert not manager.remove_adapter(model_lora2.id) assert manager.remove_adapter(model_lora1.id) assert not manager.remove_adapter(model_lora1.id) assert manager.add_adapter(model_lora1) assert manager.activate_adapter(1) assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 1 assert manager.add_adapter(model_lora2) assert manager.deactivate_adapter(3) assert manager.lora_index_to_id[0] is None assert manager.lora_index_to_id[1] == 1 assert manager.activate_adapter(2) assert manager.lora_index_to_id[0] == 2 assert manager.lora_index_to_id[1] == 1 assert manager.activate_adapter(3) assert manager.lora_index_to_id[0] == 2 assert manager.lora_index_to_id[1] == 3 assert manager.pin_adapter(2) assert manager.lora_index_to_id[0] == 2 assert manager.lora_index_to_id[1] == 3 assert manager.activate_adapter(1) assert manager.lora_index_to_id[0] == 2 assert manager.lora_index_to_id[1] == 1 assert manager.deactivate_adapter(2) assert manager.lora_index_to_id[0] is None assert manager.lora_index_to_id[1] == 1 assert manager.activate_adapter(3) assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 1 assert manager.pin_adapter(3) assert manager.pin_adapter(1) with pytest.raises(RuntimeError): assert manager.pin_adapter(2) assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 1 with pytest.raises(RuntimeError): assert manager.activate_adapter(2) assert manager.deactivate_adapter(3) assert manager.pin_adapter(2) assert manager.lora_index_to_id[0] == 2 assert manager.lora_index_to_id[1] == 1 assert manager.remove_adapter(3) with pytest.raises(ValueError): assert manager.pin_adapter(3) assert ( manager.punica_wrapper_mapping.get(DEFAULT_LANGUAGE_WRAPPER_KEY).device == device ) assert manager.device == device @pytest.mark.parametrize("device", DEVICES) def test_lru_lora_model_manager(dist_init, dummy_model, device): # This tests just the LRU cache functionality, everything else is # tested in test_lora_model_manager model = dummy_model model_lora1 = create_lora( 1, model, ["layer1.dense1", "dense2", "lm_head"], device=device ) model_lora2 = create_lora(2, model, ["dense1", "dense2", "lm_head"], device=device) model_lora3 = create_lora(3, model, ["dense1", "dense2", "lm_head"], device=device) model_lora4 = create_lora(4, model, ["dense1", "dense2", "lm_head"], device=device) manager = LRUCacheLoRAModelManager( model, 2, 2, 2, LoRAConfig( max_lora_rank=8, max_cpu_loras=2, max_loras=2, lora_dtype=DEFAULT_DTYPE ), device=device, ) assert all(x is None for x in manager.lora_index_to_id) # Add up to capacity assert manager.add_adapter(model_lora1) assert manager.add_adapter(model_lora2) assert manager.activate_adapter(1) assert manager.activate_adapter(2) assert set(manager.list_adapters()) == {1, 2} assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] == 2 # Add over capacity assert manager.add_adapter(model_lora3) assert manager.add_adapter(model_lora4) assert manager.activate_adapter(3) assert manager.activate_adapter(4) assert set(manager.list_adapters()) == {3, 4} assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 4 # Add 3 again to move it to the top and then add 2 # should return false since it's in already assert not manager.add_adapter(model_lora3) assert not manager.activate_adapter(3) assert manager.add_adapter(model_lora2) assert manager.activate_adapter(2) assert set(manager.list_adapters()) == {3, 2} assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 2 # Remove manually assert manager.remove_adapter(3) assert not manager.remove_adapter(3) assert set(manager.list_adapters()) == {2} assert manager.lora_index_to_id[0] is None assert manager.lora_index_to_id[1] == 2 assert manager.add_adapter(model_lora3) assert manager.activate_adapter(3) assert manager.add_adapter(model_lora4) assert manager.activate_adapter(4) assert set(manager.list_adapters()) == {3, 4} assert manager.lora_index_to_id[0] == 3 assert manager.lora_index_to_id[1] == 4 assert manager.remove_oldest_adapter() assert set(manager.list_adapters()) == {4} assert manager.lora_index_to_id[0] is None assert manager.lora_index_to_id[1] == 4 assert manager.remove_oldest_adapter() assert set(manager.list_adapters()) == set() assert all(x is None for x in manager.lora_index_to_id) assert not manager.remove_oldest_adapter() assert set(manager.list_adapters()) == set() assert all(x is None for x in manager.lora_index_to_id) # pinning assert manager.add_adapter(model_lora3) assert manager.activate_adapter(3) assert manager.add_adapter(model_lora4) assert manager.activate_adapter(4) assert set(manager.list_adapters()) == {3, 4} with pytest.raises(ValueError): assert manager.pin_adapter(1) assert manager.pin_adapter(3) # Remove manually assert manager.remove_adapter(3) assert not manager.remove_adapter(3) assert set(manager.list_adapters()) == {4} assert manager.lora_index_to_id[0] is None assert manager.lora_index_to_id[1] == 4 assert manager.add_adapter(model_lora1) assert manager.pin_adapter(1) assert manager.add_adapter(model_lora2) assert manager.activate_adapter(2) assert set(manager.list_adapters()) == {1, 2} assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] == 2 assert manager.remove_oldest_adapter() assert set(manager.list_adapters()) == {1} assert manager.lora_index_to_id[0] == 1 assert manager.lora_index_to_id[1] is None with pytest.raises(RuntimeError): assert manager.remove_oldest_adapter() assert set(manager.list_adapters()) == {1} assert ( manager.punica_wrapper_mapping.get(DEFAULT_LANGUAGE_WRAPPER_KEY).device == device ) assert manager.device == device @pytest.mark.parametrize("device", DEVICES) def test_lru_cache_worker_adapter_manager(dist_init, dummy_model, device, tmp_path): lora_config = LoRAConfig( max_lora_rank=8, max_cpu_loras=4, max_loras=4, lora_dtype=DEFAULT_DTYPE ) dummy_lora_files = f"{tmp_path}/lora_adapter" os.makedirs(dummy_lora_files, exist_ok=True) create_peft_lora( dummy_model, save_dir=dummy_lora_files, target_modules=["layer1.dense1", "dense2"], lora_dtype=DEFAULT_DTYPE, ) model_config = ModelConfig(max_model_len=16) vllm_config = VllmConfig(model_config=model_config, lora_config=lora_config) vllm_config.scheduler_config.max_num_seqs = 4 vllm_config.scheduler_config.max_num_batched_tokens = 2 worker_adapter_manager = LRUCacheWorkerLoRAManager( vllm_config, device, EMBEDDING_MODULES ) worker_adapter_manager.max_num_seqs = 4 worker_adapter_manager.max_num_batched_tokens = 2 worker_adapter_manager.create_lora_manager(dummy_model) mapping = LoRAMapping([], []) worker_adapter_manager.set_active_adapters( [LoRARequest("1", 1, dummy_lora_files), LoRARequest("2", 2, dummy_lora_files)], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 2} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 2 worker_adapter_manager.set_active_adapters( [ LoRARequest("1", 1, dummy_lora_files), LoRARequest("3", 3, dummy_lora_files), LoRARequest("4", 4, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 2, 3, 4} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 2 assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] == 3 assert worker_adapter_manager._adapter_manager.lora_index_to_id[3] == 4 worker_adapter_manager.set_active_adapters( [ LoRARequest("1", 1, dummy_lora_files), LoRARequest("2", 2, dummy_lora_files), LoRARequest("5", 5, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 2, 4, 5} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 2 assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] == 5 assert worker_adapter_manager._adapter_manager.lora_index_to_id[3] == 4 worker_adapter_manager.set_active_adapters( [ LoRARequest("1", 1, dummy_lora_files), LoRARequest("1", 1, dummy_lora_files), LoRARequest("1", 1, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 2, 4, 5} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 2 assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] == 5 assert worker_adapter_manager._adapter_manager.lora_index_to_id[3] == 4 worker_adapter_manager.set_active_adapters( [ LoRARequest("6", 6, dummy_lora_files), LoRARequest("7", 7, dummy_lora_files), LoRARequest("8", 8, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 6, 7, 8} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 7 assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] == 8 assert worker_adapter_manager._adapter_manager.lora_index_to_id[3] == 6 # Over capacity with pytest.raises(RuntimeError): worker_adapter_manager.set_active_adapters( [ LoRARequest("10", 10, dummy_lora_files), LoRARequest("11", 11, dummy_lora_files), LoRARequest("12", 12, dummy_lora_files), LoRARequest("13", 13, dummy_lora_files), LoRARequest("14", 14, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.device == device punica_wrapper = worker_adapter_manager._adapter_manager.punica_wrapper_mapping.get( DEFAULT_LANGUAGE_WRAPPER_KEY ) assert punica_wrapper.device == device @pytest.mark.parametrize("device", DEVICES) def test_worker_adapter_manager(dist_init, dummy_model_gate_up, device, tmp_path): # Should remove every LoRA not specified in the request. lora_config = LoRAConfig( max_lora_rank=8, max_cpu_loras=4, max_loras=4, lora_dtype=DEFAULT_DTYPE ) model_config = ModelConfig(max_model_len=16) vllm_config = VllmConfig(model_config=model_config, lora_config=lora_config) vllm_config.scheduler_config.max_num_seqs = 4 vllm_config.scheduler_config.max_num_batched_tokens = 2 worker_adapter_manager = WorkerLoRAManager(vllm_config, device, EMBEDDING_MODULES) worker_adapter_manager.vocab_size = dummy_model_gate_up.unpadded_vocab_size worker_adapter_manager.create_lora_manager(dummy_model_gate_up) dummy_lora_files = f"{tmp_path}/lora_adapter" os.makedirs(dummy_lora_files, exist_ok=True) create_peft_lora( dummy_model_gate_up, save_dir=dummy_lora_files, target_modules=["layer1.dense1", "dense2"], lora_dtype=DEFAULT_DTYPE, ) mapping = LoRAMapping([], []) worker_adapter_manager.set_active_adapters( [LoRARequest("1", 1, dummy_lora_files), LoRARequest("2", 2, dummy_lora_files)], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 2} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 2 worker_adapter_manager.set_active_adapters( [ LoRARequest("1", 1, dummy_lora_files), LoRARequest("3", 3, dummy_lora_files), LoRARequest("4", 4, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 3, 4} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 3 assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] == 4 worker_adapter_manager.set_active_adapters( [ LoRARequest("1", 1, dummy_lora_files), LoRARequest("2", 2, dummy_lora_files), LoRARequest("5", 5, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {1, 2, 5} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 2 assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] == 5 worker_adapter_manager.set_active_adapters( [ LoRARequest("1", 1, dummy_lora_files), LoRARequest("1", 1, dummy_lora_files), LoRARequest("1", 1, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {1} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 1 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] is None assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] is None worker_adapter_manager.set_active_adapters( [ LoRARequest("6", 6, dummy_lora_files), LoRARequest("7", 7, dummy_lora_files), LoRARequest("8", 8, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.list_adapters() == {6, 7, 8} assert worker_adapter_manager._adapter_manager.lora_index_to_id[0] == 8 assert worker_adapter_manager._adapter_manager.lora_index_to_id[1] == 6 assert worker_adapter_manager._adapter_manager.lora_index_to_id[2] == 7 # Over capacity with pytest.raises(RuntimeError): worker_adapter_manager.set_active_adapters( [ LoRARequest("10", 10, dummy_lora_files), LoRARequest("11", 11, dummy_lora_files), LoRARequest("12", 12, dummy_lora_files), LoRARequest("13", 13, dummy_lora_files), LoRARequest("14", 14, dummy_lora_files), ], mapping, ) assert worker_adapter_manager.device == device punica_wrapper = worker_adapter_manager._adapter_manager.punica_wrapper_mapping.get( DEFAULT_LANGUAGE_WRAPPER_KEY ) assert punica_wrapper.device == device @pytest.mark.parametrize("device", DEVICES) def test_packed_loras(dist_init, dummy_model_gate_up, device): model = dummy_model_gate_up model_lora = create_packed_lora( 1, model, module_name="gate_up_proj", replaced_module_names=["gate_proj", "up_proj"], device=device, ) model_lora1 = create_packed_lora( 2, model, module_name="gate_up_proj", replaced_module_names=["gate_proj", "up_proj"], device=device, empty_replaced_module_name="gate_proj", ) manager = LoRAModelManager( model, 2, 2, 2, LoRAConfig( max_lora_rank=8, max_cpu_loras=2, max_loras=2, lora_dtype=DEFAULT_DTYPE ), device=device, ) model = manager.model assert isinstance( model.get_submodule("gate_up_proj"), MergedColumnParallelLinearWithLoRA ) # Verify packed lora is correct model_lora_clone = model_lora.clone(1) model_lora_clone1 = model_lora1.clone(1) assert manager.add_adapter(model_lora) assert manager.add_adapter(model_lora1) assert model_lora.get_lora("gate_proj") is None assert model_lora.get_lora("up_proj") is None assert model_lora1.get_lora("up_proj") is None packed_lora = model_lora.get_lora("gate_up_proj") assert packed_lora and isinstance(packed_lora, PackedLoRALayerWeights) torch.testing.assert_close( packed_lora.lora_a[0], model_lora_clone.get_lora("gate_proj").lora_a ) torch.testing.assert_close( packed_lora.lora_b[0], model_lora_clone.get_lora("gate_proj").lora_b ) torch.testing.assert_close( packed_lora.lora_a[1], model_lora_clone.get_lora("up_proj").lora_a ) torch.testing.assert_close( packed_lora.lora_b[1], model_lora_clone.get_lora("up_proj").lora_b ) packed_lora1 = model_lora1.get_lora("gate_up_proj") assert packed_lora1 and isinstance(packed_lora1, PackedLoRALayerWeights) assert packed_lora1.lora_a[0] is None assert packed_lora1.lora_b[0] is None torch.testing.assert_close( packed_lora1.lora_a[1], model_lora_clone1.get_lora("up_proj").lora_a ) torch.testing.assert_close( packed_lora1.lora_b[1], model_lora_clone1.get_lora("up_proj").lora_b )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/lora/test_minicpmv_tp.py
tests/lora/test_minicpmv_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import vllm from vllm.assets.image import ImageAsset from vllm.lora.request import LoRARequest from vllm.platforms import current_platform from ..utils import multi_gpu_test MODEL_PATH = "openbmb/MiniCPM-Llama3-V-2_5" PROMPT_TEMPLATE = ( "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" "(<image>./</image>)\nWhat is in the image?<|eot_id|>" "<|start_header_id|>assistant<|end_header_id|>\n\n" ) IMAGE_ASSETS = [ ImageAsset("stop_sign"), ] # After fine-tuning with LoRA, all generated content should start begin `A`. EXPECTED_OUTPUT = [ "A red and white stop sign with a Chinese archway in the background featuring red lanterns and gold accents.", # noqa: E501 ] def do_sample(llm: vllm.LLM, lora_path: str, lora_id: int) -> list[str]: sampling_params = vllm.SamplingParams( temperature=0, max_tokens=5, stop_token_ids=[128001, 128009], # eos_id, eot_id ) inputs = [ { "prompt": PROMPT_TEMPLATE, "multi_modal_data": {"image": asset.pil_image}, } for asset in IMAGE_ASSETS ] outputs = llm.generate( inputs, sampling_params, lora_request=LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None, ) # Print the outputs. generated_texts: list[str] = [] for output in outputs: generated_text = output.outputs[0].text.strip() generated_texts.append(generated_text) print(f"Generated text: {generated_text!r}") return generated_texts def test_minicpmv_lora(minicpmv_lora_files): llm = vllm.LLM( MODEL_PATH, max_num_seqs=2, enable_lora=True, max_loras=2, max_lora_rank=8, enforce_eager=True, max_model_len=2048, limit_mm_per_prompt={"image": 2, "video": 0}, trust_remote_code=True, ) output1 = do_sample(llm, minicpmv_lora_files, lora_id=1) for i in range(len(EXPECTED_OUTPUT)): assert EXPECTED_OUTPUT[i].startswith(output1[i]) output2 = do_sample(llm, minicpmv_lora_files, lora_id=2) for i in range(len(EXPECTED_OUTPUT)): assert EXPECTED_OUTPUT[i].startswith(output2[i]) @pytest.mark.skipif( current_platform.is_cuda_alike(), reason="Skipping to avoid redundant model tests" ) @multi_gpu_test(num_gpus=4) def test_minicpmv_tp4_wo_fully_sharded_loras(minicpmv_lora_files): llm = vllm.LLM( MODEL_PATH, enable_lora=True, max_num_seqs=2, max_loras=4, max_lora_rank=64, tensor_parallel_size=4, limit_mm_per_prompt={"image": 2, "video": 0}, trust_remote_code=True, ) output_tp = do_sample(llm, minicpmv_lora_files, lora_id=1) for i in range(len(EXPECTED_OUTPUT)): assert EXPECTED_OUTPUT[i].startswith(output_tp[i]) @pytest.mark.skipif( current_platform.is_cuda_alike(), reason="Skipping to avoid redundant model tests" ) @multi_gpu_test(num_gpus=4) def test_minicpmv_tp4_fully_sharded_loras(minicpmv_lora_files): llm = vllm.LLM( MODEL_PATH, enable_lora=True, max_num_seqs=2, max_loras=2, max_lora_rank=8, tensor_parallel_size=4, trust_remote_code=True, limit_mm_per_prompt={"image": 1, "video": 0}, fully_sharded_loras=True, ) output_tp = do_sample(llm, minicpmv_lora_files, lora_id=1) for i in range(len(EXPECTED_OUTPUT)): assert EXPECTED_OUTPUT[i].startswith(output_tp[i]) output_tp = do_sample(llm, minicpmv_lora_files, lora_id=2) for i in range(len(EXPECTED_OUTPUT)): assert EXPECTED_OUTPUT[i].startswith(output_tp[i])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/detokenizer/test_min_tokens.py
tests/detokenizer/test_min_tokens.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from transformers import AutoTokenizer from vllm import SamplingParams from vllm.v1.engine import EngineCoreRequest from vllm.v1.engine.detokenizer import FastIncrementalDetokenizer PROMPT = "Hello, my name is Lee, and I'm a student in the " + "college of engineering" @pytest.mark.parametrize( "min_tokens,stop,truth", [ (0, None, " is Lee, and I'm a student in the college of engineering"), (0, "e", " is L"), (5, "e", " is Lee, and I'm a stud"), ], ) def test_min_tokens_with_stop(min_tokens: int, stop: str, truth: str): """Test for a specific min_tokens and stop. See https://github.com/vllm-project/vllm/pull/22014 """ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m") all_prompt_ids = tokenizer(PROMPT, add_special_tokens=False).input_ids # The prompt is "Hello, my name is" prompt_token_ids = all_prompt_ids[:4] params = SamplingParams( stop=stop, min_tokens=min_tokens, ) request = EngineCoreRequest( request_id="", prompt_token_ids=prompt_token_ids, mm_features=None, sampling_params=params, pooling_params=None, eos_token_id=None, arrival_time=0.0, lora_request=None, cache_salt=None, data_parallel_rank=None, ) detokenizer = FastIncrementalDetokenizer(tokenizer, request) detokenizer.update(all_prompt_ids[4:], False) assert detokenizer.output_text == truth
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/detokenizer/test_stop_strings.py
tests/detokenizer/test_stop_strings.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any import pytest from vllm import LLM, SamplingParams MODEL = "meta-llama/llama-2-7b-hf" MAX_TOKENS = 200 def _test_stopping( llm: LLM, expected_output: str, expected_reason: Any, stop: list[str] | None = None, stop_token_ids: list[int] | None = None, include_in_output: bool = False, ) -> None: output = llm.generate( "A story about vLLM:\n", SamplingParams( temperature=0.0, max_tokens=MAX_TOKENS, stop=stop, stop_token_ids=stop_token_ids, include_stop_str_in_output=include_in_output, ), )[0].outputs[0] assert output is not None assert output.text == expected_output assert output.stop_reason == expected_reason def _stop_basic(llm): _test_stopping( llm, stop=["."], include_in_output=False, expected_output="VLLM is a 100% volunteer organization", expected_reason=".", ) _test_stopping( llm, stop=["."], include_in_output=True, expected_output="VLLM is a 100% volunteer organization.", expected_reason=".", ) def _stop_multi_tokens(llm): _test_stopping( llm, stop=["group of peo", "short"], include_in_output=False, expected_output="VLLM is a 100% volunteer organization. We are a ", expected_reason="group of peo", ) _test_stopping( llm, stop=["group of peo", "short"], include_in_output=True, expected_output="VLLM is a 100% volunteer organization. We are a group of peo", expected_reason="group of peo", ) def _stop_partial_token(llm): _test_stopping( llm, stop=["gani"], include_in_output=False, expected_output="VLLM is a 100% volunteer or", expected_reason="gani", ) _test_stopping( llm, stop=["gani"], include_in_output=True, expected_output="VLLM is a 100% volunteer organi", expected_reason="gani", ) def _stop_token_id(llm): # token id 13013 => " organization" _test_stopping( llm, stop_token_ids=[13013], include_in_output=False, expected_output="VLLM is a 100% volunteer", expected_reason=13013, ) _test_stopping( llm, stop_token_ids=[13013], include_in_output=True, expected_output="VLLM is a 100% volunteer organization", expected_reason=13013, ) @pytest.mark.skip_global_cleanup def test_stop_strings(): llm = LLM(MODEL, enforce_eager=True) _stop_basic(llm) _stop_multi_tokens(llm) _stop_partial_token(llm) # FIXME: this does not respect include_in_output=False # _stop_token_id(llm)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/detokenizer/test_stop_string_while_stop_model_terminates.py
tests/detokenizer/test_stop_string_while_stop_model_terminates.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.sampling_params import SamplingParams from vllm.v1.engine import EngineCoreRequest from vllm.v1.engine.detokenizer import BaseIncrementalDetokenizer @pytest.fixture(params=[True, False]) def include_stop_str_in_output(request): return request.param class _DummyDetokenizer(BaseIncrementalDetokenizer): def __init__(self, request: EngineCoreRequest): super().__init__(request) def decode_next(self, next_token_id: int) -> str: # Map token id to single ASCII character for deterministic testing. return chr(next_token_id) def _make_request(stop, include_stop_str_in_output: bool, min_tokens: int = 0): params = SamplingParams( stop=stop, include_stop_str_in_output=include_stop_str_in_output, min_tokens=min_tokens, ) # Keep other fields minimal for unit test purposes. req = EngineCoreRequest( request_id="test", prompt_token_ids=[], mm_features=None, sampling_params=params, pooling_params=None, eos_token_id=None, arrival_time=0.0, lora_request=None, cache_salt=None, data_parallel_rank=None, ) return req def test_stop_string_while_stop_token_terminates(include_stop_str_in_output: bool): """ This test verifies that the detokenizer correctly handles the case where the generated token sequence contains both: - a stop token - an <eos> token The detokenizer should respect the stop string and truncate the output accordingly. Imagine the following sequence: - "abcdeZ" is generated, where "Z" is the <eos> token. - "cd" is the stop string. If include_stop_str_in_output=False, the detokenizer should truncate the output to "ab" because the stop string "cd" is excluded. If include_stop_str_in_output=True, the detokenizer should include the stop string "cd" in the output, resulting in "abcd". This verifies the behavioral change introduced in BaseIncrementalDetokenizer where stop-string evaluation occurs before the early-return on stop_terminated. """ # Generate text "abcdeZ" and tokenize it. generated_text = "abcde" eos_token = "Z" stop_string = "cd" generated_text = generated_text + eos_token token_ids = [ord(c) for c in generated_text] # Create a request with the stop string and initialize the detokenizer. req = _make_request( stop=[stop_string], include_stop_str_in_output=include_stop_str_in_output ) detok = _DummyDetokenizer(req) # Simulate that the last token ('Z') is a stop token (stop_terminated=True). result = detok.update(new_token_ids=token_ids, stop_terminated=True) # The update should not report a stop string assert result == stop_string # Output text should reflect stop-string handling: # - include_stop_str_in_output=False => exclude "cd" => "ab" # - include_stop_str_in_output=True => include "cd" => "abcd" expected_text = "abcd" if include_stop_str_in_output else "ab" assert detok.output_text == expected_text # The skipped final token should still be recorded in token_ids. assert detok.output_token_ids == token_ids # get_next_output_text should return the full text when finished=True. # (Buffering only applies during streaming when finished=False.) assert detok.get_next_output_text(finished=True, delta=False) == expected_text
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/detokenizer/test_stop_reason.py
tests/detokenizer/test_stop_reason.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Test the different finish_reason="stop" situations during generation: 1. One of the provided stop strings 2. One of the provided stop tokens 3. The EOS token Run `pytest tests/engine/test_stop_reason.py`. """ import pytest import transformers from vllm import SamplingParams MODEL = "distilbert/distilgpt2" STOP_STR = "." SEED = 42 MAX_TOKENS = 1024 @pytest.fixture def vllm_model(vllm_runner): with vllm_runner(MODEL) as vllm_model: yield vllm_model def test_stop_reason(vllm_model, example_prompts): tokenizer = transformers.AutoTokenizer.from_pretrained(MODEL) stop_token_id = tokenizer.convert_tokens_to_ids(STOP_STR) llm = vllm_model.llm # test stop token outputs = llm.generate( example_prompts, sampling_params=SamplingParams( ignore_eos=True, seed=SEED, max_tokens=MAX_TOKENS, stop_token_ids=[stop_token_id], ), ) for output in outputs: output = output.outputs[0] assert output.finish_reason == "stop" assert output.stop_reason == stop_token_id # test stop string outputs = llm.generate( example_prompts, sampling_params=SamplingParams( ignore_eos=True, seed=SEED, max_tokens=MAX_TOKENS, stop="." ), ) for output in outputs: output = output.outputs[0] assert output.finish_reason == "stop" assert output.stop_reason == STOP_STR # test EOS token outputs = llm.generate( example_prompts, sampling_params=SamplingParams(seed=SEED, max_tokens=MAX_TOKENS), ) for output in outputs: output = output.outputs[0] assert output.finish_reason == "length" or ( output.finish_reason == "stop" and output.stop_reason is None )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/detokenizer/test_disable_detokenization.py
tests/detokenizer/test_disable_detokenization.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.entrypoints.llm import LLM from vllm.sampling_params import SamplingParams @pytest.mark.skip_v1 @pytest.mark.parametrize("model", ["distilbert/distilgpt2"]) def test_computed_prefix_blocks(model: str): # This test checks if the engine generates completions both with and # without optional detokenization, that detokenization includes text # and no-detokenization doesn't, and that both completions have the same # token_ids. prompt = ( "You are a helpful assistant. How do I build a car from cardboard and " "paper clips? Is there an easy to follow video tutorial available " "online for free?" ) llm = LLM(model=model) sampling_params = SamplingParams(max_tokens=10, temperature=0.0, detokenize=False) outputs_no_detokenization = llm.generate(prompt, sampling_params)[0].outputs[0] sampling_params.detokenize = True outputs_with_detokenization = llm.generate(prompt, sampling_params)[0].outputs[0] assert outputs_no_detokenization.text == "" assert outputs_with_detokenization.text != "" assert outputs_no_detokenization.token_ids == outputs_with_detokenization.token_ids
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/detokenizer/__init__.py
tests/detokenizer/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_fla_layernorm_guard.py
tests/kernels/test_fla_layernorm_guard.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch import torch.nn.functional as F from vllm.model_executor.layers.fla.ops.layernorm_guard import ( layer_norm_fwd, layernorm_fn, rms_norm_ref, ) from vllm.platforms import current_platform def layer_norm_ref( x, weight, bias, z=None, eps=1e-6, group_size=None, norm_before_gate=True, is_rms_norm=False, ): """Reference implementation for both layer norm and RMS norm.""" if is_rms_norm: # Use the imported rms_norm_ref for RMS norm cases return rms_norm_ref( x, weight, bias, z=z, eps=eps, group_size=group_size, norm_before_gate=norm_before_gate, upcast=True, ) # Layer norm implementation dtype = x.dtype x = x.float() weight = weight.float() bias = bias.float() if bias is not None else None z = z.float() if z is not None else None if z is not None and not norm_before_gate: x = x * F.silu(z) if group_size is None: # Layer norm: subtract mean mean = x.mean(dim=-1, keepdim=True) var = ((x - mean).square()).mean(dim=-1, keepdim=True) rstd = 1 / torch.sqrt(var + eps) out = (x - mean) * rstd * weight if bias is not None: out = out + bias else: # Group norm from einops import rearrange x_group = rearrange(x, "... (g d) -> ... g d", d=group_size) mean = x_group.mean(dim=-1, keepdim=True) var = ((x_group - mean).square()).mean(dim=-1, keepdim=True) rstd = 1 / torch.sqrt(var + eps) x_group = (x_group - mean) * rstd out = rearrange(x_group, "... g d -> ... (g d)") * weight if bias is not None: out = out + bias if z is not None and norm_before_gate: out *= F.silu(z) return out.to(dtype) DTYPES = [torch.bfloat16, torch.float32] # Test various M sizes to ensure rows_per_block logic works correctly NUM_TOKENS = [ 1, 7, 16, 63, 128, 256, 512, 1024, 2048, 4096, 5789, 8189, 8191, 16383, 32767, ] HIDDEN_SIZES = [64, 128, 256, 1024] GROUP_SIZES = [None, 64, 128] # None means full hidden size NORM_BEFORE_GATE = [True, False] IS_RMS_NORM = [True, False] SEEDS = [0, 42] @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("is_rms_norm", IS_RMS_NORM) @torch.inference_mode() def test_layer_norm_fwd_basic( num_tokens: int, hidden_size: int, dtype: torch.dtype, seed: int, is_rms_norm: bool, ) -> None: """Test basic layer norm forward pass without z (gate) tensor.""" current_platform.seed_everything(seed) device = torch.device("cuda:0") # Create inputs x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) weight = torch.randn(hidden_size, dtype=dtype, device=device) bias = None if is_rms_norm else torch.randn(hidden_size, dtype=dtype, device=device) eps = 1e-6 # Run the triton kernel out, mean, rstd = layer_norm_fwd( x, weight, bias, eps, z=None, is_rms_norm=is_rms_norm ) # Run reference implementation ref_out = layer_norm_ref(x, weight, bias, z=None, eps=eps, is_rms_norm=is_rms_norm) # Check outputs assert out.shape == x.shape assert out.dtype == x.dtype torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) # Check mean and rstd shapes if not is_rms_norm: assert mean.shape == (num_tokens,) assert rstd.shape == (num_tokens,) @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("hidden_size", [128, 256, 1024]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("norm_before_gate", NORM_BEFORE_GATE) @pytest.mark.parametrize("is_rms_norm", IS_RMS_NORM) @torch.inference_mode() def test_layer_norm_fwd_with_gate( num_tokens: int, hidden_size: int, dtype: torch.dtype, norm_before_gate: bool, is_rms_norm: bool, ) -> None: """Test layer norm forward pass with z (gate) tensor.""" current_platform.seed_everything(42) device = torch.device("cuda:0") # Create inputs x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) z = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) weight = torch.randn(hidden_size, dtype=dtype, device=device) bias = None if is_rms_norm else torch.randn(hidden_size, dtype=dtype, device=device) eps = 1e-6 # Run the triton kernel out, mean, rstd = layer_norm_fwd( x, weight, bias, eps, z=z, norm_before_gate=norm_before_gate, is_rms_norm=is_rms_norm, ) # Run reference implementation ref_out = layer_norm_ref( x, weight, bias, z=z, eps=eps, norm_before_gate=norm_before_gate, is_rms_norm=is_rms_norm, ) # Check outputs assert out.shape == x.shape assert out.dtype == x.dtype torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) @pytest.mark.parametrize("num_tokens", [128, 512]) @pytest.mark.parametrize("hidden_size", [512, 1024]) @pytest.mark.parametrize("group_size", [64, 128, 256]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) @pytest.mark.parametrize("is_rms_norm", IS_RMS_NORM) @torch.inference_mode() def test_layer_norm_fwd_with_groups( num_tokens: int, hidden_size: int, group_size: int, dtype: torch.dtype, is_rms_norm: bool, ) -> None: """Test layer norm forward pass with group normalization.""" if hidden_size % group_size != 0: pytest.skip( f"hidden_size {hidden_size} not divisible by group_size {group_size}" ) current_platform.seed_everything(42) device = torch.device("cuda:0") # Create inputs x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) weight = torch.randn(hidden_size, dtype=dtype, device=device) bias = None if is_rms_norm else torch.randn(hidden_size, dtype=dtype, device=device) eps = 1e-6 ngroups = hidden_size // group_size # Run the triton kernel out, mean, rstd = layer_norm_fwd( x, weight, bias, eps, z=None, group_size=group_size, is_rms_norm=is_rms_norm ) # Run reference implementation ref_out = layer_norm_ref( x, weight, bias, z=None, eps=eps, group_size=group_size, is_rms_norm=is_rms_norm ) # Check outputs assert out.shape == x.shape assert out.dtype == x.dtype torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) # Check mean and rstd shapes for groups if not is_rms_norm: assert mean.shape == (ngroups * num_tokens,) assert rstd.shape == (ngroups * num_tokens,) @pytest.mark.parametrize("num_tokens", [7, 63, 128, 513, 1024, 2049]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) @torch.inference_mode() def test_layer_norm_rows_per_block( num_tokens: int, dtype: torch.dtype, ) -> None: """Test that rows_per_block logic works correctly for various M sizes.""" current_platform.seed_everything(42) device = torch.device("cuda:0") hidden_size = 1024 # Create inputs x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) weight = torch.randn(hidden_size, dtype=dtype, device=device) bias = torch.randn(hidden_size, dtype=dtype, device=device) eps = 1e-6 # Run the triton kernel out, mean, rstd = layer_norm_fwd(x, weight, bias, eps, z=None, is_rms_norm=False) # Run reference implementation ref_out = layer_norm_ref(x, weight, bias, z=None, eps=eps, is_rms_norm=False) # Check outputs torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) @pytest.mark.parametrize("dtype", [torch.bfloat16]) @torch.inference_mode() def test_strided_input(dtype: torch.dtype) -> None: """Test that the kernel handles non-contiguous (strided) inputs correctly.""" current_platform.seed_everything(42) device = torch.device("cuda:0") num_tokens = 128 hidden_size = 1024 # Create a larger tensor and take a strided slice x_large = torch.randn(num_tokens, hidden_size * 2, dtype=dtype, device=device) x = x_large[:, :hidden_size] # Make it contiguous for the kernel x_contiguous = x.contiguous() weight = torch.randn(hidden_size, dtype=dtype, device=device) bias = torch.randn(hidden_size, dtype=dtype, device=device) eps = 1e-6 # Run the triton kernel with contiguous input out, mean, rstd = layer_norm_fwd( x_contiguous, weight, bias, eps, z=None, is_rms_norm=False ) # Run reference implementation ref_out = layer_norm_ref( x_contiguous, weight, bias, z=None, eps=eps, is_rms_norm=False ) # Check outputs torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) @pytest.mark.parametrize("num_tokens", [1, 128, 2048]) @pytest.mark.parametrize("hidden_size", [768, 4096]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) @torch.inference_mode() def test_output_buffer_provided( num_tokens: int, hidden_size: int, dtype: torch.dtype, ) -> None: """Test that the kernel works when an output buffer is provided.""" current_platform.seed_everything(42) device = torch.device("cuda:0") # Create inputs x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) weight = torch.randn(hidden_size, dtype=dtype, device=device) bias = torch.randn(hidden_size, dtype=dtype, device=device) eps = 1e-6 # Pre-allocate output buffer out_buffer = torch.empty_like(x) # Run the triton kernel with provided output out, mean, rstd = layer_norm_fwd( x, weight, bias, eps, z=None, out=out_buffer, is_rms_norm=False ) # Check that the provided buffer was used assert out.data_ptr() == out_buffer.data_ptr() # Run reference implementation ref_out = layer_norm_ref(x, weight, bias, z=None, eps=eps, is_rms_norm=False) # Check outputs torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) @pytest.mark.parametrize( "shape", [ (4, 16, 1024), # 3D tensor (2, 8, 512, 256), # 4D tensor ], ) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) @torch.inference_mode() def test_multidimensional_input( shape: tuple, dtype: torch.dtype, ) -> None: """Test that the autograd function handles multidimensional inputs.""" current_platform.seed_everything(42) device = torch.device("cuda:0") hidden_size = shape[-1] # Create inputs x = torch.randn(*shape, dtype=dtype, device=device) weight = torch.randn(hidden_size, dtype=dtype, device=device) bias = torch.randn(hidden_size, dtype=dtype, device=device) eps = 1e-6 # Run through autograd function out = layernorm_fn(x, weight, bias, z=None, eps=eps) # Run reference implementation ref_out = layer_norm_ref(x, weight, bias, z=None, eps=eps, is_rms_norm=False) # Check outputs assert out.shape == x.shape torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) if __name__ == "__main__": # Run a quick smoke test test_layer_norm_fwd_basic(128, 1024, torch.float16, 42, False) test_layer_norm_fwd_with_gate(128, 1024, torch.float16, True, False) test_layer_norm_rows_per_block(513, torch.float16) print("All smoke tests passed!")
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/allclose_default.py
tests/kernels/allclose_default.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch # Reference default values of atol and rtol are from # https://github.com/pytorch/pytorch/blob/6d96beb6bec24d73ee3f080bac54d2104068f675/test/test_transformers.py#L67 default_atol = {torch.float16: 1e-3, torch.bfloat16: 1e-3, torch.float: 1e-5} default_rtol = {torch.float16: 1e-3, torch.bfloat16: 1.6e-2, torch.float: 1.3e-6} def get_default_atol(output) -> float: return default_atol[output.dtype] def get_default_rtol(output) -> float: return default_rtol[output.dtype]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_shuffle_rows.py
tests/kernels/test_shuffle_rows.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Tests for the shuffle_rows function Run `pytest tests/kernels/test_shuffle_rows.py`. """ import pytest import torch from vllm._custom_ops import shuffle_rows from vllm.platforms import current_platform @pytest.mark.parametrize("num_tokens", [1, 16, 64, 128, 256, 512, 1024]) @pytest.mark.parametrize("hidden_size", [128, 256, 512, 1024, 2048, 4096]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32]) def test_shuffle_rows_basic(num_tokens: int, hidden_size: int, dtype: torch.dtype): """Test basic functionality of shuffle_rows with various tensor sizes and dtypes.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") # Create input tensor input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) # Create a simple permutation map (identity mapping) dst2src_map = torch.arange(num_tokens, device="cuda", dtype=torch.int32) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # With identity mapping, output should be identical to input torch.testing.assert_close(output, input_tensor, atol=0, rtol=0) # Check output shape assert output.shape == (num_tokens, hidden_size) assert output.dtype == dtype assert output.device == input_tensor.device @pytest.mark.parametrize("num_tokens", [16, 64, 128]) @pytest.mark.parametrize("hidden_size", [128, 512, 1024]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) def test_shuffle_rows_permutation( num_tokens: int, hidden_size: int, dtype: torch.dtype ): """Test shuffle_rows with actual permutation.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") # Create input tensor input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) # Create a reverse permutation map dst2src_map = torch.arange(num_tokens - 1, -1, -1, device="cuda", dtype=torch.int32) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Check that the output is the reverse of the input expected_output = torch.flip(input_tensor, dims=[0]) torch.testing.assert_close(output, expected_output, atol=1e-6, rtol=1e-5) # Check output shape and properties assert output.shape == (num_tokens, hidden_size) assert output.dtype == dtype assert output.device == input_tensor.device @pytest.mark.parametrize("num_tokens", [32, 64]) @pytest.mark.parametrize("hidden_size", [256, 512]) def test_shuffle_rows_expansion(num_tokens: int, hidden_size: int): """Test shuffle_rows with expansion (more output tokens than input tokens).""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") dtype = torch.float16 # Create input tensor input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) # Create a mapping that duplicates some tokens (expansion) expanded_size = num_tokens * 2 dst2src_map = torch.randint( 0, num_tokens, (expanded_size,), device="cuda", dtype=torch.int32 ) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Check output shape assert output.shape == (expanded_size, hidden_size) assert output.dtype == dtype assert output.device == input_tensor.device # Verify that each output row matches the corresponding input row for i in range(expanded_size): src_idx = dst2src_map[i].item() torch.testing.assert_close( output[i], input_tensor[src_idx], atol=1e-6, rtol=1e-5 ) @pytest.mark.parametrize("num_tokens", [16, 64]) @pytest.mark.parametrize("hidden_size", [128, 512]) def test_shuffle_rows_random_permutation(num_tokens: int, hidden_size: int): """Test shuffle_rows with random permutation.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") dtype = torch.float16 # Set seed for reproducibility torch.manual_seed(42) # Create input tensor input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) # Create a random permutation map dst2src_map = torch.randperm(num_tokens, device="cuda", dtype=torch.int32) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Check output shape and properties assert output.shape == (num_tokens, hidden_size) assert output.dtype == dtype assert output.device == input_tensor.device # Verify that each output row matches the corresponding input row for i in range(num_tokens): src_idx = dst2src_map[i].item() torch.testing.assert_close( output[i], input_tensor[src_idx], atol=1e-6, rtol=1e-5 ) def test_shuffle_rows_edge_cases(): """Test shuffle_rows with edge cases.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") dtype = torch.float16 # Test with single token input_tensor = torch.randn(1, 128, device="cuda", dtype=dtype) dst2src_map = torch.tensor([0], device="cuda", dtype=torch.int32) output = shuffle_rows(input_tensor, dst2src_map) torch.testing.assert_close(output, input_tensor, atol=0, rtol=0) # Test with single feature dimension input_tensor = torch.randn(16, 1, device="cuda", dtype=dtype) dst2src_map = torch.arange(16, device="cuda", dtype=torch.int32) output = shuffle_rows(input_tensor, dst2src_map) torch.testing.assert_close(output, input_tensor, atol=0, rtol=0) def test_shuffle_rows_moe_like_scenario(): """Test shuffle_rows in a scenario similar to MoE usage.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") dtype = torch.float16 batch_size = 32 hidden_size = 1024 topk = 2 # Simulate input tokens input_tensor = torch.randn(batch_size, hidden_size, device="cuda", dtype=dtype) # Simulate expert assignment (each token goes to topk experts) # This creates a mapping where tokens are duplicated for multiple experts total_tokens = batch_size * topk dst2src_map = torch.zeros(total_tokens, device="cuda", dtype=torch.int32) # Fill the mapping to simulate MoE token distribution for i in range(batch_size): for k in range(topk): dst2src_map[i * topk + k] = i # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Check output shape assert output.shape == (total_tokens, hidden_size) assert output.dtype == dtype assert output.device == input_tensor.device # Verify that tokens are correctly duplicated for i in range(batch_size): for k in range(topk): output_idx = i * topk + k torch.testing.assert_close( output[output_idx], input_tensor[i], atol=1e-6, rtol=1e-5 ) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32]) def test_shuffle_rows_dtype_consistency(dtype: torch.dtype): """Test that shuffle_rows preserves dtype correctly.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") num_tokens = 64 hidden_size = 512 # Create input tensor with specific dtype input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) dst2src_map = torch.arange(num_tokens, device="cuda", dtype=torch.int32) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Verify dtype is preserved assert output.dtype == dtype assert output.device == input_tensor.device torch.testing.assert_close(output, input_tensor, atol=1e-6, rtol=1e-5) def test_shuffle_rows_device_consistency(): """Test that shuffle_rows maintains device consistency.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") num_tokens = 32 hidden_size = 256 dtype = torch.float16 # Create input tensor on CUDA input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) dst2src_map = torch.arange(num_tokens, device="cuda", dtype=torch.int32) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Verify device is maintained assert output.device == input_tensor.device assert output.device.type == "cuda" def test_shuffle_rows_contiguous_output(): """Test that shuffle_rows produces contiguous output.""" if not current_platform.is_cuda(): pytest.skip("shuffle_rows requires CUDA") num_tokens = 64 hidden_size = 512 dtype = torch.float16 # Create input tensor input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) dst2src_map = torch.arange(num_tokens, device="cuda", dtype=torch.int32) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Verify output is contiguous assert output.is_contiguous()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_fused_quant_activation.py
tests/kernels/test_fused_quant_activation.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch import vllm._custom_ops as ops from tests.kernels.utils import opcheck from vllm.model_executor.layers.activation import SiluAndMul from vllm.platforms import current_platform DTYPES = [torch.bfloat16, torch.float16] QUANT_DTYPES = [current_platform.fp8_dtype()] NUM_TOKENS = [1, 17, 86, 1234, 3045] # Arbitrary values for testing HIDDEN_SIZES = [16, 48, 128, 1562, 4096] # Arbitrary values for testing SEEDS = [0] CUDA_DEVICES = [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)] def ref_impl( silu_and_mul: SiluAndMul, x: torch.Tensor, scale: torch.Tensor ) -> torch.Tensor: silu_and_mul_out = silu_and_mul.forward_native(x) out, scales = ops.scaled_fp8_quant(silu_and_mul_out, scale) return out def ops_impl(x: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: out_shape = (x.shape[0], x.shape[1] // 2) out = torch.empty(out_shape, dtype=current_platform.fp8_dtype(), device=x.device) torch.ops._C.silu_and_mul_quant(out, x, scale) return out @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("quant_dtype", QUANT_DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @torch.inference_mode() def test_silu_and_mul( num_tokens: int, hidden_size: int, dtype: torch.dtype, quant_dtype: torch.dtype, seed: int, device: str, ) -> None: torch.random.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.set_default_device(device) layer = SiluAndMul() # Make inputs scale = torch.randn((1), device=device, dtype=torch.float32) x = torch.randn(num_tokens, hidden_size, dtype=dtype) ref_out = ref_impl(layer, x, scale) ops_out = ops_impl(x, scale) assert ref_out.dtype == quant_dtype assert ops_out.dtype == quant_dtype assert ref_out.shape == ops_out.shape assert torch.allclose( ref_out.to(dtype=torch.float32), ops_out.to(dtype=torch.float32) ) opcheck(torch.ops._C.silu_and_mul_quant, (ops_out, x, scale))
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_cache_kernels.py
tests/kernels/test_cache_kernels.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Unit tests for CUDA kernels in cache_kernels.cu.""" import pytest import torch try: from vllm import _custom_ops as ops except ImportError: pytest.skip( "Could not import vllm._custom_ops. (pip install -e .)", allow_module_level=True ) @pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Need CUDA device") def test_gather_cache_oob(): """ Tests for OOB read in gather_and_maybe_dequant_cache (Issue #27909). This test constructs a boundary case identified in the issue where seq_starts causes the block_table offset to read out of bounds. """ batch_size = 1 block_size = 64 entry_size = 128 block_table = torch.tensor([[1, 2]], dtype=torch.int32, device="cuda") # This will result in offset = 128 / block_size = 128 / 64 = 2 # This will cause the kernel to try to read from # block_table[0, 2], but its size is only 2. seq_starts = torch.tensor([128], dtype=torch.int32, device="cuda") seq_len = 65 cu_seq_lens = torch.tensor([0, seq_len], dtype=torch.int32, device="cuda") # src_cache: [num_blocks, block_size, entry_size] num_blocks = 5 src_cache = torch.randn( (num_blocks, block_size, entry_size), dtype=torch.float16, device="cuda" ) dst = torch.empty((seq_len, entry_size), dtype=torch.float16, device="cuda") scale = torch.tensor([1.0], dtype=torch.float32, device="cuda") # Calling the C++ function gather_and_maybe_dequant_cache ops.gather_and_maybe_dequant_cache( src_cache, dst, block_table, cu_seq_lens, batch_size, "auto", # kv_cache_dtype scale, seq_starts, ) torch.cuda.synchronize() assert True if __name__ == "__main__": pytest.main([__file__])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_onednn.py
tests/kernels/test_onednn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from tests.kernels.utils import to_int8 from vllm import _custom_ops as ops from vllm.platforms import current_platform if not current_platform.is_cpu(): pytest.skip("skipping CPU-only tests", allow_module_level=True) NK_FACTORS = [ (256, 128), (4096, 4096), (16384, 4096), (1023, 491), (1001, 15), ] M_FACTORS = [ (16, 1, 32, 128, 64), (1, 17, 1, 31, 17), ] CACHE_SIZES = [2] DTYPE = [torch.bfloat16] def rand_int8(shape: tuple, device: str = "cpu"): return to_int8(torch.rand(shape, device=device) * 255 - 128) def ref_int8_scaled_mm( a: torch.Tensor, b: torch.Tensor, scale_a: torch.Tensor, scale_b: torch.Tensor, azp: torch.Tensor | None, bias: torch.Tensor | None, output_type: torch.dtype, ): if azp is not None: a = a.to(dtype=torch.float32) - azp.to(dtype=torch.float32) output = torch.mm( (scale_a * a.to(dtype=torch.float32)), (scale_b * b.to(dtype=torch.float32)) ) if bias is not None: output += bias.float() return output.to(dtype=output_type) def onednn_int8_gemm_test_helper( primitive_cache_size: int, m: int, n: int, k: int, per_tensor_a_quant: bool, per_tensor_b_quant: bool, use_azp: bool, use_bias: bool, out_dtype: torch.dtype = torch.bfloat16, device: str = "cpu", ): # Test for a oneDNN kernel with per-tensor / per-token activation # quantization and per-tensor / per-output channel weight quantization. a = to_int8(torch.randn((m, k), device=device) * 5) b = to_int8(torch.randn((n, k), device=device).t() * 5) a_scales_shape = (1, 1) if per_tensor_a_quant else (m, 1) b_scales_shape = (1, 1) if per_tensor_b_quant else (1, n) scale_a = torch.randn(a_scales_shape, device=device, dtype=torch.float32) scale_b = torch.randn(b_scales_shape, device=device, dtype=torch.float32) if use_azp: azp = torch.rand(a_scales_shape, dtype=torch.float32) * 10 + 1.5 azp = (azp / scale_a).round().to(dtype=torch.int32) azp_adj = scale_b * b.sum(dim=0, keepdim=True, dtype=torch.float32) else: azp = None azp_adj = None bias = torch.rand((n,), device=device, dtype=out_dtype) * 10 if use_bias else None handler = ops.create_onednn_scaled_mm( b, scale_b, out_dtype, not per_tensor_a_quant, use_azp, primitive_cache_size, ) out = torch.zeros((m, n), dtype=out_dtype) ops.onednn_scaled_mm(handler, a, out, scale_a, azp, azp_adj, bias) baseline = ref_int8_scaled_mm(a, b, scale_a, scale_b, azp, bias, out_dtype) torch.testing.assert_close(out, baseline, rtol=1e-1, atol=1e0) if use_bias: # To test runtime bias setting out = torch.zeros((m, n), dtype=out_dtype) ops.onednn_scaled_mm(handler, a, out, scale_a, azp, azp_adj, None) baseline = ref_int8_scaled_mm(a, b, scale_a, scale_b, azp, None, out_dtype) torch.testing.assert_close(out, baseline, rtol=1e-1, atol=1e0) def onednn_gemm_test_helper( primitive_cache_size: int, m: int, n: int, k: int, use_bias: bool, use_stride: bool, dtype: torch.dtype = torch.bfloat16, device: str = "cpu", ): if use_stride: a = torch.rand((m, 2 * k), dtype=dtype, device=device) * 1.5 a = a[:, :k] else: a = torch.rand((m, k), dtype=dtype, device=device) * 1.5 b = torch.rand((n, k), dtype=dtype, device=device) * 1.5 if use_bias: bias = torch.rand((n,), device=device, dtype=dtype) * 5 bias_f32 = bias.float() else: bias = None bias_f32 = None handler = ops.create_onednn_mm( b.t(), primitive_cache_size, ) out = ops.onednn_mm(handler, a, bias) baseline = torch.nn.functional.linear(a.float(), b.float(), bias_f32).to( dtype=a.dtype ) torch.testing.assert_close(out, baseline) if use_bias: # To test runtime bias setting out = ops.onednn_mm(handler, a, None) baseline = torch.nn.functional.linear(a.float(), b.float(), None).to( dtype=a.dtype ) torch.testing.assert_close(out, baseline) @pytest.mark.parametrize("n,k", NK_FACTORS) @pytest.mark.parametrize("m_list", M_FACTORS) @pytest.mark.parametrize("per_tensor_a_scale", [True, False]) @pytest.mark.parametrize("per_tensor_b_scale", [True, False]) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.parametrize("use_azp", [True, False]) @pytest.mark.parametrize("output_type", DTYPE) @pytest.mark.parametrize("primitive_cache_size", CACHE_SIZES) def test_onednn_int8_scaled_gemm( n: int, k: int, m_list: tuple[int, ...], per_tensor_a_scale: bool, per_tensor_b_scale: bool, use_bias: bool, use_azp: bool, output_type: torch.dtype, primitive_cache_size: int, ): for m in m_list: onednn_int8_gemm_test_helper( primitive_cache_size=primitive_cache_size, m=m, n=n, k=k, per_tensor_a_quant=per_tensor_a_scale, per_tensor_b_quant=per_tensor_b_scale, use_bias=use_bias, use_azp=use_azp, out_dtype=output_type, ) @pytest.mark.parametrize("n,k", NK_FACTORS) @pytest.mark.parametrize("m_list", M_FACTORS) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.parametrize("use_stride", [True, False]) @pytest.mark.parametrize("dtype", DTYPE) @pytest.mark.parametrize("primitive_cache_size", CACHE_SIZES) def test_onednn_gemm( n: int, k: int, m_list: tuple[int, ...], use_bias: bool, use_stride: bool, dtype: torch.dtype, primitive_cache_size: int, ): for m in m_list: onednn_gemm_test_helper( primitive_cache_size=primitive_cache_size, m=m, n=n, k=k, use_bias=use_bias, use_stride=use_stride, dtype=dtype, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_top_k_per_row.py
tests/kernels/test_top_k_per_row.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import numpy as np import pytest import torch from vllm.platforms import current_platform # Test parameters NUM_ROWS = [1, 32, 2050] TOP_K_VALUES = [2048, 3000] BATCH_SIZE = [1, 2, 2048] NEXT_N = [1, 8] DATA_GENERATION = ["random", "10LSBits"] def create_random_logits( row_starts: torch.Tensor, row_ends: torch.Tensor, dtype: torch.dtype, seed: int, data_generation: str, ) -> torch.Tensor: """Create random logits tensor for testing.""" torch.manual_seed(seed) np.random.seed(seed) # Generate logits with some structure to make testing more meaningful if data_generation == "random": logits = torch.randn( row_starts.shape[0], max(row_ends), dtype=dtype, device="cuda" ) elif data_generation == "10LSBits": top_22_bits_mask = 0xFFFFFC00 last_10_bits_mask = 0x000003FF fixed_top_22_bits = 0x3F900000 # Generate random bits for the last 10 bits random_bottom_bits = torch.randint( 0, 2**10, (row_starts.shape[0], max(row_ends)), dtype=torch.int32, device="cuda", ) # Combine: fixed top 22 bits with random last 10 bits logits_bits = (fixed_top_22_bits & top_22_bits_mask) | ( random_bottom_bits & last_10_bits_mask ) logits = logits_bits.view(dtype) for i, end in enumerate(row_ends): logits[i, end:] = float("-inf") return logits def create_row_boundaries( seq_len: int, vocab_size: int ) -> tuple[torch.Tensor, torch.Tensor]: """Create row start and end indices for testing.""" row_starts = torch.zeros(seq_len, dtype=torch.int32, device="cuda") row_ends = torch.arange(1, seq_len + 1, device="cuda", dtype=torch.int32) return row_starts, row_ends def compare_top_k_results( logits: torch.Tensor, cuda_indices: torch.Tensor, torch_indices: torch.Tensor, row_starts: torch.Tensor, row_ends: torch.Tensor, top_k: int, tolerance: float = 1e-5, ) -> bool: """ Compare results from CUDA top_k_per_row with torch.topk. Both results should be sorted and contain the same top-k elements. """ num_rows = cuda_indices.shape[0] for row_idx in range(num_rows): # Get valid elements using row boundaries row_start = row_starts[row_idx].item() row_end = row_ends[row_idx].item() row_length = row_end - row_start num_valid = min(top_k, row_length) cuda_row_indices = cuda_indices[row_idx][:num_valid].cpu() torch_row_indices = torch_indices[row_idx][:num_valid].cpu() # Compare the sets of indices first cuda_set = set(cuda_row_indices.tolist()) torch_set = set(torch_row_indices.tolist()) if cuda_set == torch_set: continue # Any difference in elements, compare the values logits_row = logits[row_idx] cuda_row_values = [logits_row[i] for i in cuda_row_indices] torch_row_values = [logits_row[i] for i in torch_row_indices] cuda_only_values, torch_only_values = [], [] for idx in cuda_set - torch_set: cuda_pos = (cuda_row_indices == idx).nonzero(as_tuple=True)[0] cuda_only_values.append(cuda_row_values[cuda_pos[0]]) for idx in torch_set - cuda_set: torch_pos = (torch_row_indices == idx).nonzero(as_tuple=True)[0] torch_only_values.append(torch_row_values[torch_pos[0]]) if len(cuda_only_values) != len(torch_only_values): return False if not torch.allclose( torch.tensor(cuda_only_values), torch.tensor(torch_only_values), rtol=tolerance, atol=tolerance, ): return False return True @pytest.mark.parametrize("num_rows", NUM_ROWS) @pytest.mark.parametrize("top_k", TOP_K_VALUES) @pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA") @torch.inference_mode() def test_top_k_per_row( num_rows: int, top_k: int, ) -> None: """ Test top_k_per_row. """ torch.set_default_device("cuda:0") # Create test data vocab_size = 20000 row_starts, row_ends = create_row_boundaries(num_rows, vocab_size) logits = create_random_logits(row_starts, row_ends, torch.float32, 42, "random") # Create output tensors indices = torch.empty((num_rows, top_k), dtype=torch.int32, device="cuda") # Run CUDA implementation torch.ops._C.top_k_per_row_prefill( logits, row_starts, row_ends, indices, num_rows, logits.stride(0), logits.stride(1), top_k, ) # Run reference implementation torch_indices = logits.topk(min(top_k, max(row_ends)), dim=-1)[1] mask_lo = torch_indices >= 0 mask_hi = (torch_indices - (row_ends - row_starts)[:, None]) < 0 mask = mask_lo & mask_hi torch_indices = torch_indices.masked_fill(~mask, -1) # Compare results assert compare_top_k_results( logits, indices, torch_indices, row_starts, row_ends, top_k ), "CUDA top_k_per_row_prefill results don't match torch.topk" def _run_top_k_per_row_decode_test( top_k: int, batch_size: int, next_n: int, vocab_size: int, data_generation: str, ) -> None: """ Helper function to run top_k_per_row_decode test with given parameters. """ torch.set_default_device("cuda:0") # Create test data num_rows = batch_size * next_n seq_lens = torch.randint( vocab_size, (batch_size,), dtype=torch.int32, device="cuda" ) row_starts = torch.zeros(num_rows, dtype=torch.int32, device="cuda") row_indices = torch.arange(num_rows, device="cuda") // next_n next_n_offset = torch.arange(num_rows, device="cuda") % next_n row_ends = seq_lens[row_indices] - next_n + next_n_offset + 1 logits = create_random_logits( row_starts, row_ends, torch.float32, 42, data_generation ) # Create output tensors indices = torch.empty((num_rows, top_k), dtype=torch.int32, device="cuda") # Run CUDA implementation torch.ops._C.top_k_per_row_decode( logits, next_n, seq_lens, indices, num_rows, logits.stride(0), logits.stride(1), top_k, ) torch.cuda.synchronize() # Run reference implementation torch_indices = logits.topk(min(top_k, max(row_ends)), dim=-1)[1] mask_lo = torch_indices >= 0 mask_hi = (torch_indices - (row_ends - row_starts)[:, None]) < 0 mask = mask_lo & mask_hi torch_indices = torch_indices.masked_fill(~mask, -1) # Compare results assert compare_top_k_results( logits, indices, torch_indices, row_starts, row_ends, top_k ), "CUDA top_k_per_row_decode results don't match torch.topk" @pytest.mark.parametrize("top_k", TOP_K_VALUES) @pytest.mark.parametrize("batch_size", BATCH_SIZE) @pytest.mark.parametrize("next_n", NEXT_N) @pytest.mark.parametrize("data_generation", DATA_GENERATION) @pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA") @torch.inference_mode() def test_top_k_per_row_decode( top_k: int, batch_size: int, next_n: int, data_generation: str, ) -> None: """ Test top_k_per_row with seq_lens tensor. """ vocab_size = 20000 _run_top_k_per_row_decode_test( top_k, batch_size, next_n, vocab_size, data_generation ) @pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA") @torch.inference_mode() def test_top_k_per_row_decode_large_vocab_size() -> None: """ Test top_k_per_row_decode with large vocabulary size. """ top_k = 2048 batch_size = 2 next_n = 2 vocab_size = 300000 data_generation = "random" _run_top_k_per_row_decode_test( top_k, batch_size, next_n, vocab_size, data_generation )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/utils.py
tests/kernels/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Kernel test utils""" import itertools import random from collections.abc import Sequence from numbers import Number from typing import Any, NamedTuple from unittest.mock import patch import torch from torch._prims_common import TensorLikeType from tests.kernels.quant_utils import native_w8a8_block_matmul from vllm.attention.backends.abstract import AttentionType from vllm.model_executor.custom_op import CustomOp from vllm.model_executor.layers.activation import SiluAndMul from vllm.model_executor.layers.fused_moe.utils import moe_kernel_quantize_input from vllm.utils.torch_utils import make_tensor_with_pad # For now, disable "test_aot_dispatch_dynamic" since there are some # bugs related to this test in PyTorch 2.4. DEFAULT_OPCHECK_TEST_UTILS: tuple[str, ...] = ( "test_schema", "test_autograd_registration", "test_faketensor", ) ALL_OPCHECK_TEST_UTILS: tuple[str, ...] = ( "test_schema", "test_autograd_registration", "test_faketensor", "test_aot_dispatch_dynamic", ) class QKVInputs(NamedTuple): """ Data structure for representing unpacked attention inputs, query/key/values and their sequence lengths. Attributes: * {query,key,value}: unpacked (batch_size x padded_seq_len x num_heads x head_size) attention inputs * q_seq_lens: query sequence lengths list * kv_seq_lens: shared key/value sequence lengths list """ query: torch.Tensor key: torch.Tensor value: torch.Tensor q_seq_lens: list[int] kv_seq_lens: list[int] class QKVO(NamedTuple): """ Data structure for representing unpacked attention inputs, alongside unpacked known-correct attention output Attributes: * qkv: unpacked (batch_size x padded_seq_len x num_heads x head_size) attention inputs * ideal_output: unpacked (batch_size x padded_seq_len x num_heads x head_size) known-correct attention output """ qkv: QKVInputs ideal_output: torch.Tensor class PackedQKVInputs(NamedTuple): """ Data structure for representing packed attention inputs Attributes: * {query,key,value}: packed (number_of_tokens x num_heads x head_size) attention inputs * q_start_loc_list: list of query start locations within packed tensor * kv_start_loc_list: shared list of key/value start locations within packed tensor * q_seq_lens: query sequence lengths list * kv_seq_lens: shared key/value sequence lengths list """ query: torch.Tensor key: torch.Tensor value: torch.Tensor q_start_loc_list: list[int] | None kv_start_loc_list: list[int] | None q_seq_lens: list[int] | None kv_seq_lens: list[int] | None class PackedQKVO(NamedTuple): """ Data structure for representing packed attention inputs, alongside packed known-correct attention output Attributes: * packed_qkv: packed (number_of_tokens x num_heads x head_size) attention inputs * ideal_output: packed (number_of_tokens x num_heads x head_size) known-correct attention output """ packed_qkv: PackedQKVInputs | None ideal_output: torch.Tensor class KVMemoryMap(NamedTuple): """ Data structure for encapsulating KV cache memory mapping. Attributes: * block_tables: KV cache block tables * slot_mapping: mapping of sequence offset to physical address """ block_tables: torch.Tensor slot_mapping: torch.Tensor class PhaseTestParameters(NamedTuple): """ Data structure for encapsulating the test parameters for a given test "phase" (prefill or decode phase) and attention scenario (encoder, decoder-self, encoder/decoder-cross) Attributes: * packed_qkvo: packed (number_of_tokens x num_heads x head_size) attention inputs & known-correct output * kv_mmap: KV cache memory mapping, specific to this test phase & attention scenario """ packed_qkvo: PackedQKVO kv_mmap: KVMemoryMap | None def maybe_make_int_tensor( _list: list[int] | None, device: torch.device | str, ) -> torch.Tensor: """ Convert Python int list to a 1D int torch.Tensor on `device` Returns: * If _list is not None: 1D int torch.Tensor on `device` * None otherwise """ return ( None if _list is None else torch.tensor(_list, dtype=torch.int, device=device) ) def maybe_make_long_tensor( _list: list[int] | None, device: torch.device | str, ) -> torch.Tensor: """ Convert Python int list to a 1D long torch.Tensor on `device` Returns: * If _list is not None: 1D long torch.Tensor on `device` * None otherwise """ return ( None if _list is None else torch.tensor(_list, dtype=torch.long, device=device) ) def maybe_max(_list: list | None) -> Number | None: """ Returns: * If _list is not None: max(_list) * None otherwise """ return None if _list is None else max(_list) def make_causal_mask( q_max_seq_len: int, kv_max_seq_len: int, ) -> torch.Tensor: """ Create a q_max_seq_len x kv_max_seq_len causal mask Arguments: * q_max_seq_len: query max seq len * kv_max_seq_len: key/value max seq len Returns: * 2D tensor, q_max_seq_len x kv_max_seq_len """ # Create a matrix where entry (i, j) is True if i >= j mask = torch.triu(torch.ones(q_max_seq_len, kv_max_seq_len), diagonal=1) # Replace True with float('-inf') and False with 0 mask = mask.masked_fill(mask == 1, float("-inf")).masked_fill(mask == 0, 0.0) return mask def ref_masked_attention( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, scale: float, custom_mask: torch.Tensor | None = None, q_seq_lens: list | None = None, kv_seq_lens: list | None = None, ) -> torch.Tensor: """ "Golden" masked attention reference. Supports two types of masking: * Basic attention mask, utilizing {q,kv}_seq_lens args to mask out padding elements * Custom attention mask, which can force an arbitrary mask tensor, i.e. causal Arguments: * query: batch_size x q_padded_seq_len x num_heads x head_size * key: batch_size x kv_padded_seq_len x num_heads x head_size * value: batch_size x kv_padded_seq_len x num_heads x head_size * scale: Attention scale factor * custom_mask: custom attention mask; good place to inject a causal attention mask * q_seq_lens: list of unpadded query seq_lens for each batch index * kv_seq_lens: list of unpadded key/value seq_lens for each batch index Returns: * Attention result, batch_size x q_padded_seq_len x num_heads x head_size """ assert q_seq_lens is not None assert kv_seq_lens is not None batch_size = query.shape[0] assert len(q_seq_lens) == batch_size assert len(kv_seq_lens) == batch_size attn_weights = scale * torch.einsum("bqhd,bkhd->bhqk", query, key).float() # Basic attention mask, derived from seq lens if (q_seq_lens is not None) or (kv_seq_lens is not None): attn_mask = torch.zeros_like(attn_weights) if q_seq_lens is not None: for bdx, plen in enumerate(q_seq_lens): attn_mask[bdx, :, plen:, :] = -torch.inf if kv_seq_lens is not None: for bdx, plen in enumerate(kv_seq_lens): attn_mask[bdx, :, :, plen:] = -torch.inf attn_weights = attn_weights + attn_mask.float() # Custom attention mask if custom_mask is not None: attn_weights = attn_weights + custom_mask.float() attn_weights = torch.softmax(attn_weights, dim=-1).to(value.dtype) out = torch.einsum("bhqk,bkhd->bqhd", attn_weights, value) return out def make_qkv( batch_size: int, max_q_seq_len: int, max_kv_seq_len: int | None, num_heads: int, head_size: int, device: torch.device | str, force_kv_seq_lens: list[int] | None = None, attn_type: AttentionType = AttentionType.ENCODER_DECODER, force_max_len: bool = False, ) -> tuple[QKVInputs, QKVInputs, QKVInputs]: """ Construct QKV test tensors for self- and cross-attention. Generates three query/key/value triplets: * "Baseline" query/key/value (for input to reference attention function) * "Prefill" query/key/value (last sequence offset zero'd out, for use as input to prefill kernel) * "Decode" query/key/value (only the last sequence offset from baseline, for use as input to decode kernel) Each Q/K/V triplet is associated with a list of q seqlens and a list of k/v seqlens Arguments: * batch_size * max_q_seq_len: max query seq len * max_kv_seq_len: max key/value seq len * num_heads * head_size * is_encoder_decoder_attn: if True, query seqlen may differ from key/value seqlen (as is often the case for cross-attention); o/w, query/key/value seqlens match at each batch index (max_kv_seq_len is unused) * force_kv_seq_lens: if not None, overrides kv sequence lengths * attn_type: encoder, decoder self, or enc/dec cross attention * force_max_len: if True, all query seqlens are max_q_seq_len; o/w query seqlens are random in [2,max_q_seq_lens]. Same for key/value seqlens and max_kv_seq_len, unless forced by is_encoder_decoder_attn=False * device: CPU or CUDA device Returns: * Overall QKVInputs structure (containing full unpacked Q/K/V tensors) * Prefill QKVInputs structure (containing all but the last sequence offset) * Decode QKVInputs structure (containing all only the last sequence offset) """ if force_max_len: q_seq_lens = [max_q_seq_len for _ in range(batch_size)] else: q_seq_lens = [random.randint(2, max_q_seq_len) for _ in range(batch_size)] kv_seq_lens = None if force_kv_seq_lens is not None: kv_seq_lens = force_kv_seq_lens elif attn_type != AttentionType.ENCODER_DECODER: # K,V seq lens match Q for self-attention kv_seq_lens = q_seq_lens else: # K,V seq lens are distinct from Q seq lens & random assert max_kv_seq_len is not None if force_max_len: kv_seq_lens = [max_kv_seq_len] * batch_size else: kv_seq_lens = [random.randint(2, max_kv_seq_len) for _ in range(batch_size)] query = torch.rand((batch_size, max_q_seq_len, num_heads, head_size)).to(device) key = torch.rand((batch_size, max_kv_seq_len, num_heads, head_size)).to(device) value = torch.rand((batch_size, max_kv_seq_len, num_heads, head_size)).to(device) prefill_query = torch.zeros((batch_size, max_q_seq_len, num_heads, head_size)).to( device ) prefill_key = torch.zeros((batch_size, max_kv_seq_len, num_heads, head_size)).to( device ) prefill_value = torch.zeros((batch_size, max_kv_seq_len, num_heads, head_size)).to( device ) decode_query = torch.zeros((batch_size, 1, num_heads, head_size)).to(device) decode_key = torch.zeros((batch_size, 1, num_heads, head_size)).to(device) decode_value = torch.zeros((batch_size, 1, num_heads, head_size)).to(device) for bdx, (q_seq_len, kv_seq_len) in enumerate(zip(q_seq_lens, kv_seq_lens)): query[bdx, q_seq_len:, :, :] = 0 key[bdx, kv_seq_len:, :, :] = 0 value[bdx, kv_seq_len:, :, :] = 0 prefill_query[bdx, 0 : (q_seq_len - 1), :, :] = query[ bdx, 0 : (q_seq_len - 1), :, : ] prefill_key[bdx, 0 : (kv_seq_len - 1), :, :] = key[ bdx, 0 : (kv_seq_len - 1), :, : ] prefill_value[bdx, 0 : (kv_seq_len - 1), :, :] = value[ bdx, 0 : (kv_seq_len - 1), :, : ] decode_query[bdx, :, :, :] = query[bdx, (q_seq_len - 1) : q_seq_len, :, :] decode_key[bdx, :, :, :] = key[bdx, (kv_seq_len - 1) : kv_seq_len, :, :] decode_value[bdx, :, :, :] = value[bdx, (kv_seq_len - 1) : kv_seq_len, :, :] prefill_q_seq_lens = [plen - 1 for plen in q_seq_lens] prefill_kv_seq_lens = [plen - 1 for plen in kv_seq_lens] decode_q_seq_lens = [1 for _ in q_seq_lens] decode_kv_seq_lens = [1 for _ in kv_seq_lens] return ( QKVInputs( query, # Overall QKV inputs key, value, q_seq_lens, kv_seq_lens, ), QKVInputs( prefill_query, # Prefill subset of QKV sequences prefill_key, prefill_value, prefill_q_seq_lens, prefill_kv_seq_lens, ), QKVInputs( decode_query, # Decode subset of KV sequences decode_key, decode_value, decode_q_seq_lens, decode_kv_seq_lens, ), ) def pack_tensor( unpacked_tensor: torch.Tensor, seq_lens: list[int], device: torch.device | str ) -> tuple[torch.Tensor, list[int]]: """ Pack a batch_size x padded_seq_len x num_heads x head_size tensor into an unpadded number_of_tokens x num_heads x head_size tensor, where number_of_tokens = sum(seq_lens) Arguments: * unpacked_tensor: batch_size x padded_seq_len x num_heads x head_size * seq_lens: list of token counts for each seq * device: CPU or CUDA device Returns * packed_tensor: number_of_tokens x num_heads x head_size * start_loc_list: start idx of each batch elt in packed_tensor; [0] + list(itertools.accumulate(seq_lens)) """ num_tok = sum(seq_lens) num_heads = unpacked_tensor.shape[-2] head_size = unpacked_tensor.shape[-1] start_loc_list = [0] + list(itertools.accumulate(seq_lens)) packed_tensor = torch.zeros((num_tok, num_heads, head_size), device=device) for bdx, (seq_len, start_loc) in enumerate(zip(seq_lens, start_loc_list)): packed_tensor[start_loc : (start_loc + seq_len), :, :] = unpacked_tensor[ bdx, :seq_len, :, : ] return packed_tensor, start_loc_list def pack_qkv(qkv: QKVInputs, device: torch.device | str) -> PackedQKVInputs: """ Individually pack each of Q, K and V, each with dimensions batch_size x padded_seq_len x num_heads x head_size, into respective number_of_tokens x num_heads x head_size tensors. For Q, number_of_tokens = sum(q_seq_lens). For K and V, number_of_tokens = sum(kv_seq_lens) Arguments: * qkv: Unpacked (batch_size x padded_seq_len x num_heads x head_size) attention inputs * device: CPU or CUDA device Returns * Packed (number_of_tokens x num_heads x head_size) QKV inputs derived from unpacked inputs """ if qkv.query is None: packed_query = None q_start_loc_list = None else: packed_query, q_start_loc_list = pack_tensor( qkv.query, qkv.q_seq_lens, device=device ) packed_key, kv_start_loc_list = pack_tensor(qkv.key, qkv.kv_seq_lens, device=device) packed_value, _ = pack_tensor(qkv.value, qkv.kv_seq_lens, device=device) return PackedQKVInputs( packed_query, packed_key, packed_value, q_start_loc_list, kv_start_loc_list, (None if q_start_loc_list is None else qkv.q_seq_lens), qkv.kv_seq_lens, ) def _make_metadata_tensors( seq_lens: list[int] | None, context_lens: list[int] | None, encoder_seq_lens: list[int] | None, device: torch.device | str, ) -> tuple[ torch.Tensor, torch.Tensor, Any, Any, torch.Tensor | None, torch.Tensor, torch.Tensor, int | None, ]: """ Build scalar & tensor values required to build attention metadata structure. Arguments: * seq_lens: list of token-counts for each decoder input seq * context_lens: list of context length values for each seq * encoder_seq_lens: list of token-counts for each encoder input seq * device: CPU or CUDA device Returns: * seq_lens_tensor: decoder seq_lens list, as tensor * context_lens_tensor: context_lens list, as tensor * max_context_len: max(context_lens) * max_seq_len: max(seq_lens) * seq_start_loc: start idx of each sequence * encoder_seq_lens_tensor: encoder seq_lens list, as tensor * encoder_seq_start_loc: start idx of each encoder sequence * max_encoder_seq_len: encoder seq_lens list, as tensor """ seq_lens_tensor = maybe_make_int_tensor(seq_lens, device) context_lens_tensor = maybe_make_int_tensor(context_lens, device) max_context_len = maybe_max(context_lens) max_seq_len = maybe_max(seq_lens) encoder_seq_lens_tensor = maybe_make_int_tensor(encoder_seq_lens, device) max_encoder_seq_len = None if encoder_seq_lens is None else max(encoder_seq_lens) seq_start_loc = None if seq_lens_tensor is not None: seq_start_loc = torch.zeros( seq_lens_tensor.shape[0] + 1, dtype=torch.int32, device=seq_lens_tensor.device, ) torch.cumsum( seq_lens_tensor, dim=0, dtype=seq_start_loc.dtype, out=seq_start_loc[1:] ) encoder_seq_start_loc = torch.zeros( encoder_seq_lens_tensor.shape[0] + 1, dtype=torch.int32, device=encoder_seq_lens_tensor.device, ) torch.cumsum( encoder_seq_lens_tensor, dim=0, dtype=encoder_seq_start_loc.dtype, out=encoder_seq_start_loc[1:], ) return ( seq_lens_tensor, context_lens_tensor, max_context_len, max_seq_len, seq_start_loc, encoder_seq_lens_tensor, encoder_seq_start_loc, max_encoder_seq_len, ) def make_kv_cache( num_blocks: int, num_heads: int, head_size: int, block_size: int, device: torch.device | str, backend: str, default_val: float = 0.0, ) -> torch.Tensor: """ Create a fake KV cache. Arguments: * num_blocks: number of blocks in the KV cache * num_heads: number of attention heads * head_size: head dimension * block_size: number of offsets within a block * device: CPU or CUDA device * default_val: initialization value for KV cache elements Returns: * kv_cache: 2 x num_blocks x block_size x num_heads x head_size * for backend 'FLASH_ATTN' """ if backend != "FLASH_ATTN": raise ValueError(f"Unknown backend value: '{backend}'. Expected 'FLASH_ATTN'.") kv_cache = torch.rand((2, num_blocks, block_size, num_heads, head_size)).to(device) if default_val is not None: kv_cache[:, :, :] = default_val return kv_cache def _num_tokens_to_min_blocks(num_tokens: int, block_size: int) -> int: """ Compute the minimum number of blocks required to hold num_tokens tokens, given block_size """ return (num_tokens + block_size) // block_size def make_empty_slot_mapping_tensor(device: torch.device | str): return maybe_make_long_tensor([], device) def make_empty_block_tables_tensor(device: torch.device | str): return torch.tensor([], device=device) def split_slot_mapping( slot_mapping_list: torch.Tensor, seq_lens: list[int], device: torch.device | str, ): """ Split a slot mapping into valid prefill- and decode-phase slot mappings. Context: * Your goal is to test (1) prefill of N prompts, with prompt-lengths {K_i \\forall i \\in [0,N)}, followed by (2) decoding of a single token for all N prompts (N tokens total); the resultant sequence lengths after decode would be {K_i + 1 for i \\in [0,N)} * The test you want to do requires (1) having the prefill slot mapping for all tokens present during prefill, the number of which is M = \\sum_i{K_i}, and (2) having the decode slot mapping for all N decoded tokens This function consumes a single 1D slot mapping, which is the concatenation of N slot mappings each of length K_i + 1 (corresponding to the sequence lengths after decode), with a total length of P = \\sum_i{K_i + 1} = M + N The prefill-phase slot mapping results from excising the (K_i + 1)-th entry from each of the N subsequences in the slot mapping (i.e. omitting the decoded token's mapping.) The N excised entries are appended to obtain the decode-phase slot mapping Arguments: * slot_mapping_list: Length-P 1D slot mapping (as list) reflecting all N post-decode sequences * seq_lens: list of N post-decode sequence lengths (K_i + 1 in the description above) * device: cuda, cpu, etc. Returns: * prefill_slot_mapping: Length-M 1D slot mapping (as Tensor) reflecting all N prefill prompts * decode_slot_mapping: Length-N 1D slot mapping (as Tensor) reflecting all N decoded tokens """ prefill_slot_mapping = [] decode_slot_mapping = [] base_idx = 0 for seq_len in seq_lens: prefill_slot_mapping.extend( slot_mapping_list[base_idx : (base_idx + seq_len - 1)] ) decode_slot_mapping.append(slot_mapping_list[base_idx + seq_len - 1]) base_idx += seq_len return ( maybe_make_long_tensor(prefill_slot_mapping, device), maybe_make_long_tensor(decode_slot_mapping, device), ) def make_block_tables_slot_mapping( block_size: int, seq_lens: list[int], device: torch.device | str, block_base_addr: int = 0, ) -> tuple[torch.Tensor, list[int], int]: """ Construct fake block tables & slot mappings. For a sequence with num_tokens tokens the minimum number of required KV cache blocks is num_blocks = (num_tokens + block_size) // block_size Then the minimum KV cache size in blocks is total_cache_blocks = sum(num_blocks for all seqs) Then, the blocktable mapping counts downward from block_base_addr + total_cache_blocks to block_base_addr The constructed block-tables and slot-mapping are sized to the lengths of the sequences in their entirety (as reflected by seq_lens), i.e. the total of prefill prompt tokens + decoded tokens. Arguments: * block_size: number of offsets per block * seq_lens: list of token-counts for each sequence * block_base_addr: the block table base address * device: CPU or CUDA device Return: * block_tables_tensor: block table for sequence * slot_mapping_list: slot mapping for sequence * max_block_idx: the highest block address within this block table """ # Provision minimum number of KV cache blocks num_blocks_list = [ _num_tokens_to_min_blocks(num_tokens, block_size) for num_tokens in seq_lens ] max_block_table_len = max(num_blocks_list) block_table_pad_tokens = 10 block_tables = [] slot_mapping_list = [] # Compute uppermost address of block table total_cache_blocks = sum(num_blocks_list) block_base_idx = block_base_addr + total_cache_blocks max_block_idx = block_base_idx for sdx, num_tokens in enumerate(seq_lens): num_blocks = num_blocks_list[sdx] block_table = list(range(block_base_idx, block_base_idx - num_blocks, -1)) for idx in range(num_tokens): mapping_value = (idx % block_size) + block_table[ idx // block_size ] * block_size slot_mapping_list.append(mapping_value) block_base_idx -= num_blocks block_tables.append(block_table) block_tables_tensor = make_tensor_with_pad( block_tables, max_len=max_block_table_len + block_table_pad_tokens, pad=0, dtype=torch.int, device=device, ) return (block_tables_tensor, slot_mapping_list, max_block_idx) def assert_actual_matches_ideal( test_params: PhaseTestParameters, output_under_test: torch.Tensor, backend: str ) -> None: """ Assert that observed output matches the ideal output contained in the test parameters data structure. Arguments: * test_params: Test parameters including packed ideal output * output_under_test: actually observed output value """ ideal_output = test_params.packed_qkvo.ideal_output if backend != "FLASH_ATTN": raise ValueError(f"Unknown backend value: '{backend}'. Expected 'FLASH_ATTN'.") # For FlashAttention override the accuracy thresholds to non default # values since we notice a higher difference between the ideal and # actual output. torch.testing.assert_close( ideal_output, output_under_test.view_as(ideal_output), atol=0.01, rtol=0.016 ) # Copied/modified from torch._refs.__init__.py def fp8_allclose( a: TensorLikeType, b: TensorLikeType, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False, ) -> bool: """ Reference implementation of torch.allclose """ torch._refs._check_close_args(name="torch.allclose", a=a, b=b, rtol=rtol, atol=atol) return bool( torch.all( torch.isclose( a.double(), b.double(), rtol=rtol, atol=atol, equal_nan=equal_nan ) ).item() ) # Marlin MoE test utils def stack_and_dev(tensors: list[torch.Tensor]): dev = tensors[0].device return torch.stack(tensors, dim=0).to(dev) def compute_max_diff(output, output_ref): return torch.mean(torch.abs(output - output_ref)) / torch.mean( torch.abs(output_ref) ) def torch_experts( a: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, topk_weight: torch.Tensor, topk_ids: torch.Tensor, global_num_experts: int = -1, b_bias1: torch.Tensor | None = None, b_bias2: torch.Tensor | None = None, expert_map: torch.Tensor | None = None, w1_scale: torch.Tensor | None = None, w2_scale: torch.Tensor | None = None, a1_scale: torch.Tensor | None = None, a2_scale: torch.Tensor | None = None, quant_dtype: torch.dtype | None = None, per_act_token_quant=False, block_shape: list[int] | None = None, apply_router_weights_on_input: bool = False, activation: str = "silu_and_mul", ) -> torch.Tensor: assert ( global_num_experts == -1 or (global_num_experts == w1.shape[0] and expert_map is None) or (expert_map is not None and global_num_experts == expert_map.shape[0]) ) if quant_dtype in [torch.float16, torch.bfloat16]: quant_dtype = None quant_input_only = quant_dtype is not None and w1_scale is None and w2_scale is None if quant_input_only: assert a1_scale is None and a2_scale is None assert per_act_token_quant M, K = a.shape topk = topk_ids.shape[1] if apply_router_weights_on_input: assert topk == 1 a = a * topk_weight.to(a.dtype) a = a.view(M, -1, K).repeat(1, topk, 1).reshape(-1, K) out = torch.zeros(M * topk, w2.shape[1], dtype=a.dtype, device=a.device) if a1_scale: assert not per_act_token_quant and block_shape is None a, a_scale = moe_kernel_quantize_input( a, a1_scale, quant_dtype, per_act_token_quant, block_shape ) if quant_input_only: a = (a.float() * a_scale.view(-1, 1)).to(w1.dtype) num_experts = w1.shape[0] topk_ids = topk_ids.view(-1) if expert_map is not None: topk_ids = expert_map[topk_ids] f32 = torch.float32 act = CustomOp.op_registry[activation] for i in range(num_experts): mask = topk_ids == i if mask.sum(): if quant_dtype is None: tmp1 = a[mask] @ w1[i].transpose(0, 1) if b_bias1 is not None: tmp1 = tmp1 + b_bias1[i].view(1, -1).to(tmp1.dtype) tmp2 = act()(tmp1) out[mask] = tmp2 @ w2[i].transpose(0, 1) if b_bias2 is not None: out[mask] = out[mask] + b_bias2[i].view(1, -1).to(tmp1.dtype) elif quant_input_only: tmp1 = a[mask] @ w1[i].transpose(0, 1) tmp2 = SiluAndMul()(tmp1) tmp2, tmp2_scale = moe_kernel_quantize_input( tmp2, None, quant_dtype, per_act_token_quant ) tmp2 = (tmp2.float() * tmp2_scale.view(-1, 1)).to(w2.dtype) out[mask] = tmp2 @ w2[i].transpose(0, 1) elif block_shape is not None: # block quantized assert ( a_scale is not None and w1_scale is not None and w2_scale is not None ) tmp1 = native_w8a8_block_matmul( a[mask], w1[i], a_scale[mask], w1_scale[i], block_shape, out.dtype ) if b_bias1 is not None: tmp1 = tmp1 + b_bias1[i].view(1, -1).to(tmp1.dtype) tmp2 = SiluAndMul()(tmp1) tmp2, b_scale = moe_kernel_quantize_input( tmp2, a2_scale, quant_dtype, per_act_token_quant, block_shape ) out[mask] = native_w8a8_block_matmul( tmp2, w2[i], b_scale, w2_scale[i], block_shape, out.dtype ) if b_bias2 is not None: out[mask] = out[mask] + b_bias2[i].view(1, -1).to(tmp1.dtype) else: assert ( a_scale is not None and w1_scale is not None and w2_scale is not None ) scales = a_scale if a_scale.numel() == 1 else a_scale[mask] tmp1 = a[mask].to(f32) * scales w1_dq = (w1[i].to(f32) * w1_scale[i]).transpose(0, 1) tmp1 = (tmp1 @ w1_dq).to(out.dtype) if b_bias1 is not None: tmp1 = tmp1 + b_bias1[i].view(1, -1).to(out.dtype) tmp2 = SiluAndMul()(tmp1).to(out.dtype) tmp2, b_scale = moe_kernel_quantize_input( tmp2, a2_scale, quant_dtype, per_act_token_quant, block_shape ) assert b_scale is not None tmp2 = tmp2.to(f32) * b_scale w2_dq = (w2[i].to(f32) * w2_scale[i]).transpose(0, 1) out[mask] = (tmp2 @ w2_dq).to(out.dtype) if b_bias2 is not None: out[mask] = out[mask] + b_bias2[i].view(1, -1).to(out.dtype) if apply_router_weights_on_input: return out else: return ( (out.view(M, -1, w2.shape[1]).to(f32) * topk_weight.view(M, -1, 1)) .sum(dim=1) .to(out.dtype) ) def torch_moe( a: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, score: torch.Tensor, topk: int, b_bias1: torch.Tensor | None = None, b_bias2: torch.Tensor | None = None, global_num_experts: int = -1, expert_map: torch.Tensor | None = None, activation: str = "silu_and_mul", ) -> torch.Tensor: score = torch.softmax(score, dim=-1, dtype=torch.float32) topk_weight, topk_ids = torch.topk(score, topk) return torch_experts( a, w1, w2, topk_weight, topk_ids, global_num_experts, b_bias1, b_bias2, expert_map, activation=activation, ) def torch_moe_single(a, w, score, topk): B, D = a.shape a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) out = torch.zeros(B * topk, w.shape[1], dtype=a.dtype, device=a.device) score = torch.softmax(score, dim=-1, dtype=torch.float32) _, topk_ids = torch.topk(score, topk) topk_ids = topk_ids.view(-1) for i in range(w.shape[0]): mask = topk_ids == i if mask.sum(): out[mask] = a[mask] @ w[i].transpose(0, 1) return (out.view(B, -1, w.shape[1])).sum(dim=1) # A special version of op check that has a restricted default set of test_utils # and a patched version of allclose that supports fp8 types. def opcheck( op: torch._ops.OpOverload | torch._ops.OpOverloadPacket | torch._library.custom_ops.CustomOpDef, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None, *, test_utils: str | Sequence[str] = ALL_OPCHECK_TEST_UTILS, raise_exception: bool = True, cond: bool = True, ) -> dict[str, str]: with patch("torch.allclose", new=fp8_allclose): return ( torch.library.opcheck(
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/__init__.py
tests/kernels/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quant_utils.py
tests/kernels/quant_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm.model_executor.layers.quantization.utils.quant_utils import group_broadcast from vllm.platforms import current_platform from vllm.utils.math_utils import round_up # Using the default value (240.0) from pytorch will cause accuracy # issue on dynamic quantization models. Here use 224.0 for rocm. ROCM_FP8FNUZ_MAX = 224.0 FP8_DTYPE = current_platform.fp8_dtype() def as_float32_tensor(x: float | torch.Tensor) -> torch.Tensor: return torch.as_tensor(x, dtype=torch.float32, device="cuda") def ref_dynamic_per_token_quant( x: torch.Tensor, quant_dtype: torch.dtype, scale_ub: torch.Tensor | None = None ) -> tuple[torch.Tensor, torch.Tensor]: assert quant_dtype in [torch.int8, FP8_DTYPE] if scale_ub is not None: assert quant_dtype == FP8_DTYPE qtype_traits = ( torch.iinfo(quant_dtype) if quant_dtype == torch.int8 else torch.finfo(quant_dtype) ) use_fp8fnuz = ( current_platform.is_fp8_fnuz() and quant_dtype == current_platform.fp8_dtype() ) qtype_traits_max = ROCM_FP8FNUZ_MAX if use_fp8fnuz else qtype_traits.max qtype_traits_min = -ROCM_FP8FNUZ_MAX if use_fp8fnuz else qtype_traits.min qtype_max = as_float32_tensor(qtype_traits_max) s_1 = as_float32_tensor(1.0) s_512 = as_float32_tensor(512.0) # For fp8, in order to match the cuda kernel output, we have to do exactly # the same operations as in the corresponding fp8 kernel to prevent # rounding errors. # Compute scales x_token_max, _ = x.abs().max(dim=-1) x_token_max = as_float32_tensor(x_token_max) if scale_ub is not None: x_token_max = x_token_max.clamp(max=scale_ub) scales = (x_token_max / qtype_max)[:, None] # Quant if quant_dtype == torch.int8: iscales = as_float32_tensor(s_1 / scales) torch_out = as_float32_tensor(x) * iscales torch_out = torch_out.round() torch_out = torch_out.clamp(qtype_traits_min, qtype_traits_max).to(quant_dtype) else: assert quant_dtype == FP8_DTYPE min_scaling_factor = s_1 / (qtype_max * s_512) scales = scales.clamp(min=min_scaling_factor) torch_out = as_float32_tensor(x) / scales torch_out = torch_out.clamp(qtype_traits_min, qtype_traits_max).to(quant_dtype) return torch_out, scales # The int8 version is very similar. Incorporate the int8 version, like in # ref_dynamic_per_token_quant, when we have a dynamic_per_tensor int8 quant # kernel def ref_dynamic_per_tensor_fp8_quant( x: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: fp8_traits = torch.finfo(FP8_DTYPE) fp8_traits_max = ( ROCM_FP8FNUZ_MAX if current_platform.is_rocm() and current_platform.is_fp8_fnuz() else fp8_traits.max ) fp8_traits_min = ( -ROCM_FP8FNUZ_MAX if current_platform.is_rocm() and current_platform.is_fp8_fnuz() else fp8_traits.min ) fp8_max = as_float32_tensor(fp8_traits_max) one = as_float32_tensor(1.0) # For fp8, in order to match the cuda kernel output, we have to do exactly # the same operations as in the corresponding fp8 kernel to prevent # rounding errors. x_max = as_float32_tensor(x.abs().max()) ref_scale = x_max / fp8_max ref_iscale = one / ref_scale ref_out = ( (as_float32_tensor(x) * ref_iscale) .clamp(fp8_traits_min, fp8_traits_max) .to(FP8_DTYPE) ) return ref_out, ref_scale.view(1) def native_w8a8_block_matmul( A: torch.Tensor, B: torch.Tensor, As: torch.Tensor, Bs: torch.Tensor, block_size: list[int], output_dtype: torch.dtype, compute_type: torch.dtype = torch.float32, ) -> torch.Tensor: """This function performs matrix multiplication with block-wise quantization using native torch. It is agnostic to the input data type and can be used for both int8 and fp8 data types. It takes two input tensors `A` and `B` (int8) with scales `As` and `Bs` (float32). The output is returned in the specified `output_dtype`. """ A = A.to(compute_type) B = B.to(compute_type) assert A.shape[-1] == B.shape[-1] assert B.ndim == 2 and B.is_contiguous() and Bs.ndim == 2 assert len(block_size) == 2 block_n, block_k = block_size[0], block_size[1] assert (A.shape[-1] + block_k - 1) // block_k == As.shape[-1] assert A.shape[:-1] == As.shape[:-1] M = A.numel() // A.shape[-1] N, K = B.shape origin_C_shape = A.shape[:-1] + (N,) A = A.reshape(M, A.shape[-1]) As = As.reshape(M, As.shape[-1]) n_tiles = (N + block_n - 1) // block_n k_tiles = (K + block_k - 1) // block_k assert n_tiles == Bs.shape[0], f"{n_tiles} == {Bs.shape[0]}" assert k_tiles == Bs.shape[1], f"{k_tiles} == {Bs.shape[1]}" C_shape = (M, N) C = torch.zeros(C_shape, dtype=compute_type, device=A.device) A_tiles = [A[:, i * block_k : min((i + 1) * block_k, K)] for i in range(k_tiles)] B_tiles = [ [ B[ j * block_n : min((j + 1) * block_n, N), i * block_k : min((i + 1) * block_k, K), ] for i in range(k_tiles) ] for j in range(n_tiles) ] C_tiles = [C[:, j * block_n : min((j + 1) * block_n, N)] for j in range(n_tiles)] As_tiles = [As[:, i : i + 1] for i in range(k_tiles)] for i in range(k_tiles): for j in range(n_tiles): a = A_tiles[i] b = B_tiles[j][i] c = C_tiles[j] s = As_tiles[i] * Bs[j][i] c[:, :] += torch.matmul(a, b.t()) * s C = C.reshape(origin_C_shape).to(output_dtype) return C def native_per_token_group_quant_fp8( x, group_size, eps=1e-10, dtype=torch.float8_e4m3fn ): """Function to perform per-token-group quantization on an input tensor `x` using native torch.""" assert x.shape[-1] % group_size == 0, ( "the last dimension of `x` must be divisible by `group_size`" ) assert x.is_contiguous(), "`x` is not contiguous" finfo = torch.finfo(dtype) fp8_min = finfo.min fp8_max = finfo.max x_ = x.reshape(x.numel() // group_size, group_size) amax = x_.abs().max(dim=-1, keepdim=True)[0].clamp(min=eps).to(torch.float32) x_s = amax / fp8_max x_q = (x_ / x_s).clamp(min=fp8_min, max=fp8_max).to(dtype) x_q = x_q.reshape(x.shape) x_s = x_s.reshape(x.shape[:-1] + (x.shape[-1] // group_size,)) return x_q, x_s def native_per_token_group_quant_int8(x, group_size, eps=1e-10, dtype=torch.int8): """Function to perform per-token-group quantization on an input tensor `x` using native torch. It converts the tensor values into int8 values and returns the quantized tensor along with the scaling factor used for quantization. """ assert x.shape[-1] % group_size == 0, ( "the last dimension of `x` must be divisible by `group_size`" ) assert x.is_contiguous(), "`x` is not contiguous" iinfo = torch.iinfo(dtype) int8_min = iinfo.min int8_max = iinfo.max x_ = x.reshape(x.numel() // group_size, group_size) # Use float32 for scale calculation for stability amax = x_.abs().max(dim=-1, keepdim=True)[0].clamp(min=eps).to(torch.float32) x_s = amax / int8_max x_q = ( (x_.to(torch.float32) / x_s).round().clamp(min=int8_min, max=int8_max).to(dtype) ) # Round before clamping x_q = x_q.reshape(x.shape) x_s = x_s.reshape(x.shape[:-1] + (x.shape[-1] // group_size,)) return x_q, x_s DEFAULT_BLOCK_SHAPE = [128, 128] def per_block_cast_to_int8( x: torch.Tensor, block_shape: list[int] = DEFAULT_BLOCK_SHAPE, ) -> tuple[torch.Tensor, torch.Tensor]: block_m, block_n = block_shape assert x.dim() == 2 m, n = x.shape x_padded = torch.zeros( (round_up(m, block_m), round_up(n, block_n)), dtype=x.dtype, device=x.device ) x_padded[:m, :n] = x x_view = x_padded.view(-1, block_m, x_padded.size(1) // block_n, block_n) x_amax = x_view.abs().float().amax(dim=(1, 3), keepdim=True).clamp(1e-4) x_scaled = (x_view * (256.0 / x_amax)).to(torch.int8) x_scaled_sub = x_scaled.view_as(x_padded)[:m, :n].contiguous() scales = (x_amax / 256.0).view(x_view.size(0), x_view.size(2)) return x_scaled_sub, scales def dequant( t: torch.Tensor, scale: torch.Tensor | None, block_shape: list[int] | None, per_act_token_quant: bool, out_dtype: torch.dtype | None = torch.float32, ) -> torch.Tensor: if scale is not None: f32 = torch.float32 if per_act_token_quant or block_shape is None: return (t.to(f32) * scale).to(out_dtype) else: return (t.to(f32) * group_broadcast(scale, t.shape)).to(out_dtype) else: return t.to(out_dtype) def batched_dequant( t: torch.Tensor, scale: torch.Tensor | None, block_shape: list[int] | None, per_act_token_quant: bool, out_dtype: torch.dtype | None = torch.float32, ) -> torch.Tensor: if scale is not None: assert t.shape[0] == scale.shape[0] out = torch.empty_like(t, dtype=out_dtype) for e in range(t.shape[0]): out[e] = dequant( t[e], scale[e], block_shape, per_act_token_quant, out_dtype ) return out return t.to(out_dtype) def native_batched_masked_quant_matmul( A: torch.Tensor, B: torch.Tensor, C: torch.Tensor, num_expert_tokens: torch.Tensor, A_scale: torch.Tensor | None = None, B_scale: torch.Tensor | None = None, block_shape: list[int] | None = None, per_act_token_quant: bool = False, ) -> torch.Tensor: num_expert_tokens_cpu = num_expert_tokens.clone() num_expert_tokens_cpu = num_expert_tokens_cpu.to(device="cpu") num_experts = num_expert_tokens.size(0) for e in range(num_experts): num_tokens = num_expert_tokens_cpu[e] if A.dtype.itemsize == 1 and block_shape is not None: assert A_scale is not None and B_scale is not None tmp = native_w8a8_block_matmul( A[e], B[e], A_scale[e], B_scale[e], block_shape, C.dtype ) C[e, :num_tokens, :] = tmp[:num_tokens, :] elif A.dtype.itemsize == 1 and block_shape is None: assert A_scale is not None and B_scale is not None A_dq = dequant(A[e], A_scale[e], block_shape, per_act_token_quant) B_dq = dequant(B[e], B_scale[e], block_shape, per_act_token_quant) C[e, :num_tokens, :] = (A_dq[:num_tokens] @ B_dq.transpose(0, 1)).to( C.dtype ) else: assert A_scale is None assert B_scale is None C[e, :num_tokens, :] = A[e, :num_tokens, :] @ B[e].transpose(0, 1) return C
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_flex_attention.py
tests/kernels/test_flex_attention.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Integration tests for FlexAttention backend vs default backend""" import random import numpy as np import pytest import torch from packaging import version from tests.v1.attention.utils import ( BatchSpec, create_common_attn_metadata, create_standard_kv_cache_spec, create_vllm_config, ) from vllm.v1.attention.backends.flex_attention import ( FlexAttentionMetadataBuilder, physical_to_logical_mapping, ) from ..models.utils import check_embeddings_close, check_logprobs_close TORCH_VERSION = version.parse(torch.__version__) MINIMUM_TORCH_VERSION = version.parse("2.7.0") DIRECT_BUILD_VERSION = version.parse("2.9.dev0") def set_seed(seed): """Set seeds for reproducibility""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) @pytest.mark.skipif( not torch.cuda.is_available() or TORCH_VERSION < MINIMUM_TORCH_VERSION, reason="CUDA not available or PyTorch version < 2.7", ) def test_flex_attention_vs_default_backend(vllm_runner): """Test that FlexAttention produces the same outputs as the default backend. This test compares the outputs from the FlexAttention backend with the default backend, ensuring they are similar when using the same seed. """ model_name = "Qwen/Qwen2.5-1.5B-Instruct" seed = 42 max_tokens = 24 num_logprobs = 5 prompts = [ "Hello, my name is", "The president of the United States is", "The capital of France is", ] # Run with flex attention set_seed(seed) with vllm_runner( model_name, runner="generate", tensor_parallel_size=1, num_gpu_blocks_override=128, enforce_eager=True, attention_config={"backend": "FLEX_ATTENTION"}, ) as llm_flex: output_flex = llm_flex.generate_greedy_logprobs( prompts, max_tokens, num_logprobs ) # Run with default backend set_seed(seed) with vllm_runner( model_name, runner="generate", tensor_parallel_size=1, num_gpu_blocks_override=128, enforce_eager=True, gpu_memory_utilization=0.85, ) as llm_default: output_default = llm_default.generate_greedy_logprobs( prompts, max_tokens, num_logprobs ) check_logprobs_close( outputs_0_lst=output_flex, outputs_1_lst=output_default, name_0="flex", name_1="default", ) @pytest.mark.skipif( not torch.cuda.is_available() or TORCH_VERSION < MINIMUM_TORCH_VERSION, reason="CUDA not available or PyTorch version < 2.7", ) def test_encoder_flex_attention_vs_default_backend(vllm_runner): """Test that FlexAttention produces the same outputs as the default backend. This test compares the outputs from the FlexAttention backend with the default backend for encoder models. """ model_name = "BAAI/bge-base-en-v1.5" prompts = [ "Hello, my name is", "The president of the United States is", "The capital of France is", ] # Run with flex attention with vllm_runner( model_name, runner="pooling", dtype=torch.bfloat16, tensor_parallel_size=1, max_model_len=100, enforce_eager=True, attention_config={"backend": "FLEX_ATTENTION"}, ) as llm_flex: flex_outputs = llm_flex.embed(prompts) # Run with default backend with vllm_runner( model_name, runner="pooling", dtype=torch.bfloat16, tensor_parallel_size=1, max_model_len=100, enforce_eager=True, ) as llm_default: default_outputs = llm_default.embed(prompts) check_embeddings_close( embeddings_0_lst=flex_outputs, embeddings_1_lst=default_outputs, name_0="flex", name_1="default", tol=1e-2, ) @pytest.mark.skipif( not torch.cuda.is_available() or TORCH_VERSION < DIRECT_BUILD_VERSION, reason="CUDA not available or PyTorch version < 2.7", ) def test_block_mask_direct_vs_slow_path(): """Test that direct path block mask is a superset of slow path. The direct path may include extra blocks for performance (over-estimation), but must include all blocks that the slow path determines are necessary. """ device = torch.device("cuda") vllm_config = create_vllm_config( model_name="meta-llama/Meta-Llama-3-8B", block_size=16, max_model_len=1024 ) kv_cache_spec = create_standard_kv_cache_spec(vllm_config) # Use a mixed batch that will create groups spanning multiple sequences batch_spec = BatchSpec( seq_lens=[35, 64, 128, 256], query_lens=[33, 5, 32, 64], name="test_mixed_batch" ) common_attn_metadata = create_common_attn_metadata( batch_spec, vllm_config.cache_config.block_size, device ) builder = FlexAttentionMetadataBuilder(kv_cache_spec, [], vllm_config, device) metadata_direct = builder.build( common_prefix_len=0, common_attn_metadata=common_attn_metadata ) builder.direct_build = False metadata_slow = builder.build( common_prefix_len=0, common_attn_metadata=common_attn_metadata ) assert metadata_direct.block_mask is not None assert metadata_slow.block_mask is not None # Extract block indices for comparison, B, H are the same direct_indices = metadata_direct.block_mask.kv_indices[0, 0] slow_indices = metadata_slow.block_mask.kv_indices[0, 0] direct_num = metadata_direct.block_mask.kv_num_blocks[0, 0] slow_num = metadata_slow.block_mask.kv_num_blocks[0, 0] # main test: every block needed by slow path must be in direct path num_groups = direct_num.shape[0] all_contained = True missing_details = [] for group_idx in range(num_groups): direct_blocks = set(direct_indices[group_idx, : direct_num[group_idx]].tolist()) slow_blocks = set(slow_indices[group_idx, : slow_num[group_idx]].tolist()) missing_blocks = slow_blocks - direct_blocks if missing_blocks: all_contained = False missing_details.append( f"Group {group_idx}: missing {sorted(missing_blocks)}" ) assert all_contained, ( "Direct path is missing blocks required by slow path:\n" + "\n".join(missing_details) ) def test_physical_to_logical_mapping_handles_reused_blocks(): """Regression test: reused physical blocks map to the latest logical block. For sliding-window / hybrid attention layers, physical KV-cache blocks can be reused over time. The inverse mapping must therefore select the latest logical block index for a physical block id. """ # Padding should not make physical block 0 look live. block_table = torch.tensor([[6, 0, 0, 0]], dtype=torch.int32) seq_lens = torch.tensor([1 * 16], dtype=torch.int32) # only 1 block valid out = physical_to_logical_mapping( block_table=block_table, seq_lens=seq_lens, block_size=16, total_blocks=10 ) assert out[0, 0].item() == -1 assert out[0, 6].item() == 0 # If a physical block id appears multiple times (block reuse), mapping should # point to the latest logical block index. block_table2 = torch.tensor([[2, 2, 5]], dtype=torch.int32) seq_lens2 = torch.tensor([3 * 16], dtype=torch.int32) out2 = physical_to_logical_mapping( block_table=block_table2, seq_lens=seq_lens2, block_size=16, total_blocks=8 ) assert out2[0, 2].item() == 1 if __name__ == "__main__": pytest.main([__file__])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/test_apply_repetition_penalties.py
tests/kernels/test_apply_repetition_penalties.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from tests.kernels.utils import opcheck from vllm._custom_ops import ( apply_repetition_penalties_cuda, apply_repetition_penalties_torch, ) from vllm.platforms import current_platform NUM_SEQS = [1, 2, 3, 4, 8, 13, 17, 32, 37, 256, 1023, 1024, 1025] # [stress, stress, stress, Qwen, llama 4] VOCAB_SIZES = [17, 256, 1019, 151936, 202048] REPETITION_PENALTY_VALUES = [1.05] SEEDS = [0] DTYPES = [torch.float32, torch.float16] @pytest.mark.parametrize("num_seqs", NUM_SEQS) @pytest.mark.parametrize("vocab_size", VOCAB_SIZES) @pytest.mark.parametrize("repetition_penalty", REPETITION_PENALTY_VALUES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.skipif( not current_platform.is_cuda(), reason="This test for checking CUDA kernel" ) @torch.inference_mode() def test_apply_repetition_penalties( num_seqs: int, vocab_size: int, repetition_penalty: float, dtype: torch.dtype, seed: int, ) -> None: """ Test the apply_repetition_penalties custom op against a reference implementation. """ current_platform.seed_everything(seed) torch.set_default_device("cuda:0") # Create test data logits = torch.randn(num_seqs, vocab_size, dtype=dtype) # Create masks with some random tokens marked as repeated prompt_mask = torch.zeros(num_seqs, vocab_size, dtype=torch.bool) output_mask = torch.zeros(num_seqs, vocab_size, dtype=torch.bool) # Mark some tokens as repeated in prompt and output prompt_indices = torch.randint(0, vocab_size, (num_seqs, max(1, vocab_size // 200))) output_indices = torch.randint(0, vocab_size, (num_seqs, max(1, vocab_size // 200))) for i in range(num_seqs): prompt_mask[i, prompt_indices[i]] = True output_mask[i, output_indices[i]] = True # Create repetition penalties tensor repetition_penalties = torch.full((num_seqs,), repetition_penalty, dtype=dtype) # Run all three implementations logits_torch = logits.clone() logits_cuda = logits.clone() apply_repetition_penalties_torch( logits_torch, prompt_mask, output_mask, repetition_penalties ) apply_repetition_penalties_cuda( logits_cuda, prompt_mask, output_mask, repetition_penalties ) # Compare all outputs to reference torch.testing.assert_close(logits_torch, logits_cuda, rtol=1e-3, atol=1e-3) # Test the operator by applying the opcheck utility opcheck( torch.ops._C.apply_repetition_penalties_, (logits.clone(), prompt_mask, output_mask, repetition_penalties), ) @pytest.mark.skipif( not current_platform.is_cuda(), reason="This test for checking CUDA kernel" ) @torch.inference_mode() def test_apply_repetition_penalties_zero_seqs() -> None: """ Test the apply_repetition_penalties custom op with num_seqs=0 against a reference implementation. """ num_seqs = 0 vocab_size = 17 repetition_penalty = 1.05 dtype = torch.float32 seed = 0 current_platform.seed_everything(seed) torch.set_default_device("cuda:0") # Create test data logits = torch.randn(num_seqs, vocab_size, dtype=dtype) # Create masks with some random tokens marked as repeated prompt_mask = torch.zeros(num_seqs, vocab_size, dtype=torch.bool) output_mask = torch.zeros(num_seqs, vocab_size, dtype=torch.bool) # No tokens to mark as repeated since num_seqs=0 # Create repetition penalties tensor repetition_penalties = torch.full((num_seqs,), repetition_penalty, dtype=dtype) # Run all three implementations logits_torch = logits.clone() logits_cuda = logits.clone() apply_repetition_penalties_torch( logits_torch, prompt_mask, output_mask, repetition_penalties ) apply_repetition_penalties_cuda( logits_cuda, prompt_mask, output_mask, repetition_penalties ) # Compare all outputs to reference torch.testing.assert_close(logits_torch, logits_cuda, rtol=1e-3, atol=1e-3) # Test the operator by applying the opcheck utility opcheck( torch.ops._C.apply_repetition_penalties_, (logits.clone(), prompt_mask, output_mask, repetition_penalties), )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_triton_decode_attention.py
tests/kernels/attention/test_triton_decode_attention.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.attention.ops.triton_decode_attention import decode_attention_fwd from vllm.utils.math_utils import cdiv @pytest.mark.parametrize("B", [3, 5]) @pytest.mark.parametrize("L", [1027, 1025]) @pytest.mark.parametrize("H_Q", [32]) @pytest.mark.parametrize("H_KV", [32, 8]) @pytest.mark.parametrize("D_QK", [128, 192, 576]) @pytest.mark.parametrize("D_V", [128, 512]) @pytest.mark.parametrize("CACHE_SIZE", [16384]) @pytest.mark.parametrize("PAGE_SIZE", [1, 16]) def test_decode_attention(B, L, H_Q, H_KV, D_QK, D_V, CACHE_SIZE, PAGE_SIZE): assert CACHE_SIZE % PAGE_SIZE == 0 dtype = torch.bfloat16 seq_len = L # This represents the number of tokens already in the sequence sm_scale = 1.0 / (D_QK**0.5) num_kv_splits = 8 num_pages_per_batch = cdiv(seq_len, PAGE_SIZE) req_to_page = torch.randint( 0, CACHE_SIZE // PAGE_SIZE, (B, num_pages_per_batch, 1), device="cuda" ) req_to_token = req_to_page * PAGE_SIZE req_to_token = req_to_token.expand(B, num_pages_per_batch, PAGE_SIZE) req_to_token = req_to_token + torch.arange(PAGE_SIZE, device="cuda").view(1, 1, -1) req_to_token = req_to_token.view(B, -1) req_to_token = req_to_token[:, :seq_len].contiguous() # q represents the new token being generated, one per batch q = torch.randn(B, H_Q, D_QK, dtype=dtype, device="cuda") # k_buffer and v_buffer represent all previous tokens # Page size is 1. k_buffer = torch.randn(CACHE_SIZE, H_KV, D_QK, dtype=dtype, device="cuda") v_buffer = torch.randn(CACHE_SIZE, H_KV, D_V, dtype=dtype, device="cuda") # o will have the same shape as q o = torch.zeros(B, H_Q, D_V, dtype=dtype, device="cuda") lse = torch.zeros(B, H_Q, dtype=dtype, device="cuda") b_seq_len = torch.full((B,), seq_len, device="cuda") attn_logits = torch.empty( (B, H_Q, num_kv_splits, D_V + 1), dtype=torch.float32, device="cuda", ) # Call the original implementation. decode_attention_fwd( q, k_buffer, v_buffer, o, lse, req_to_token, b_seq_len, attn_logits, num_kv_splits, sm_scale, ) # Page size can be larger than 1. k_buffer = k_buffer.view(CACHE_SIZE // PAGE_SIZE, PAGE_SIZE, H_KV, D_QK) v_buffer = v_buffer.view(CACHE_SIZE // PAGE_SIZE, PAGE_SIZE, H_KV, D_V) o1 = torch.zeros_like(o) lse1 = torch.zeros_like(lse) decode_attention_fwd( q, k_buffer, v_buffer, o1, lse1, req_to_page, b_seq_len, attn_logits, num_kv_splits, sm_scale, PAGE_SIZE, ) assert torch.allclose(o, o1)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_mha_attn.py
tests/kernels/attention/test_mha_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Test: * Tests for MMEncoderAttention layer """ import itertools from unittest.mock import patch import pytest import torch from vllm.attention.backends.registry import AttentionBackendEnum from vllm.attention.layers.mm_encoder_attention import MMEncoderAttention from vllm.attention.selector import _cached_get_attn_backend from vllm.platforms import current_platform from vllm.platforms.cpu import CpuPlatform from vllm.platforms.cuda import CudaPlatform from vllm.platforms.rocm import RocmPlatform @pytest.fixture(autouse=True) def clear_cache(): """Clear lru cache to ensure each test case runs without caching.""" _cached_get_attn_backend.cache_clear() devices = ["cpu"] if current_platform.is_cuda(): devices.append("cuda") if current_platform.is_rocm(): devices.append("hip") @pytest.mark.parametrize("device", devices) def test_mha_attn_platform(device: str): """ Test the attention selector between different platform and device. """ torch.set_default_dtype(torch.float16) if device == "cpu": with ( patch("vllm.model_executor.models.vision.current_platform", CpuPlatform()), ): attn = MMEncoderAttention(16, 64, scale=1) assert attn.attn_backend == AttentionBackendEnum.TORCH_SDPA elif device == "hip": with ( patch("vllm.model_executor.models.vision.current_platform", RocmPlatform()), ): attn = MMEncoderAttention(16, 64, scale=1) assert attn.attn_backend == AttentionBackendEnum.FLASH_ATTN else: # Test CUDA with head_size=64 (divisible by 32) # - should use vLLM's FlashAttention with ( patch("vllm.model_executor.models.vision.current_platform", CudaPlatform()), ): attn = MMEncoderAttention(16, 64, scale=1) assert attn.attn_backend == AttentionBackendEnum.FLASH_ATTN # Test CUDA with head_size=72 (not divisible by 32) # - should use vLLM's FlashAttention with ( patch("vllm.model_executor.models.vision.current_platform", CudaPlatform()), ): attn = MMEncoderAttention(16, 72, scale=1) assert attn.attn_backend == AttentionBackendEnum.FLASH_ATTN def ref_attention( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, scale: float, ) -> torch.Tensor: """ Native implementation of scaled dot product attention without mask: - query, key, value: [batch_size, seq_len, num_heads, head_size] - attn_mask: [batch_size, seq_len, seq_len] """ query, key, value = (x.transpose(1, 2) for x in (query, key, value)) attn_weights = scale * torch.matmul(query, key.transpose(2, 3)) attn_weights = torch.softmax(attn_weights, dim=-1).to(value.dtype) out = torch.matmul(attn_weights, value).transpose(1, 2) return out BATCH_SIZES = [1, 16] SEQ_LENS = [1] VAR_SEQ_LENS = [ [2, 2], [2, 3, 4], ] NUM_HEADS = [1, 16] NUM_KV_HEADS = [1] HEAD_SIZES = [64, 80] # flshattF and tritonflashattF supported: {torch.float16, torch.bfloat16} DTYPES = ( [torch.half, torch.bfloat16, torch.float] if not current_platform.is_rocm() else [torch.half, torch.bfloat16] ) CUDA_DEVICES = ["cuda"] @pytest.mark.parametrize("batch_size", BATCH_SIZES) @pytest.mark.parametrize("seq_len", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("num_kv_heads", NUM_KV_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("device", CUDA_DEVICES) def test_mha_attn_forward( batch_size: int, seq_len: int, num_heads: int, num_kv_heads: int, head_size: int, dtype: torch.dtype, device: str, ): current_platform.seed_everything(0) torch.set_default_device(device) torch.set_default_dtype(dtype) q = torch.randn(batch_size, seq_len, num_heads * head_size) k = torch.randn(batch_size, seq_len, num_kv_heads * head_size) v = torch.randn(batch_size, seq_len, num_kv_heads * head_size) scale = 1.0 / head_size**0.5 attn = MMEncoderAttention( num_heads, head_size, scale=scale, num_kv_heads=num_kv_heads ) output = attn(q, k, v) assert num_heads % num_kv_heads == 0 num_queries_per_kv = num_heads // num_kv_heads q = q.reshape(batch_size, seq_len, num_heads, head_size) k = k.reshape(batch_size, seq_len, num_kv_heads, head_size) v = v.reshape(batch_size, seq_len, num_kv_heads, head_size) if num_queries_per_kv > 1: k = torch.repeat_interleave(k, num_queries_per_kv, dim=2) v = torch.repeat_interleave(v, num_queries_per_kv, dim=2) ref_output = ref_attention( q, k, v, scale=scale, ).reshape(batch_size, seq_len, num_heads * head_size) torch.testing.assert_close(output, ref_output) @pytest.mark.parametrize("var_seq_len", VAR_SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("num_kv_heads", NUM_KV_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("device", CUDA_DEVICES) def test_mha_attn_varlen_forward( var_seq_len: list[int], num_heads: int, num_kv_heads: int, head_size: int, dtype: torch.dtype, device: str, ): current_platform.seed_everything(0) torch.set_default_device(device) torch.set_default_dtype(dtype) q = torch.randn(1, sum(var_seq_len), num_heads, head_size) k = torch.randn(1, sum(var_seq_len), num_kv_heads, head_size) v = torch.randn(1, sum(var_seq_len), num_kv_heads, head_size) cu_seqlens = torch.tensor( [0] + list(itertools.accumulate(var_seq_len)), dtype=torch.int32 ) scale = 1.0 / head_size**0.5 attn = MMEncoderAttention( num_heads, head_size, scale=scale, num_kv_heads=num_kv_heads ) output = attn( q, k, v, cu_seqlens=cu_seqlens, max_seqlen=torch.tensor(max(var_seq_len)) ) assert num_heads % num_kv_heads == 0 num_queries_per_kv = num_heads // num_kv_heads if num_queries_per_kv > 1: k = torch.repeat_interleave(k, num_queries_per_kv, dim=2) v = torch.repeat_interleave(v, num_queries_per_kv, dim=2) ref_output = [] for q_i, k_i, v_i in zip( torch.split(q, var_seq_len, dim=1), torch.split(k, var_seq_len, dim=1), torch.split(v, var_seq_len, dim=1), ): output_i = ref_attention( q_i, k_i, v_i, scale=scale, ) ref_output.append(output_i) ref_output = torch.cat(ref_output, dim=1) torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=1e-2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_pack_unpack_triton.py
tests/kernels/attention/test_pack_unpack_triton.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from torch.testing import assert_close from vllm.attention.ops.common import pack_seq_triton, unpack_seq_triton def test_pack_seq_basic_fp8(): """Test basic functionality of pack_seq_triton with fp8 and 3D tensors.""" device = "cuda" dtype = torch.float8_e4m3fn # Test cases with 3D tensors (N, H, D) test_cases = [ (6, 8, 4, 2, [3, 3]), # (6, 8, 4) -> (2, 3, 8, 4) (10, 4, 8, 3, [2, 4, 4]), # (10, 4, 8) -> (3, 4, 4, 8) (20, 16, 32, 4, [5, 5, 5, 5]), # (20, 16, 32) -> (4, 5, 16, 32) ] for N, H, D, B, lengths_list in test_cases: # Create input tensor with small values for fp8 x = torch.randn(N, H, D, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor(lengths_list, device=device) # Pack the data packed = pack_seq_triton(x, lengths) # Check output shape and properties expected_shape = (B, max(lengths_list), H, D) assert packed.shape == expected_shape assert packed.dtype == dtype assert packed.device == x.device # Check that valid data is preserved (within fp8 precision) for b in range(B): start_idx = sum(lengths_list[:b]) seq_len = lengths_list[b] expected_data = x[start_idx : start_idx + seq_len].to(torch.float32) actual_data = packed[b, :seq_len].to(torch.float32) assert_close(actual_data, expected_data, rtol=1e-1, atol=1e-2) def test_pack_seq_custom_padding_fp8(): """Test pack_seq_triton with custom padding values for fp8.""" device = "cuda" dtype = torch.float8_e4m3fn N, H, D, B = 20, 8, 16, 2 lengths = torch.tensor([10, 10], device=device) x = torch.randn(N, H, D, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) # Test with different padding values for pad_value in [-100.0, -10.0, 0.0, 10.0, 100.0]: result = pack_seq_triton(x, lengths, pad_value=pad_value) # Check valid data for b in range(B): start_idx = b * 10 expected_data = x[start_idx : start_idx + 10].to(torch.float32) actual_data = result[b, :10].to(torch.float32) assert_close(actual_data, expected_data, rtol=1e-1, atol=1e-2) # Check padding (fp8 has limited range, so check for large values) padded_data = result[:, 10:].to(torch.float32) if pad_value < 0: assert torch.all(padded_data < -50) # Large negative values elif pad_value > 0: assert torch.all(padded_data > 50) # Large positive values else: assert torch.allclose(padded_data, torch.zeros_like(padded_data), atol=1e-2) def test_pack_seq_default_negative_inf_padding_fp8(): """Test that pack_seq_triton uses -inf padding by default for fp8.""" device = "cuda" dtype = torch.float8_e4m3fn # B = 2 N, H, D = 20, 8, 16 lengths = torch.tensor([10, 10], device=device) x = torch.randn(N, H, D, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) result = pack_seq_triton(x, lengths) # Check that padding is large negative values (fp8 representation of -inf) padded_data = result[:, 10:].to(torch.float32) assert torch.all( padded_data < -100 ) # fp8 -inf is represented as large negative number def test_pack_seq_edge_cases_fp8(): """Test pack_seq_triton with edge cases for fp8.""" device = "cuda" dtype = torch.float8_e4m3fn # Test with single batch element x = torch.randn(10, 8, 16, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor([10], device=device) result = pack_seq_triton(x, lengths) assert result.shape == (1, 10, 8, 16) # Test with very short sequences x = torch.randn(20, 4, 8, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor([1, 1, 1], device=device) result = pack_seq_triton(x, lengths) assert result.shape == (3, 1, 4, 8) # Test with different sequence lengths x = torch.randn(15, 8, 16, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor([5, 7, 3], device=device) result = pack_seq_triton(x, lengths) assert result.shape == (3, 7, 8, 16) def test_pack_seq_different_block_sizes_fp8(): """Test pack_seq_triton with different block sizes for fp8.""" device = "cuda" dtype = torch.float8_e4m3fn N, H, D, B = 100, 16, 32, 4 lengths = torch.tensor([25, 25, 25, 25], device=device) x = torch.randn(N, H, D, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) # Test different block sizes for block_t, block_d in [(32, 32), (64, 64), (128, 128)]: result = pack_seq_triton(x, lengths, block_t=block_t, block_d=block_d) assert result.shape == (B, 25, H, D) # Check that valid data is preserved (within fp8 precision) for b in range(B): start_idx = b * 25 expected_data = x[start_idx : start_idx + 25].to(torch.float32) actual_data = result[b, :25].to(torch.float32) assert_close(actual_data, expected_data, rtol=1e-1, atol=1e-2) def test_pack_seq_shape_consistency(): """Test that pack_seq_triton maintains shape consistency.""" device = "cuda" dtype = torch.float8_e4m3fn N, H, D, B = 20, 8, 16, 2 lengths = torch.tensor([10, 10], device=device) x = torch.randn(N, H, D, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) result = pack_seq_triton(x, lengths) # Check shape consistency assert result.shape[0] == B # Batch dimension assert result.shape[1] == lengths.max().item() # Max sequence length assert result.shape[2:] == x.shape[1:] # Feature dimensions preserved def test_pack_unpack_roundtrip_fp8(): """Test that pack -> unpack gives us back the original data for fp8.""" device = "cuda" dtype = torch.float8_e4m3fn # Test cases with 3D tensors test_cases = [ (6, 8, 4, 2, [3, 3]), (10, 4, 8, 3, [2, 4, 4]), (20, 16, 32, 4, [5, 5, 5, 5]), (15, 8, 16, 3, [7, 5, 3]), ] for N, H, D, B, lengths_list in test_cases: # Create input tensor with small values for fp8 x = torch.randn(N, H, D, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor(lengths_list, device=device) # Pack the data packed = pack_seq_triton(x, lengths) # Unpack the data unpacked = unpack_seq_triton(packed, lengths) # Check that we get back the original data (within fp8 precision) assert unpacked.shape == x.shape x_f32 = x.to(torch.float32) unpacked_f32 = unpacked.to(torch.float32) assert_close(x_f32, unpacked_f32, rtol=1e-3, atol=1e-3) # Unpack without explicit start locations (computed in kernel) unpacked_with_loc = unpack_seq_triton(packed, lengths) assert_close(x_f32, unpacked_with_loc.to(torch.float32), rtol=1e-3, atol=1e-2) def test_unpack_seq_triton_edge_cases_fp8(): """Test unpack function with edge cases for fp8.""" device = "cuda" dtype = torch.float8_e4m3fn # Test with single batch element x = torch.randn(10, 8, 16, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor([10], device=device) packed = pack_seq_triton(x, lengths) unpacked = unpack_seq_triton(packed, lengths) assert unpacked.shape == x.shape assert_close(x.to(torch.float32), unpacked.to(torch.float32), rtol=1e-1, atol=1e-2) # Test with very short sequences x = torch.randn(20, 4, 8, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor([1, 1, 1], device=device) packed = pack_seq_triton(x, lengths) unpacked = unpack_seq_triton(packed, lengths) # Only compare the first 3 elements that were actually packed assert_close( x[:3].to(torch.float32), unpacked.to(torch.float32), rtol=1e-1, atol=1e-2 ) x = torch.randn(15, 8, 16, dtype=torch.float32, device=device) * 0.1 x = x.to(dtype=dtype) lengths = torch.tensor([5, 7, 3], device=device) packed = pack_seq_triton(x, lengths) unpacked = unpack_seq_triton(packed, lengths) assert unpacked.shape == x.shape assert_close(x.to(torch.float32), unpacked.to(torch.float32), rtol=1e-1, atol=1e-2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_flash_attn.py
tests/kernels/attention/test_flash_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.platforms import current_platform try: from vllm.vllm_flash_attn import ( fa_version_unsupported_reason, flash_attn_varlen_func, is_fa_version_supported, ) except ImportError: if current_platform.is_rocm(): pytest.skip( "vllm_flash_attn is not supported for vLLM on ROCm.", allow_module_level=True, ) NUM_HEADS = [(4, 4), (8, 2)] HEAD_SIZES = [40, 72, 80, 128, 256] BLOCK_SIZES = [16] DTYPES = [torch.bfloat16] QDTYPES = [None, torch.float8_e4m3fn] # one value large enough to test overflow in index calculation. # one value small enough to test the schema op check NUM_BLOCKS = [32768, 2048] SOFT_CAPS = [None] SLIDING_WINDOWS = [None, 256] def ref_paged_attn( query: torch.Tensor, key_cache: torch.Tensor, value_cache: torch.Tensor, query_lens: list[int], kv_lens: list[int], block_tables: torch.Tensor, scale: float, sliding_window: int | None = None, soft_cap: float | None = None, ) -> torch.Tensor: num_seqs = len(query_lens) block_tables = block_tables.cpu().numpy() _, block_size, num_kv_heads, head_size = key_cache.shape outputs: list[torch.Tensor] = [] start_idx = 0 for i in range(num_seqs): query_len = query_lens[i] kv_len = kv_lens[i] q = query[start_idx : start_idx + query_len] q *= scale num_kv_blocks = (kv_len + block_size - 1) // block_size block_indices = block_tables[i, :num_kv_blocks] k = key_cache[block_indices].view(-1, num_kv_heads, head_size) k = k[:kv_len] v = value_cache[block_indices].view(-1, num_kv_heads, head_size) v = v[:kv_len] if q.shape[1] != k.shape[1]: k = torch.repeat_interleave(k, q.shape[1] // k.shape[1], dim=1) v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1) attn = torch.einsum("qhd,khd->hqk", q, k).float() empty_mask = torch.ones(query_len, kv_len) mask = torch.triu(empty_mask, diagonal=kv_len - query_len + 1).bool() if sliding_window is not None: sliding_window_mask = ( torch.triu( empty_mask, diagonal=kv_len - (query_len + sliding_window) + 1 ) .bool() .logical_not() ) mask |= sliding_window_mask if soft_cap is not None: attn = soft_cap * torch.tanh(attn / soft_cap) attn.masked_fill_(mask, float("-inf")) attn = torch.softmax(attn, dim=-1).to(v.dtype) out = torch.einsum("hqk,khd->qhd", attn, v) outputs.append(out) start_idx += query_len return torch.cat(outputs, dim=0) @pytest.mark.parametrize("use_out", [True, False]) @pytest.mark.parametrize( "seq_lens", [[(1, 1328), (5, 18), (129, 463)], [(1, 523), (1, 37), (1, 2011)]] ) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("soft_cap", SOFT_CAPS) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("fa_version", [2, 3]) @pytest.mark.parametrize("q_dtype", QDTYPES) @torch.inference_mode() def test_varlen_with_paged_kv( use_out: bool, seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, fa_version: int, q_dtype: torch.dtype | None, ) -> None: torch.set_default_device("cuda") if not is_fa_version_supported(fa_version): pytest.skip( f"Flash attention version {fa_version} not supported due " f'to: "{fa_version_unsupported_reason(fa_version)}"' ) if q_dtype is not None and (dtype != torch.bfloat16 or fa_version == 2): pytest.skip( "Flash attention with quantized inputs is only " "supported on version 3 with bfloat16 base type" ) current_platform.seed_everything(0) num_seqs = len(seq_lens) query_lens = [x[0] for x in seq_lens] kv_lens = [x[1] for x in seq_lens] num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_query_len = max(query_lens) max_kv_len = max(kv_lens) window_size = (sliding_window - 1, 0) if sliding_window is not None else (-1, -1) scale = head_size**-0.5 query = torch.randn(sum(query_lens), num_query_heads, head_size, dtype=dtype) key_cache = torch.randn( num_blocks, block_size, num_kv_heads, head_size, dtype=dtype ) value_cache = torch.randn_like(key_cache) cu_query_lens = torch.tensor([0] + query_lens, dtype=torch.int32).cumsum( dim=0, dtype=torch.int32 ) kv_lens = torch.tensor(kv_lens, dtype=torch.int32) max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, num_blocks, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) out = torch.empty_like(query) if use_out else None maybe_quantized_query = query maybe_quantized_key_cache = key_cache maybe_quantized_value_cache = value_cache q_descale = None k_descale = None v_descale = None if q_dtype is not None: # QKV are drawn from N(0, 1): no need for a fp8 scaling factor maybe_quantized_query = query.to(q_dtype) maybe_quantized_key_cache = key_cache.to(q_dtype) maybe_quantized_value_cache = value_cache.to(q_dtype) scale_shape = (num_seqs, num_kv_heads) q_descale = torch.ones(scale_shape, dtype=torch.float32) k_descale = torch.ones(scale_shape, dtype=torch.float32) v_descale = torch.ones(scale_shape, dtype=torch.float32) output = flash_attn_varlen_func( q=maybe_quantized_query, k=maybe_quantized_key_cache, v=maybe_quantized_value_cache, out=out, cu_seqlens_q=cu_query_lens, seqused_k=kv_lens, max_seqlen_q=max_query_len, max_seqlen_k=max_kv_len, softmax_scale=scale, causal=True, window_size=window_size, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, fa_version=fa_version, q_descale=q_descale, k_descale=k_descale, v_descale=v_descale, ) output = output if not use_out else out ref_output = ref_paged_attn( query=query, key_cache=key_cache, value_cache=value_cache, query_lens=query_lens, kv_lens=kv_lens, block_tables=block_tables, scale=scale, sliding_window=sliding_window, soft_cap=soft_cap, ) atol, rtol = 1.5e-2, 1e-2 if q_dtype is not None: atol, rtol = 1.5e-1, 1.5e-1 ( torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol), f"{torch.max(torch.abs(output - ref_output))}", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_flashinfer_trtllm_attention.py
tests/kernels/attention/test_flashinfer_trtllm_attention.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from tests.kernels.quantization.nvfp4_utils import ( dequantize_nvfp4_to_dtype, get_nvfp4_global_scale, ) from vllm.platforms import current_platform from vllm.utils.math_utils import round_up if not current_platform.is_device_capability_family(100): pytest.skip( "This TRTLLM kernel requires NVIDIA Blackwell.", allow_module_level=True ) else: import flashinfer FLOAT32_BYTES = torch.finfo(torch.float).bits // 8 FP8_DTYPE = current_platform.fp8_dtype() FP4_DTYPE = torch.uint8 def to_float8(x, dtype=torch.float8_e4m3fn): finfo = torch.finfo(dtype) min_val, max_val = x.aminmax() amax = torch.maximum(min_val.abs(), max_val.abs()).clamp(min=1e-12) scale = finfo.max / amax * 0.1 x_scl_sat = (x * scale).clamp(min=finfo.min, max=finfo.max) return x_scl_sat.to(dtype), scale.float().reciprocal() DTYPE = [torch.bfloat16] QUANT_DTYPES = [ # (q_quant_dtype, kv_quant_dtype, o_quant_dtype) (None, None, None), (None, FP8_DTYPE, None), (FP8_DTYPE, FP8_DTYPE, None), (FP8_DTYPE, FP8_DTYPE, FP8_DTYPE), (FP8_DTYPE, FP8_DTYPE, FP4_DTYPE), ] BATCH_SIZE = [4, 12] MAX_SEQ_LENS = [(1024, 4096)] NUM_HEADS = [(64, 8), (40, 8)] HEAD_SIZE = [128] KV_LAYOUT = ["HND"] # currently only HND is supported BLOCK_SIZE = [16] WINDOW_LEFT = [-1, 127] SOFT_CAP = [None, 50.0] HAS_SINKS = [True, False] NUM_BLOCKS = 32768 # Large enough to test overflow in index calculation. @pytest.mark.parametrize("dtype", DTYPE) @pytest.mark.parametrize("quant_dtypes", QUANT_DTYPES) @pytest.mark.parametrize("batch_size", BATCH_SIZE) @pytest.mark.parametrize("max_seq_lens", MAX_SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZE) @pytest.mark.parametrize("kv_layout", KV_LAYOUT) @pytest.mark.parametrize("block_size", BLOCK_SIZE) @pytest.mark.parametrize("window_left", WINDOW_LEFT) @pytest.mark.parametrize("soft_cap", SOFT_CAP) @pytest.mark.parametrize("has_sinks", HAS_SINKS) @torch.inference_mode def test_flashinfer_trtllm_decode_with_baseline( dtype: torch.dtype, quant_dtypes: tuple[torch.dtype | None, torch.dtype | None, torch.dtype | None], batch_size: int, max_seq_lens: tuple[int, int], num_heads: tuple[int, int], head_size: int, kv_layout: str, block_size: int, window_left: int, soft_cap: float | None, has_sinks: bool, ) -> None: torch.set_default_device("cuda") current_platform.seed_everything(42) q_quant_dtype, kv_quant_dtype, o_quant_dtype = quant_dtypes q_quant_dtype = q_quant_dtype or dtype kv_quant_dtype = kv_quant_dtype or dtype o_quant_dtype = o_quant_dtype or dtype _, max_kv_len = max_seq_lens num_qo_heads, num_kv_heads = num_heads assert num_qo_heads % num_kv_heads == 0 sm_scale = float(1.0 / (head_size**0.5)) kv_cache_shape = None if kv_layout == "NHD": kv_cache_shape = (NUM_BLOCKS, 2, block_size, num_kv_heads, head_size) elif kv_layout == "HND": kv_cache_shape = (NUM_BLOCKS, 2, num_kv_heads, block_size, head_size) else: raise ValueError(f"Invalid kv_layout: {kv_layout}") # max_q_len = 1 q_lens = torch.ones((batch_size,), dtype=torch.int32) q_indptr = torch.cat( [ torch.tensor([0], dtype=torch.int32), torch.cumsum(q_lens, dim=0, dtype=torch.int32), ] ) query = torch.randn(torch.sum(q_lens).item(), num_qo_heads, head_size, dtype=dtype) if q_quant_dtype == FP8_DTYPE: query, q_scale = to_float8(query) ref_query = query.to(dtype) * q_scale else: q_scale = 1.0 ref_query = query kv_lens = torch.randint(1, max_kv_len, (batch_size,), dtype=torch.int32) kv_lens[-1] = max_kv_len seq_lens = kv_lens + q_lens max_seq_len = torch.max(seq_lens).item() kv_cache = torch.randn(kv_cache_shape, dtype=dtype) if kv_quant_dtype == FP8_DTYPE: kv_cache, kv_scale = to_float8(kv_cache) ref_kv_cache = kv_cache.to(dtype) * kv_scale else: kv_scale = 1.0 ref_kv_cache = kv_cache k_scale = v_scale = kv_scale max_num_blocks_per_seq = (max_seq_len + block_size - 1) // block_size block_tables = torch.randint( 0, NUM_BLOCKS, (batch_size, max_num_blocks_per_seq), dtype=torch.int32 ) kv_indptr = [0] kv_indices = [] kv_last_page_lens = [] for i in range(batch_size): seq_len = seq_lens[i] assert seq_len > 0 num_blocks = (seq_len + block_size - 1) // block_size kv_indices.extend(block_tables[i, :num_blocks]) kv_indptr.append(kv_indptr[-1] + num_blocks) kv_last_page_len = seq_len % block_size if kv_last_page_len == 0: kv_last_page_len = block_size kv_last_page_lens.append(kv_last_page_len) kv_indptr = torch.tensor(kv_indptr, dtype=torch.int32) kv_indices = torch.tensor(kv_indices, dtype=torch.int32) kv_last_page_lens = torch.tensor(kv_last_page_lens, dtype=torch.int32) workspace_buffer = torch.zeros(128 * 1024 * 1024, dtype=torch.int8) # Baseline Decode if has_sinks: sinks = torch.rand(num_qo_heads, dtype=torch.float32) * 5 wrapper = flashinfer.BatchAttentionWithAttentionSinkWrapper( float_workspace_buffer=workspace_buffer, kv_layout=kv_layout, backend="fa2" ) else: sinks = None wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper( float_workspace_buffer=workspace_buffer, kv_layout=kv_layout, backend="fa2" ) wrapper.plan( qo_indptr=q_indptr, paged_kv_indptr=kv_indptr, paged_kv_indices=kv_indices, paged_kv_last_page_len=kv_last_page_lens, num_qo_heads=num_qo_heads, num_kv_heads=num_kv_heads, head_dim_qk=head_size, page_size=block_size, causal=True, sm_scale=sm_scale, window_left=window_left, logits_soft_cap=soft_cap, q_data_type=dtype, kv_data_type=dtype, ) output = torch.empty(ref_query.shape, dtype=dtype) wrapper.run(ref_query, ref_kv_cache, sinks, sm_scale, out=output) o_scale = 1.0 o_sf_scale_float = None if o_quant_dtype == FP8_DTYPE: _, o_scale = to_float8(output) elif o_quant_dtype == FP4_DTYPE: o_sf_scale = get_nvfp4_global_scale(output) o_sf_scale_float = o_sf_scale.item() # TRTLLM Decode if o_quant_dtype == FP4_DTYPE: output_trtllm = flashinfer.utils.FP4Tensor( torch.empty(query.shape[:-1] + (query.shape[-1] // 2,), dtype=torch.uint8), torch.empty( ( round_up(query.shape[0], 128), round_up(query.shape[1] * query.shape[2] // 16, 4), ), dtype=torch.float8_e4m3fn, ), ) else: output_trtllm = torch.empty(query.shape, dtype=o_quant_dtype) flashinfer.decode.trtllm_batch_decode_with_kv_cache( query=query, kv_cache=kv_cache, workspace_buffer=workspace_buffer, block_tables=block_tables, seq_lens=seq_lens, max_seq_len=max_seq_len, bmm1_scale=q_scale * k_scale * sm_scale, bmm2_scale=v_scale / o_scale, window_left=window_left, sinks=sinks, o_sf_scale=o_sf_scale_float, out=output_trtllm, ) if o_quant_dtype == FP8_DTYPE: output_trtllm = output_trtllm.to(dtype) * o_scale elif o_quant_dtype == FP4_DTYPE: output_trtllm.data = output_trtllm.data.reshape( -1, query.shape[1] * query.shape[2] // 2 ) output_trtllm = dequantize_nvfp4_to_dtype( output_trtllm.data, output_trtllm.scale, o_sf_scale, dtype, query.device ) output_trtllm = output_trtllm.reshape(-1, query.shape[1], query.shape[2]) if q_quant_dtype == FP8_DTYPE and o_quant_dtype == FP4_DTYPE: rtol, atol = 7e-2, 9e-2 elif q_quant_dtype == FP8_DTYPE and o_quant_dtype == FP8_DTYPE: rtol, atol = 3e-2, 4e-2 elif q_quant_dtype == FP8_DTYPE and o_quant_dtype == dtype: rtol, atol = 2e-2, 2e-2 elif kv_quant_dtype == FP8_DTYPE: rtol, atol = 4e-2, 6e-2 else: rtol, atol = 1e-2, 1e-2 ( torch.testing.assert_close(output, output_trtllm, atol=atol, rtol=rtol), f"{torch.max(torch.abs(output - output_trtllm))}", ) @pytest.mark.parametrize("dtype", DTYPE) @pytest.mark.parametrize("quant_dtypes", QUANT_DTYPES) @pytest.mark.parametrize("batch_size", BATCH_SIZE) @pytest.mark.parametrize("max_seq_lens", MAX_SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZE) @pytest.mark.parametrize("kv_layout", KV_LAYOUT) @pytest.mark.parametrize("block_size", BLOCK_SIZE) @pytest.mark.parametrize("window_left", WINDOW_LEFT) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("has_sinks", HAS_SINKS) @torch.inference_mode def test_flashinfer_trtllm_prefill_with_baseline( dtype: torch.dtype, quant_dtypes: tuple[torch.dtype | None, torch.dtype | None, torch.dtype | None], batch_size: int, max_seq_lens: tuple[int, int], num_heads: tuple[int, int], head_size: int, kv_layout: str, block_size: int, window_left: int, soft_cap: float | None, has_sinks: bool, ) -> None: torch.set_default_device("cuda") current_platform.seed_everything(42) q_quant_dtype, kv_quant_dtype, o_quant_dtype = quant_dtypes q_quant_dtype = q_quant_dtype or dtype kv_quant_dtype = kv_quant_dtype or dtype o_quant_dtype = o_quant_dtype or dtype if q_quant_dtype != kv_quant_dtype: pytest.skip("Skipped mixed QKV dtypes for prefill") max_q_len, max_kv_len = max_seq_lens num_qo_heads, num_kv_heads = num_heads assert num_qo_heads % num_kv_heads == 0 sm_scale = float(1.0 / (head_size**0.5)) kv_cache_shape = None if kv_layout == "NHD": kv_cache_shape = (NUM_BLOCKS, 2, block_size, num_kv_heads, head_size) elif kv_layout == "HND": kv_cache_shape = (NUM_BLOCKS, 2, num_kv_heads, block_size, head_size) else: raise ValueError(f"Invalid kv_layout: {kv_layout}") q_lens = torch.randint(1, max_q_len, (batch_size,), dtype=torch.int32) q_lens[-1] = max_q_len q_indptr = torch.cat( [ torch.tensor([0], dtype=torch.int32), torch.cumsum(q_lens, dim=0, dtype=torch.int32), ] ) query = torch.randn(torch.sum(q_lens).item(), num_qo_heads, head_size, dtype=dtype) if q_quant_dtype == FP8_DTYPE: query, q_scale = to_float8(query) ref_query = query.to(dtype) * q_scale else: q_scale = 1.0 ref_query = query kv_lens = torch.randint(1, max_kv_len, (batch_size,), dtype=torch.int32) kv_lens[-1] = max_kv_len seq_lens = kv_lens + q_lens max_seq_len = torch.max(seq_lens).item() kv_cache = torch.randn(kv_cache_shape, dtype=dtype) if kv_quant_dtype == FP8_DTYPE: kv_cache, kv_scale = to_float8(kv_cache) ref_kv_cache = kv_cache.to(dtype) * kv_scale else: kv_scale = 1.0 ref_kv_cache = kv_cache k_scale = v_scale = kv_scale max_num_blocks_per_seq = (max_seq_len + block_size - 1) // block_size block_tables = torch.randint( 0, NUM_BLOCKS, (batch_size, max_num_blocks_per_seq), dtype=torch.int32 ) kv_indptr = [0] kv_indices = [] kv_last_page_lens = [] for i in range(batch_size): seq_len = seq_lens[i] assert seq_len > 0 num_blocks = (seq_len + block_size - 1) // block_size kv_indices.extend(block_tables[i, :num_blocks]) kv_indptr.append(kv_indptr[-1] + num_blocks) kv_last_page_len = seq_len % block_size if kv_last_page_len == 0: kv_last_page_len = block_size kv_last_page_lens.append(kv_last_page_len) kv_indptr = torch.tensor(kv_indptr, dtype=torch.int32) kv_indices = torch.tensor(kv_indices, dtype=torch.int32) kv_last_page_lens = torch.tensor(kv_last_page_lens, dtype=torch.int32) workspace_buffer = torch.zeros(128 * 1024 * 1024, dtype=torch.int8) # Baseline Prefill if has_sinks: sinks = torch.rand(num_qo_heads, dtype=torch.float32) * 5 wrapper = flashinfer.BatchAttentionWithAttentionSinkWrapper( float_workspace_buffer=workspace_buffer, kv_layout=kv_layout, backend="fa2" ) else: sinks = None wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper( float_workspace_buffer=workspace_buffer, kv_layout=kv_layout, backend="fa2" ) wrapper.plan( qo_indptr=q_indptr, paged_kv_indptr=kv_indptr, paged_kv_indices=kv_indices, paged_kv_last_page_len=kv_last_page_lens, num_qo_heads=num_qo_heads, num_kv_heads=num_kv_heads, head_dim_qk=head_size, page_size=block_size, causal=True, sm_scale=sm_scale, window_left=window_left, logits_soft_cap=soft_cap, q_data_type=dtype, kv_data_type=dtype, ) output = torch.empty(ref_query.shape, dtype=dtype) wrapper.run(ref_query, ref_kv_cache, sinks, sm_scale, out=output) o_scale = 1.0 o_sf_scale_float = None if o_quant_dtype == FP8_DTYPE: _, o_scale = to_float8(output) elif o_quant_dtype == FP4_DTYPE: o_sf_scale = get_nvfp4_global_scale(output) o_sf_scale_float = o_sf_scale.item() # TRTLLM Prefill if o_quant_dtype == FP4_DTYPE: output_trtllm = flashinfer.utils.FP4Tensor( torch.empty(query.shape[:-1] + (query.shape[-1] // 2,), dtype=torch.uint8), torch.empty( ( round_up(query.shape[0], 128), round_up(query.shape[1] * query.shape[2] // 16, 4), ), dtype=torch.float8_e4m3fn, ), ) else: output_trtllm = torch.empty(query.shape, dtype=o_quant_dtype) flashinfer.prefill.trtllm_batch_context_with_kv_cache( query=query, kv_cache=kv_cache, workspace_buffer=workspace_buffer, block_tables=block_tables, seq_lens=seq_lens, max_q_len=max_q_len, max_kv_len=max_seq_len, bmm1_scale=q_scale * k_scale * sm_scale, bmm2_scale=v_scale / o_scale, batch_size=batch_size, cum_seq_lens_q=q_indptr, cum_seq_lens_kv=kv_indptr, window_left=window_left, sinks=sinks, o_sf_scale=o_sf_scale_float, out=output_trtllm, ) if o_quant_dtype == FP8_DTYPE: output_trtllm = output_trtllm.to(dtype) * o_scale elif o_quant_dtype == FP4_DTYPE: output_trtllm.data = output_trtllm.data.reshape( -1, query.shape[1] * query.shape[2] // 2 ) output_trtllm = dequantize_nvfp4_to_dtype( output_trtllm.data, output_trtllm.scale, o_sf_scale, dtype, query.device ) output_trtllm = output_trtllm.reshape(-1, query.shape[1], query.shape[2]) if q_quant_dtype == FP8_DTYPE and o_quant_dtype == FP4_DTYPE: rtol, atol = 3e-1, 4e-1 elif q_quant_dtype == FP8_DTYPE and o_quant_dtype == FP8_DTYPE: rtol, atol = 4e-2, 6e-2 elif q_quant_dtype == FP8_DTYPE and o_quant_dtype == dtype: rtol, atol = 2e-2, 3e-2 else: rtol, atol = 1e-2, 1e-2 ( torch.testing.assert_close(output, output_trtllm, atol=atol, rtol=rtol), f"{torch.max(torch.abs(output - output_trtllm))}", ) def test_trtllm_attention_rejects_num_kv_heads_1() -> None: """Test that TRTLLM attention correctly rejects num_kv_heads=1. When num_kv_heads=1 (MQA), the KV cache strides become degenerate (stride_heads == stride_batch), which causes CUDA's cuTensorMapEncodeTiled to fail because TMA descriptors cannot handle degenerate 4D tensors with singleton dimensions. This test verifies that can_use_trtllm_attention returns False for num_kv_heads=1 configurations. """ from vllm.utils.flashinfer import can_use_trtllm_attention # num_kv_heads=1 should be rejected assert not can_use_trtllm_attention(num_qo_heads=64, num_kv_heads=1), ( "can_use_trtllm_attention should return False for num_kv_heads=1" ) assert not can_use_trtllm_attention(num_qo_heads=32, num_kv_heads=1), ( "can_use_trtllm_attention should return False for num_kv_heads=1" ) # num_kv_heads > 1 should be accepted (if platform supports it) # Note: This may return False on non-Blackwell platforms, which is fine result_kv8 = can_use_trtllm_attention(num_qo_heads=64, num_kv_heads=8) result_kv1 = can_use_trtllm_attention(num_qo_heads=64, num_kv_heads=1) # Even if platform doesn't support TRTLLM, num_kv_heads=1 should never # return True when num_kv_heads > 1 returns True if result_kv8: assert not result_kv1, ( "If TRTLLM is supported for num_kv_heads=8, " "it must be rejected for num_kv_heads=1" )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_cutlass_mla_decode.py
tests/kernels/attention/test_cutlass_mla_decode.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import math import random import pytest import torch import vllm._custom_ops as ops from vllm.platforms import current_platform from vllm.triton_utils import triton def cal_diff( x: torch.Tensor, y: torch.Tensor, name: str, use_fp8: bool = False, diff_threshold: float | None = None, ) -> None: x, y = x.double(), y.double() cos_diff = 1 - 2 * (x * y).sum().item() / max((x * x + y * y).sum().item(), 1e-12) if diff_threshold is not None: # directly compare the cos_diff with the threshold assert cos_diff < diff_threshold else: # use the default threshold if use_fp8: assert cos_diff < 1e-4 else: assert cos_diff < 1e-5 CUTLASS_MLA_UNSUPPORTED_REASON = ( "Cutlass MLA Requires compute capability of 100 or above." if not current_platform.is_device_capability_family(100) else "Cutlass MLA is supported" ) @pytest.mark.skipif( not current_platform.has_device_capability(100), reason=CUTLASS_MLA_UNSUPPORTED_REASON, ) @pytest.mark.parametrize("b", [128]) @pytest.mark.parametrize("s_q", [1]) @pytest.mark.parametrize("mean_sk", [4096, 8192, 16384]) @pytest.mark.parametrize("h_q", [16, 32, 64, 128]) @pytest.mark.parametrize("h_kv", [1]) @pytest.mark.parametrize("d", [576]) @pytest.mark.parametrize("dv", [512]) @pytest.mark.parametrize("block_size", [64]) @pytest.mark.parametrize("causal", [True]) @pytest.mark.parametrize("varlen", [False, True]) @pytest.mark.parametrize( "torch_dtype", [ torch.bfloat16, # fp8 can have occasional precision-related failures. pytest.param(torch.float8_e4m3fn, marks=pytest.mark.flaky(reruns=2)), ], ) @torch.inference_mode() def test_cutlass_mla_decode( b, s_q, mean_sk, h_q, h_kv, d, dv, block_size, causal, varlen, torch_dtype ): device = torch.device("cuda:0") init_dtype = torch.bfloat16 if torch_dtype == torch.float8_e4m3fn else torch_dtype torch.set_default_dtype(init_dtype) torch.set_default_device(device) torch.cuda.set_device(device) torch.manual_seed(42) random.seed(42) print( f"{b=}, {s_q=}, {mean_sk=}, {h_q=}, {h_kv=}, " f"{d=}, {dv=}, {causal=}, {varlen=}, {torch_dtype=}" ) use_fp8 = torch_dtype == torch.float8_e4m3fn scale = math.sqrt(d) ** (-1) cache_seqlens = torch.full((b,), mean_sk, dtype=torch.int32) if varlen: for i in range(b): cache_seqlens[i] = max(random.normalvariate(mean_sk, mean_sk / 2), s_q) total_seqlens = cache_seqlens.sum().item() max_seqlen = cache_seqlens.max().item() max_seqlen_pad = triton.cdiv(max_seqlen, 256) * 256 q = torch.randn(b, s_q, h_q, d) block_table = torch.arange( b * max_seqlen_pad // block_size, dtype=torch.int32 ).view(b, max_seqlen_pad // block_size) blocked_k = torch.randn(block_table.numel(), block_size, h_kv, d) blocked_v = blocked_k[..., :dv] init_dtype = q.dtype if use_fp8: fp8_dtype = torch.float8_e4m3fn descale_q = torch.ones((1), dtype=torch.float32) descale_k = torch.ones((1), dtype=torch.float32) q = q.to(fp8_dtype) blocked_k = blocked_k.to(fp8_dtype) blocked_v = blocked_v.to(fp8_dtype) else: descale_q = None descale_k = None def cutlass_mla(): MAX_HEADS = 128 q_reshaped = q.squeeze(1) q_nope = q_reshaped[:, :, :dv].clone() q_pe = q_reshaped[:, :, dv:].clone() if h_q < MAX_HEADS: q_nope_padded = q_nope.new_empty((b, MAX_HEADS, dv)) q_nope_padded[:, :h_q] = q_nope q_nope = q_nope_padded q_pe_padded = q_pe.new_empty((b, MAX_HEADS, d - dv)) q_pe_padded[:, :h_q] = q_pe q_pe = q_pe_padded kv_cache_flat = blocked_k.squeeze(2) device_properties = torch.cuda.get_device_properties(torch.device("cuda:0")) sm_count = device_properties.multi_processor_count workspace_size = ops.sm100_cutlass_mla_get_workspace_size( max_seqlen * block_size, b, sm_count, num_kv_splits=1 ) workspace = torch.empty(workspace_size, device="cuda", dtype=torch.uint8) out_ans = torch.empty(b, MAX_HEADS, dv, dtype=init_dtype) output_lse = torch.empty( (b, MAX_HEADS), dtype=torch.float32, device=q_nope.device ) ops.sm100_cutlass_mla_decode( out_ans, output_lse, q_nope, q_pe, kv_cache_flat, cache_seqlens, block_table, workspace, scale, 1, ) return out_ans[:, :h_q].contiguous(), output_lse[:, :h_q].contiguous() def scaled_dot_product_attention(query, key, value, is_causal=False): query = query.float() key = key.float() value = value.float() key = key.repeat_interleave(h_q // h_kv, dim=0) value = value.repeat_interleave(h_q // h_kv, dim=0) attn_weight = query @ key.transpose(-2, -1) / math.sqrt(query.size(-1)) if is_causal: s_q = query.shape[-2] s_k = key.shape[-2] attn_bias = torch.zeros(s_q, s_k, dtype=query.dtype) temp_mask = torch.ones(s_q, s_k, dtype=torch.bool).tril(diagonal=s_k - s_q) attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf")) attn_bias.to(query.dtype) attn_weight += attn_bias lse = attn_weight.logsumexp(dim=-1) attn_weight = torch.softmax(attn_weight, dim=-1, dtype=torch.float32) return attn_weight @ value, lse def ref_mla(): q_ = (q.to(torch.float) * descale_q).to(init_dtype) if use_fp8 else q blocked_k_ = ( (blocked_k.to(torch.float) * descale_k).to(init_dtype) if use_fp8 else blocked_k ) blocked_v_ = ( (blocked_v.to(torch.float) * descale_k).to(init_dtype) if use_fp8 else blocked_v ) out = torch.empty(b, s_q, h_q, dv, dtype=torch.float32) lse = torch.empty(b, h_q, s_q, dtype=torch.float32) for i in range(b): begin = i * max_seqlen_pad end = begin + cache_seqlens[i] out_i, lse_i = scaled_dot_product_attention( q_[i].transpose(0, 1), blocked_k_.view(-1, h_kv, d)[begin:end].transpose(0, 1), blocked_v_.view(-1, h_kv, dv)[begin:end].transpose(0, 1), is_causal=causal, ) out[i] = out_i.transpose(0, 1) lse[i] = lse_i return out, lse out_cutlass, lse_cutlass = cutlass_mla() out_torch, lse_torch = ref_mla() # Extract the single token (s_q=1) slice to match cutlass output shape out_torch_slice = out_torch[:, 0, :, :] # [b, h_q, dv] lse_torch_slice = lse_torch[:, 0, :] # [b, h_q] cal_diff(out_cutlass, out_torch_slice, "out", use_fp8) # lse has larger numerical error, so use a larger threshold cal_diff(lse_cutlass, lse_torch_slice, "lse", use_fp8, diff_threshold=1e-3) t = triton.testing.do_bench(cutlass_mla) FLOPS = s_q * total_seqlens * h_q * (d + dv) * 2 bytes = (total_seqlens * h_kv * d + b * s_q * h_q * d) * ( torch.finfo(torch_dtype).bits // 8 ) + (b * s_q * h_q * dv) * (torch.finfo(init_dtype).bits // 8) print( f"{t:.3f} ms, {FLOPS / 10**9 / t:.0f} TFLOPS,", f"{bytes / 10**6 / t:.0f} GB/s" )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_cascade_flash_attn.py
tests/kernels/attention/test_cascade_flash_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.platforms import current_platform from vllm.v1.attention.backends.flash_attn import cascade_attention, merge_attn_states try: from vllm.vllm_flash_attn import ( fa_version_unsupported_reason, flash_attn_varlen_func, is_fa_version_supported, ) except ImportError: if current_platform.is_rocm(): pytest.skip( "vllm_flash_attn is not supported for vLLM on ROCm.", allow_module_level=True, ) NUM_HEADS = [(4, 4), (8, 2), (16, 2)] HEAD_SIZES = [128, 192, 256] BLOCK_SIZES = [16] DTYPES = [torch.float16, torch.bfloat16] @pytest.mark.parametrize("num_tokens", [1, 39, 16912]) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @torch.inference_mode() def test_merge_kernel( num_tokens: int, num_heads: tuple[int, int], head_size: int, dtype: torch.dtype, ): torch.set_default_device("cuda") current_platform.seed_everything(0) num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 # Prepare inputs. prefix_output = torch.randn(num_tokens, num_query_heads, head_size, dtype=dtype) suffix_output = torch.randn(num_tokens, num_query_heads, head_size, dtype=dtype) prefix_lse = torch.randn(num_query_heads, num_tokens, dtype=torch.float32) suffix_lse = torch.randn(num_query_heads, num_tokens, dtype=torch.float32) # Run the kernel. output = torch.empty(num_tokens, num_query_heads, head_size, dtype=dtype) merge_attn_states(output, prefix_output, prefix_lse, suffix_output, suffix_lse) # Reference implementation. max_lse = torch.maximum(prefix_lse, suffix_lse) p_lse = torch.exp(prefix_lse - max_lse) s_lse = torch.exp(suffix_lse - max_lse) p_scale = p_lse / (p_lse + s_lse) s_scale = s_lse / (p_lse + s_lse) p_scale = p_scale.transpose(0, 1).unsqueeze(2) s_scale = s_scale.transpose(0, 1).unsqueeze(2) ref_output = p_scale * prefix_output + s_scale * suffix_output ref_output = ref_output.to(dtype) # Compare the results. torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=1e-2) CASES = [ # Case 1. A general case. ([(129, 871), (18, 280), (37, 988), (1023, 2304), (1, 257)], 256), # Case 2. Flash-decoding case. ([(1, 1023), (1, 879), (1, 778), (1, 1777)] * 100, 512), ] @pytest.mark.parametrize("seq_lens_and_common_prefix", CASES) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("soft_cap", [None, 50]) @pytest.mark.parametrize("num_blocks", [2048]) @pytest.mark.parametrize("fa_version", [2, 3]) @torch.inference_mode() def test_cascade( seq_lens_and_common_prefix: tuple[list[tuple[int, int]], int], num_heads: tuple[int, int], head_size: int, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, fa_version: int, ) -> None: torch.set_default_device("cuda") if not is_fa_version_supported(fa_version): pytest.skip( f"Flash attention version {fa_version} not supported due " f'to: "{fa_version_unsupported_reason(fa_version)}"' ) current_platform.seed_everything(0) window_size = (-1, -1) scale = head_size**-0.5 num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 key_cache = torch.randn( num_blocks, block_size, num_kv_heads, head_size, dtype=dtype ) value_cache = torch.randn_like(key_cache) seq_lens, common_prefix_len = seq_lens_and_common_prefix num_seqs = len(seq_lens) query_lens = [x[0] for x in seq_lens] kv_lens = [x[1] for x in seq_lens] max_query_len = max(query_lens) max_kv_len = max(kv_lens) total_num_query_tokens = sum(query_lens) query = torch.randn(total_num_query_tokens, num_query_heads, head_size, dtype=dtype) cu_query_lens = torch.tensor([0] + query_lens, dtype=torch.int32).cumsum( dim=0, dtype=torch.int32 ) kv_lens_tensor = torch.tensor(kv_lens, dtype=torch.int32) max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, num_blocks, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) assert common_prefix_len > 0 assert common_prefix_len % block_size == 0 num_common_kv_blocks = common_prefix_len // block_size # Make sure the first `num_common_kv_blocks` blocks are the same. block_tables[:, :num_common_kv_blocks] = block_tables[0, :num_common_kv_blocks] # Run the regular attention. ref_output = flash_attn_varlen_func( q=query, k=key_cache, v=value_cache, cu_seqlens_q=cu_query_lens, seqused_k=kv_lens_tensor, max_seqlen_q=max_query_len, max_seqlen_k=max_kv_len, softmax_scale=scale, causal=True, window_size=window_size, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, ) # Run cascade attention. assert all(common_prefix_len < kv_len for kv_len in kv_lens) cu_prefix_query_lens = torch.tensor([0, total_num_query_tokens], dtype=torch.int32) prefix_kv_lens = torch.tensor([common_prefix_len], dtype=torch.int32) suffix_kv_lens = kv_lens_tensor - common_prefix_len output = torch.empty_like(query) cascade_attention( output=output, query=query, key_cache=key_cache, value_cache=value_cache, cu_query_lens=cu_query_lens, max_query_len=max_query_len, cu_prefix_query_lens=cu_prefix_query_lens, prefix_kv_lens=prefix_kv_lens, suffix_kv_lens=suffix_kv_lens, max_kv_len=max_kv_len, softmax_scale=scale, alibi_slopes=None, sliding_window=window_size, logits_soft_cap=soft_cap if soft_cap is not None else 0, block_table=block_tables, common_prefix_len=common_prefix_len, max_num_splits=0, # no max fa_version=fa_version, ) # Compare the results. torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=1e-2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_cache.py
tests/kernels/attention/test_cache.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import random import pytest import torch from tests.kernels.utils import DEFAULT_OPCHECK_TEST_UTILS, opcheck from vllm import _custom_ops as ops from vllm.platforms import current_platform COPYING_DIRECTION = [("cuda", "cpu"), ("cuda", "cuda"), ("cpu", "cuda")] DTYPES = [torch.bfloat16, torch.float] NUM_TOKENS = [42] # Arbitrary values for testing NUM_LAYERS = [1] # Arbitrary values for testing NUM_HEADS = [8] # Arbitrary values for testing HEAD_SIZES = [64, 80, 256] BLOCK_SIZES = [8, 16, 32] CACHE_LAYOUTS = ["NHD", "HND"] # Parameters for MLA tests. KV_LORA_RANKS = [512] QK_ROPE_HEAD_DIMS = [64] NUM_TOKENS_MLA = [42] BLOCK_SIZES_MLA = [16] NUM_BLOCKS_MLA = [8] # Arbitrary values for testing # don't make it too large. e.g. [1024, 36000] will OOM NUM_BLOCKS = [1024, 10000] NUM_MAPPINGS = [256] # Arbitrary values for testing SEEDS = [0] CUDA_DEVICES = [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)] # We assume fp8 is always enabled for testing. KV_CACHE_DTYPE = ["auto", "fp8"] RESHAPE_FLASH_IMPLEMENTATIONS = ["cuda", "triton"] @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE) @torch.inference_mode() def test_reshape_and_cache( kv_cache_factory, num_tokens: int, num_heads: int, head_size: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, device: str, kv_cache_dtype: str, ) -> None: if kv_cache_dtype == "fp8" and head_size % 16: pytest.skip() current_platform.seed_everything(seed) torch.set_default_device(device) torch.cuda.set_device(device) # Create a random slot mapping. num_slots = block_size * num_blocks slot_mapping_lst = random.sample(range(num_slots), num_tokens) slot_mapping = torch.tensor(slot_mapping_lst, dtype=torch.long) qkv = torch.randn(num_tokens, 3, num_heads, head_size, dtype=dtype) _, key, value = qkv.unbind(dim=1) # Create the KV caches. key_caches, value_caches = kv_cache_factory( num_blocks, block_size, 1, num_heads, head_size, kv_cache_dtype, dtype, seed, device, ) key_cache, value_cache = key_caches[0], value_caches[0] # Using default kv_scale k_scale = (key.amax() / 64.0).to(torch.float32) v_scale = (value.amax() / 64.0).to(torch.float32) # Clone the KV caches. if kv_cache_dtype == "fp8": cloned_key_cache = torch.empty_like(key_cache, dtype=torch.float16) ops.convert_fp8(cloned_key_cache, key_cache, k_scale.item()) cloned_value_cache = torch.empty_like(value_cache, dtype=torch.float16) ops.convert_fp8(cloned_value_cache, value_cache, v_scale.item()) else: cloned_key_cache = key_cache.clone() cloned_value_cache = value_cache.clone() # Call the reshape_and_cache kernel. opcheck( torch.ops._C_cache_ops.reshape_and_cache, ( key, value, key_cache, value_cache, slot_mapping, kv_cache_dtype, k_scale, v_scale, ), cond=(head_size == HEAD_SIZES[0]), ) ops.reshape_and_cache( key, value, key_cache, value_cache, slot_mapping, kv_cache_dtype, k_scale, v_scale, ) if kv_cache_dtype == "fp8": result_key_cache = torch.empty_like(key_cache, dtype=torch.float16) ops.convert_fp8(result_key_cache, key_cache, k_scale.item()) result_value_cache = torch.empty_like(value_cache, dtype=torch.float16) ops.convert_fp8(result_value_cache, value_cache, v_scale.item()) # Run the reference implementation. reshaped_key = key.reshape(num_tokens, *key_cache[0, :, :, 0, :].shape) block_indices = torch.div(slot_mapping, block_size, rounding_mode="floor") block_indices_lst = block_indices.cpu().tolist() block_offsets = slot_mapping % block_size block_offsets_lst = block_offsets.cpu().tolist() for i in range(num_tokens): block_idx = block_indices_lst[i] block_offset = block_offsets_lst[i] cloned_key_cache[block_idx, :, :, block_offset, :] = reshaped_key[i] cloned_value_cache[block_idx, :, :, block_offset] = value[i] if kv_cache_dtype == "fp8": torch.testing.assert_close( result_key_cache, cloned_key_cache, atol=0.001, rtol=0.1 ) torch.testing.assert_close( result_value_cache, cloned_value_cache, atol=0.001, rtol=0.1 ) else: torch.testing.assert_close(key_cache, cloned_key_cache) torch.testing.assert_close(value_cache, cloned_value_cache) @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE) @pytest.mark.parametrize("kv_cache_layout", CACHE_LAYOUTS) @pytest.mark.parametrize("implementation", RESHAPE_FLASH_IMPLEMENTATIONS) @torch.inference_mode() def test_reshape_and_cache_flash( kv_cache_factory_flashinfer, num_tokens: int, num_heads: int, head_size: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, device: str, kv_cache_dtype: str, kv_cache_layout: str, implementation: str, ) -> None: current_platform.seed_everything(seed) torch.set_default_device(device) torch.cuda.set_device(device) assert implementation in ["cuda", "triton"] if implementation == "triton" and kv_cache_layout == "HND": pytest.skip("Triton implementation only supports NHD layout.") # fp8 conversion requires continugous memory buffer. Reduce the number of # blocks and tokens to consume less memory. num_tokens = num_tokens // 2 num_blocks = num_blocks // 2 # Create a random slot mapping. num_slots = block_size * num_blocks slot_mapping_lst = random.sample(range(num_slots), num_tokens) slot_mapping = torch.tensor(slot_mapping_lst, dtype=torch.long, device=device) qkv = torch.randn(num_tokens, 3, num_heads, head_size, dtype=dtype, device=device) _, key, value = qkv.unbind(dim=1) # Create the KV caches. key_caches, value_caches = kv_cache_factory_flashinfer( num_blocks, block_size, 1, num_heads, head_size, kv_cache_dtype, dtype, device=device, cache_layout=kv_cache_layout, ) key_cache, value_cache = key_caches[0], value_caches[0] del key_caches del value_caches k_scale = (key.amax() / 64.0).to(torch.float32) v_scale = (value.amax() / 64.0).to(torch.float32) def permute_and_compact(x): y = x if kv_cache_layout == "NHD" else x.permute(0, 2, 1, 3) return y.contiguous() key_cache_compact = permute_and_compact(key_cache) value_cache_compact = permute_and_compact(value_cache) # Clone the KV caches. if kv_cache_dtype == "fp8": cloned_key_cache = torch.empty_like(key_cache_compact, dtype=torch.float16) ops.convert_fp8( cloned_key_cache, key_cache_compact, k_scale.item(), kv_cache_dtype ) cloned_value_cache = torch.empty_like(value_cache_compact, dtype=torch.float16) ops.convert_fp8( cloned_value_cache, value_cache_compact, v_scale.item(), kv_cache_dtype ) else: cloned_key_cache = key_cache_compact.clone() cloned_value_cache = value_cache_compact.clone() # Call the reshape_and_cache kernel. if implementation == "cuda": opcheck( torch.ops._C_cache_ops.reshape_and_cache_flash, ( key, value, key_cache, value_cache, slot_mapping, kv_cache_dtype, k_scale, v_scale, ), cond=(head_size == HEAD_SIZES[0]), ) ops.reshape_and_cache_flash( key, value, key_cache, value_cache, slot_mapping, kv_cache_dtype, k_scale, v_scale, ) elif implementation == "triton": from vllm.attention.ops.triton_reshape_and_cache_flash import ( triton_reshape_and_cache_flash, ) triton_reshape_and_cache_flash( key, value, key_cache, value_cache, slot_mapping, kv_cache_dtype, k_scale, v_scale, ) key_cache_compact = permute_and_compact(key_cache) value_cache_compact = permute_and_compact(value_cache) if kv_cache_dtype == "fp8": result_key_cache = torch.empty_like(key_cache_compact, dtype=torch.float16) ops.convert_fp8( result_key_cache, key_cache_compact, k_scale.item(), kv_dtype=kv_cache_dtype ) result_value_cache = torch.empty_like(value_cache_compact, dtype=torch.float16) ops.convert_fp8( result_value_cache, value_cache_compact, v_scale.item(), kv_dtype=kv_cache_dtype, ) # Run the reference implementation. block_indices = torch.div(slot_mapping, block_size, rounding_mode="floor") block_indices_lst = block_indices.cpu().tolist() block_offsets = slot_mapping % block_size block_offsets_lst = block_offsets.cpu().tolist() for i in range(num_tokens): block_idx = block_indices_lst[i] block_offset = block_offsets_lst[i] if kv_cache_layout == "NHD": cloned_key_cache[block_idx, block_offset, :, :] = key[i] cloned_value_cache[block_idx, block_offset, :, :] = value[i] else: cloned_key_cache[block_idx, :, block_offset, :] = key[i] cloned_value_cache[block_idx, :, block_offset, :] = value[i] if kv_cache_dtype == "fp8": torch.testing.assert_close( result_key_cache, cloned_key_cache, atol=0.001, rtol=0.1 ) torch.testing.assert_close( result_value_cache, cloned_value_cache, atol=0.001, rtol=0.1 ) else: torch.testing.assert_close(key_cache_compact, cloned_key_cache) torch.testing.assert_close(value_cache_compact, cloned_value_cache) @pytest.mark.parametrize("direction", COPYING_DIRECTION) @pytest.mark.parametrize("num_mappings", NUM_MAPPINGS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE) @torch.inference_mode() def test_swap_blocks( kv_cache_factory, direction: tuple[str, str], num_mappings: int, num_heads: int, head_size: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, device: str, kv_cache_dtype: str, ) -> None: if kv_cache_dtype == "fp8" and "cpu" in direction: pytest.skip() if kv_cache_dtype == "fp8" and head_size % 16: pytest.skip() current_platform.seed_everything(seed) src_device = device if direction[0] == "cuda" else "cpu" dst_device = device if direction[1] == "cuda" else "cpu" src_blocks = random.sample(range(num_blocks), num_mappings) # For the same device, mapping must not overlap if src_device == dst_device: remaining_blocks = list(set(range(num_blocks)) - set(src_blocks)) dst_blocks = random.sample(remaining_blocks, num_mappings) else: dst_blocks = random.sample(range(num_blocks), num_mappings) block_mapping = list(zip(src_blocks, dst_blocks)) block_mapping_tensor = torch.tensor( block_mapping, dtype=torch.int64, device="cpu" ).view(-1, 2) # Create the KV caches on the first device. src_key_caches, src_value_caches = kv_cache_factory( num_blocks, block_size, 1, num_heads, head_size, kv_cache_dtype, dtype, seed, src_device, ) # Create the KV caches on the second device. dist_key_caches, dist_value_caches = kv_cache_factory( num_blocks, block_size, 1, num_heads, head_size, kv_cache_dtype, dtype, seed, dst_device, ) src_key_caches_clone = src_key_caches[0].clone() src_value_caches_clone = src_value_caches[0].clone() # Call the swap_blocks kernel. do_opcheck = head_size == HEAD_SIZES[0] opcheck( torch.ops._C_cache_ops.swap_blocks, (src_key_caches[0], dist_key_caches[0], block_mapping_tensor), cond=do_opcheck, ) opcheck( torch.ops._C_cache_ops.swap_blocks, (src_value_caches[0], dist_value_caches[0], block_mapping_tensor), cond=do_opcheck, ) ops.swap_blocks(src_key_caches[0], dist_key_caches[0], block_mapping_tensor) ops.swap_blocks(src_value_caches[0], dist_value_caches[0], block_mapping_tensor) for src, dst in block_mapping: torch.testing.assert_close( src_key_caches_clone[src].cpu(), dist_key_caches[0][dst].cpu() ) torch.testing.assert_close( src_value_caches_clone[src].cpu(), dist_value_caches[0][dst].cpu() ) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @torch.inference_mode() def test_fp8_e4m3_conversion( num_heads: int, head_size: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, device: str, ) -> None: current_platform.seed_everything(seed) low = -224.0 high = 224.0 shape = (num_blocks, num_heads, head_size, block_size) cache = torch.empty(shape, dtype=dtype, device=device) cache.uniform_(low, high) cache_fp8 = torch.empty_like(cache, dtype=torch.uint8) ops.convert_fp8(cache_fp8, cache) converted_cache = torch.empty_like(cache) ops.convert_fp8(converted_cache, cache_fp8) torch.testing.assert_close(cache, converted_cache, atol=0.001, rtol=0.1) def _create_mla_cache( num_blocks: int, block_size: int, entry_size: int, dtype: torch.dtype, kv_cache_dtype: str, device: str, ) -> torch.Tensor: cache_dtype = torch.uint8 if kv_cache_dtype == "fp8" else dtype return torch.zeros( num_blocks, block_size, entry_size, dtype=cache_dtype, device=device ) def _fill_mla_cache(cache: torch.Tensor, kv_cache_dtype: str): rand_dtype = torch.float16 if kv_cache_dtype == "fp8" else cache.dtype vals = torch.randn(*cache.shape, device=cache.device, dtype=rand_dtype) if kv_cache_dtype == "fp8": temp = torch.zeros_like(cache) ops.convert_fp8(temp, vals, 1.0, kv_dtype=kv_cache_dtype) vals = temp cache.copy_(vals) @pytest.mark.parametrize("kv_lora_rank", KV_LORA_RANKS) @pytest.mark.parametrize("qk_rope_head_dim", QK_ROPE_HEAD_DIMS) @pytest.mark.parametrize("num_tokens", NUM_TOKENS_MLA) @pytest.mark.parametrize("block_size", BLOCK_SIZES_MLA) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS_MLA) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE) @torch.inference_mode() def test_concat_and_cache_mla( kv_lora_rank: int, qk_rope_head_dim: int, num_tokens: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, device: str, kv_cache_dtype: str, ) -> None: current_platform.seed_everything(seed) torch.set_default_device(device) torch.cuda.set_device(device) total_slots = num_blocks * block_size slot_mapping_lst = random.sample(range(total_slots), num_tokens) slot_mapping = torch.tensor(slot_mapping_lst, dtype=torch.long, device=device) kv_c = torch.randn(num_tokens, kv_lora_rank, dtype=dtype, device=device) k_pe = torch.randn(num_tokens, qk_rope_head_dim, dtype=dtype, device=device) entry_size = kv_lora_rank + qk_rope_head_dim scale = torch.tensor(0.1, dtype=torch.float32, device=device) kv_cache = _create_mla_cache( num_blocks, block_size, entry_size, dtype, kv_cache_dtype, device ) ref_temp = torch.zeros(*kv_cache.shape, dtype=dtype, device=device) for i in range(num_tokens): slot = slot_mapping[i].item() block_idx = slot // block_size block_offset = slot % block_size ref_temp[block_idx, block_offset, :kv_lora_rank] = kv_c[i] ref_temp[block_idx, block_offset, kv_lora_rank:] = k_pe[i] if kv_cache_dtype == "fp8": ref_kv_cache = torch.empty_like(ref_temp, dtype=kv_cache.dtype) ops.convert_fp8(ref_kv_cache, ref_temp, scale.item(), kv_dtype=kv_cache_dtype) else: ref_kv_cache = ref_temp opcheck( torch.ops._C_cache_ops.concat_and_cache_mla, (kv_c, k_pe, kv_cache, slot_mapping, kv_cache_dtype, scale), test_utils=DEFAULT_OPCHECK_TEST_UTILS, ) ops.concat_and_cache_mla(kv_c, k_pe, kv_cache, slot_mapping, kv_cache_dtype, scale) if kv_cache_dtype == "fp8": result_temp = torch.empty_like(kv_cache, dtype=torch.float16) ops.convert_fp8( result_temp, kv_cache.contiguous(), scale.item(), kv_dtype=kv_cache_dtype ) expected_temp = torch.empty_like(ref_kv_cache, dtype=torch.float16) ops.convert_fp8( expected_temp, ref_kv_cache, scale.item(), kv_dtype=kv_cache_dtype ) torch.testing.assert_close(result_temp, expected_temp, atol=0.001, rtol=0.1) else: torch.testing.assert_close(kv_cache, ref_kv_cache) @pytest.mark.parametrize("kv_lora_rank", KV_LORA_RANKS) @pytest.mark.parametrize("qk_rope_head_dim", QK_ROPE_HEAD_DIMS) @pytest.mark.parametrize("num_tokens", NUM_TOKENS_MLA) @pytest.mark.parametrize("block_size", BLOCK_SIZES_MLA) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS_MLA) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @torch.inference_mode() def test_concat_and_cache_ds_mla( kv_lora_rank: int, qk_rope_head_dim: int, num_tokens: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, device: str, ) -> None: if current_platform.is_rocm(): pytest.skip("concat_and_cache_mla doesn't support fp8_ds_mla on ROCm") if dtype.itemsize != 2: pytest.skip("ds_mla only supports 16-bit input") kv_cache_dtype = "fp8_ds_mla" current_platform.seed_everything(seed) torch.set_default_device(device) torch.cuda.set_device(device) total_slots = num_blocks * block_size slot_mapping_lst = random.sample(range(total_slots), num_tokens) slot_mapping = torch.tensor(slot_mapping_lst, dtype=torch.long, device=device) kv_c = torch.randn(num_tokens, kv_lora_rank, dtype=dtype, device=device) k_pe = torch.randn(num_tokens, qk_rope_head_dim, dtype=dtype, device=device) entry_size = kv_lora_rank + (4 * 4) + (2 * qk_rope_head_dim) scale = torch.tensor(1.0, dtype=torch.float32, device=device) kv_cache = _create_mla_cache( num_blocks, block_size, entry_size, dtype=torch.uint8, kv_cache_dtype=kv_cache_dtype, device=device, ) ref_cache = torch.zeros_like(kv_cache, dtype=kv_cache.dtype) tile_data = torch.zeros(128, dtype=dtype, device=device) for i in range(num_tokens): slot = slot_mapping[i].item() block_idx = slot // block_size block_offset = slot % block_size ref_cache_slice = ref_cache[block_idx, block_offset] ref_cache_16bit = ref_cache_slice.view(dtype) ref_cache_32bit = ref_cache_slice.view(torch.float32) kv_c_data = kv_c[i] for tile_idx in range(4): tile_start = tile_idx * 128 tile_end = (tile_idx + 1) * 128 tile_data[:] = kv_c_data[tile_start:tile_end] # tile_scale = tile_data.amax().to(torch.float32) / 448. # NOTE: Using torch's amax() gives different results, # so this must be manually computed. tile_data_float = tile_data.to(torch.float32) manual_max = abs(tile_data_float[0]) for j in range(1, 128): manual_max = max(manual_max, abs(tile_data_float[j])) tile_scale = manual_max / 448.0 ref_cache_32bit[kv_lora_rank // 4 + tile_idx] = tile_scale ops.convert_fp8( ref_cache_slice[tile_start:tile_end], tile_data, tile_scale.item(), kv_dtype="fp8", ) for j in range(qk_rope_head_dim): ref_cache_16bit[kv_lora_rank // 2 + 8 + j] = k_pe[i, j] opcheck( torch.ops._C_cache_ops.concat_and_cache_mla, (kv_c, k_pe, kv_cache, slot_mapping, kv_cache_dtype, scale), test_utils=DEFAULT_OPCHECK_TEST_UTILS, ) ops.concat_and_cache_mla(kv_c, k_pe, kv_cache, slot_mapping, kv_cache_dtype, scale) for i in range(num_tokens): slot = slot_mapping[i].item() block_idx = slot // block_size block_offset = slot % block_size kv_cache_slice = kv_cache[block_idx, block_offset] ref_cache_slice = ref_cache[block_idx, block_offset] kv_nope = kv_cache_slice[:kv_lora_rank] ref_nope = ref_cache_slice[:kv_lora_rank] kv_scales = kv_cache_slice.view(torch.float32)[ kv_lora_rank // 4 : kv_lora_rank // 4 + 4 ] ref_scales = ref_cache_slice.view(torch.float32)[ kv_lora_rank // 4 : kv_lora_rank // 4 + 4 ] kv_rope = kv_cache_slice.view(dtype)[kv_lora_rank // 2 + 8 :] ref_rope = ref_cache_slice.view(dtype)[kv_lora_rank // 2 + 8 :] torch.testing.assert_close(kv_nope, ref_nope, atol=0.001, rtol=0.1) torch.testing.assert_close(kv_scales, ref_scales, atol=0.001, rtol=0.1) torch.testing.assert_close(kv_rope, ref_rope, atol=0.001, rtol=0.1) @pytest.mark.parametrize("kv_lora_rank", KV_LORA_RANKS) @pytest.mark.parametrize("qk_rope_head_dim", QK_ROPE_HEAD_DIMS) @pytest.mark.parametrize("block_size", BLOCK_SIZES_MLA) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS_MLA) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE) @torch.inference_mode() def test_swap_blocks_mla( kv_lora_rank: int, qk_rope_head_dim: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, device: str, kv_cache_dtype: str, ) -> None: current_platform.seed_everything(seed) torch.set_default_device(device) torch.cuda.set_device(device) entry_size = kv_lora_rank + qk_rope_head_dim src_cache = _create_mla_cache( num_blocks, block_size, entry_size, dtype, kv_cache_dtype, device ) dst_cache = _create_mla_cache( num_blocks, block_size, entry_size, dtype, kv_cache_dtype, device ) _fill_mla_cache(src_cache, kv_cache_dtype) _fill_mla_cache(dst_cache, kv_cache_dtype) src_cache_clone = src_cache.clone() num_mappings = min(2, num_blocks // 2) src_blocks = random.sample(range(num_blocks), num_mappings) remaining_blocks = list(set(range(num_blocks)) - set(src_blocks)) dst_blocks = random.sample(remaining_blocks, num_mappings) block_mapping = list(zip(src_blocks, dst_blocks)) block_mapping_tensor = torch.tensor( block_mapping, dtype=torch.int64, device="cpu" ).view(-1, 2) opcheck( torch.ops._C_cache_ops.swap_blocks, (src_cache, dst_cache, block_mapping_tensor), test_utils=DEFAULT_OPCHECK_TEST_UTILS, ) ops.swap_blocks(src_cache, dst_cache, block_mapping_tensor) for src, dst in block_mapping: torch.testing.assert_close( src_cache_clone[src].cpu(), dst_cache[dst].cpu(), msg=f"Block {src} from src should have been swapped to block " f"{dst} in dst_cache.", ) @pytest.mark.parametrize("kv_lora_rank", [512]) @pytest.mark.parametrize("qk_rope_head_dim", [64]) @pytest.mark.parametrize("block_size", [16]) @pytest.mark.parametrize("num_blocks", [1024]) @pytest.mark.parametrize("max_seq_len", [512]) @pytest.mark.parametrize("batch_size", [8]) @pytest.mark.parametrize("dtype", [torch.float32]) @pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) @pytest.mark.parametrize("device", CUDA_DEVICES) @torch.inference_mode() def test_gather_and_maybe_dequant_cache_mla( kv_lora_rank, qk_rope_head_dim, block_size, num_blocks, max_seq_len, batch_size, dtype, kv_cache_dtype, device, ): entry_size = kv_lora_rank + qk_rope_head_dim scale = torch.tensor(0.1, dtype=torch.float32, device=device) src_cache = _create_mla_cache( num_blocks, block_size, entry_size, dtype, kv_cache_dtype, device ) _fill_mla_cache(src_cache, kv_cache_dtype=kv_cache_dtype) seq_len_tensor = torch.randint( max_seq_len, max_seq_len + 1, (batch_size,), device=device ) total_tokens = seq_len_tensor.sum() cu_seq_lens = torch.empty((batch_size + 1), dtype=torch.int32, device=device) cu_seq_lens[0] = 0 cu_seq_lens[1:] = seq_len_tensor.cumsum(dim=0).to(dtype=torch.int32) token_to_seq = torch.arange(0, batch_size, dtype=torch.int32, device=device) token_to_seq = torch.repeat_interleave(token_to_seq, seq_len_tensor) print("seq_len_tensor", seq_len_tensor) tot_blocks_tensor = (seq_len_tensor + block_size - 1) // block_size block_table = torch.empty( (batch_size, num_blocks), dtype=torch.int32, device=device ) for b in range(batch_size): perm = torch.randperm(num_blocks, device=device) block_table[b, :] = perm dst = torch.zeros((total_tokens, entry_size), dtype=dtype, device=device) expected_batches = [] for b in range(batch_size): s = seq_len_tensor[b] if s == 0: continue tot = tot_blocks_tensor[b] blocks = block_table[b, :tot].tolist() gathered_rows = [] for i in range(tot - 1): block_data = src_cache[blocks[i]] if kv_cache_dtype == "fp8": dequantized_block = torch.empty_like(block_data, dtype=dtype) ops.convert_fp8(dequantized_block, block_data, scale.item()) gathered_rows.append(dequantized_block) else: gathered_rows.append(block_data) remaining = s - (tot - 1) * block_size last_block_data = src_cache[blocks[-1], :remaining, :] if kv_cache_dtype == "fp8": dequantized_last_block = torch.empty_like(last_block_data, dtype=dtype) ops.convert_fp8(dequantized_last_block, last_block_data, scale.item()) gathered_rows.append(dequantized_last_block) else: gathered_rows.append(last_block_data) batch_expected = torch.cat(gathered_rows, dim=0) expected_batches.append(batch_expected) expected = torch.cat(expected_batches, dim=0) opcheck( torch.ops._C_cache_ops.gather_and_maybe_dequant_cache, ( src_cache, dst, block_table, cu_seq_lens, token_to_seq, total_tokens, kv_cache_dtype, scale, None, ), test_utils=DEFAULT_OPCHECK_TEST_UTILS, ) ops.gather_and_maybe_dequant_cache( src_cache, dst, block_table, cu_seq_lens, token_to_seq, total_tokens, kv_cache_dtype, scale, None, ) torch.testing.assert_close(dst, expected) @pytest.mark.parametrize("kv_lora_rank", [512]) @pytest.mark.parametrize("qk_rope_head_dim", [64]) @pytest.mark.parametrize("block_size", [16]) @pytest.mark.parametrize("num_blocks", [1024]) @pytest.mark.parametrize("max_seq_len", [512]) @pytest.mark.parametrize("batch_size", [8]) @pytest.mark.parametrize("dtype", [torch.float32]) @pytest.mark.parametrize( "kv_cache_dtype", ["auto"] ) # You can also test "fp8" if needed. @pytest.mark.parametrize("device", CUDA_DEVICES) @torch.inference_mode() def test_cp_gather_cache_mla( kv_lora_rank, qk_rope_head_dim, block_size, num_blocks, max_seq_len, batch_size, dtype, kv_cache_dtype, device, ): entry_size = kv_lora_rank + qk_rope_head_dim src_cache = _create_mla_cache( num_blocks, block_size, entry_size, dtype, kv_cache_dtype, device ) _fill_mla_cache(src_cache, kv_cache_dtype=kv_cache_dtype) seq_len_tensor = torch.randint(0, max_seq_len + 1, (batch_size,), device=device) total_tokens = seq_len_tensor.sum() cu_seq_lens = torch.empty((batch_size + 1), dtype=torch.int32, device=device) cu_seq_lens[0] = 0 cu_seq_lens[1:] = seq_len_tensor.cumsum(dim=0).to(dtype=torch.int32) print("seq_len_tensor", seq_len_tensor) tot_blocks_tensor = (seq_len_tensor + block_size - 1) // block_size block_table = torch.empty( (batch_size, num_blocks), dtype=torch.int32, device=device ) for b in range(batch_size): perm = torch.randperm(num_blocks, device=device) block_table[b, :] = perm dst = torch.zeros((total_tokens, entry_size), dtype=src_cache.dtype, device=device) expected_batches = [] for b in range(batch_size): s = seq_len_tensor[b] if s == 0: continue tot = tot_blocks_tensor[b] blocks = block_table[b, :tot].tolist() gathered_rows = [] for i in range(tot - 1): gathered_rows.append(src_cache[blocks[i]]) remaining = s - (tot - 1) * block_size gathered_rows.append(src_cache[blocks[-1], :remaining, :]) batch_expected = torch.cat(gathered_rows, dim=0) expected_batches.append(batch_expected) expected = torch.cat(expected_batches, dim=0) opcheck( torch.ops._C_cache_ops.cp_gather_cache, (src_cache, dst, block_table, cu_seq_lens, batch_size, None), test_utils=DEFAULT_OPCHECK_TEST_UTILS, ) ops.cp_gather_cache(src_cache, dst, block_table, cu_seq_lens, batch_size) torch.testing.assert_close(dst, expected) @pytest.mark.parametrize("kv_lora_rank", KV_LORA_RANKS) @pytest.mark.parametrize("qk_rope_head_dim", QK_ROPE_HEAD_DIMS) @pytest.mark.parametrize("num_tokens", NUM_TOKENS_MLA) @pytest.mark.parametrize("block_size", BLOCK_SIZES_MLA) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS_MLA) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.cpu_model @pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only") @torch.inference_mode() def test_concat_and_cache_mla_cpu( kv_lora_rank: int, qk_rope_head_dim: int, num_tokens: int, block_size: int, num_blocks: int, dtype: torch.dtype, seed: int, ) -> None: device = "cpu" kv_cache_dtype = "auto" current_platform.seed_everything(seed) torch.set_default_device(device) total_slots = num_blocks * block_size slot_mapping_lst = random.sample(range(total_slots), num_tokens) slot_mapping = torch.tensor(slot_mapping_lst, dtype=torch.long, device=device)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_cpu_attn.py
tests/kernels/attention/test_cpu_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import functools import math import pytest import torch from vllm.platforms import CpuArchEnum, current_platform from vllm.v1.attention.backends.cpu_attn import _get_attn_isa if not current_platform.is_cpu(): pytest.skip("skipping CPU-only tests", allow_module_level=True) from vllm._custom_ops import ( cpu_attention_with_kv_cache, cpu_attn_get_scheduler_metadata, cpu_attn_reshape_and_cache, ) NUM_HEADS = [ (4, 4), (8, 2), (9, 3), ] HEAD_SIZES = [96, 128] QTYPES = [torch.bfloat16, torch.half, torch.float32] SLIDING_WINDOWS = [None, 256] NUM_BLOCKS = [ 1024, ] SEQ_LENS = [ # (q_len, kv_len) [(1, 213), (1, 1), (1, 312), (1, 7), (1, 7812)], # decode batch [(2345, 2345), (5, 5), (3, 16), (134, 5131)], # prefill batch [(992, 2456), (1, 1234), (98, 1145), (1, 4162), (2345, 2345)], # mixed batch ] def get_attn_isa( block_size: int | None = None, dtype: torch.dtype | None = None, ): if block_size and dtype: return _get_attn_isa(dtype, block_size) else: if current_platform.get_cpu_architecture() == CpuArchEnum.ARM: return "neon" elif torch._C._cpu._is_amx_tile_supported(): return "amx" else: return "vec" # rand number generation takes too much time, cache rand tensors @functools.lru_cache(maxsize=128, typed=False) def tensor_cache( elem_num: int, dtype: torch.dtype, ) -> torch.Tensor: tensor = torch.randn(elem_num, dtype=dtype) return tensor def _get_alibi_slopes(total_num_heads: int) -> torch.Tensor: closest_power_of_2 = 2 ** math.floor(math.log2(total_num_heads)) base = torch.tensor( 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), dtype=torch.float32, ) powers = torch.arange(1, 1 + closest_power_of_2, dtype=torch.int32) slopes = torch.pow(base, powers) if closest_power_of_2 != total_num_heads: extra_base = torch.tensor( 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), dtype=torch.float32, ) num_remaining_heads = min( closest_power_of_2, total_num_heads - closest_power_of_2 ) extra_powers = torch.arange( start=1, end=1 + 2 * num_remaining_heads, step=2, dtype=torch.int32 ) slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0) return slopes.float() def ref_paged_attn( query: torch.Tensor, key_cache: torch.Tensor, value_cache: torch.Tensor, query_lens: list[int], kv_lens: list[int], block_tables: torch.Tensor, scale: float, sliding_window: int | None = None, soft_cap: float | None = None, alibi_slopes: torch.Tensor | None = None, s_aux: torch.Tensor | None = None, ) -> torch.Tensor: num_seqs = len(query_lens) block_tables = block_tables.cpu().numpy() _, block_size, num_kv_heads, head_size = key_cache.shape dtype = query.dtype outputs: list[torch.Tensor] = [] start_idx = 0 if alibi_slopes is not None: alibi_slopes = alibi_slopes[:, None, None] if s_aux is not None: s_aux = s_aux.float() s_aux = s_aux[:, None, None] for i in range(num_seqs): query_len = query_lens[i] kv_len = kv_lens[i] q = query[start_idx : start_idx + query_len].float() q *= scale num_kv_blocks = (kv_len + block_size - 1) // block_size block_indices = block_tables[i, :num_kv_blocks] k = key_cache[block_indices].view(-1, num_kv_heads, head_size) k = k[:kv_len].float() v = value_cache[block_indices].view(-1, num_kv_heads, head_size) v = v[:kv_len].float() if q.shape[1] != k.shape[1]: k = torch.repeat_interleave(k, q.shape[1] // k.shape[1], dim=1) v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1) attn = torch.einsum("qhd,khd->hqk", q, k).float() empty_mask = torch.ones(query_len, kv_len) mask = torch.triu(empty_mask, diagonal=kv_len - query_len + 1).bool() if sliding_window is not None: sliding_window_mask = ( torch.triu( empty_mask, diagonal=kv_len - (query_len + sliding_window) + 1 ) .bool() .logical_not() ) mask |= sliding_window_mask if soft_cap is not None: attn = soft_cap * torch.tanh(attn / soft_cap) if alibi_slopes is not None: q_start_pos = kv_len - query_len q_pos = q_start_pos + torch.arange(0, query_len)[None, :, None] kv_pos = torch.arange(0, kv_len)[None, None, :] dist = q_pos - kv_pos alibi_bias = -alibi_slopes * dist attn += alibi_bias attn.masked_fill_(mask, float("-inf")) if s_aux is not None: s_aux_ext = s_aux.repeat(1, query_len, 1) attn = torch.cat((s_aux_ext, attn), dim=-1) attn = torch.softmax(attn, dim=-1) if s_aux is not None: attn = attn[:, :, 1:] out = torch.einsum("hqk,khd->qhd", attn, v).to(dtype=dtype) outputs.append(out) start_idx += query_len return torch.cat(outputs, dim=0) @torch.inference_mode() def varlen_with_paged_kv( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: current_platform.seed_everything(0) num_seqs = len(seq_lens) query_lens = [x[0] for x in seq_lens] kv_lens = [x[1] for x in seq_lens] num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_kv_len = max(kv_lens) window_size = (sliding_window - 1, 0) if sliding_window is not None else (-1, -1) scale = head_size**-0.5 token_num = sum(query_lens) # for n heads the set of slopes is the geometric sequence that starts # 2^(-8/n) alibi_slopes = _get_alibi_slopes(num_query_heads) if use_alibi else None s_aux = ( 15 * torch.rand((num_query_heads,), dtype=torch.bfloat16) if use_sink else None ) query = tensor_cache( elem_num=token_num * num_query_heads * head_size, dtype=dtype, ) query = query.view( token_num, num_query_heads, head_size, ) key_value = tensor_cache( elem_num=2 * num_blocks * num_kv_heads * block_size * head_size, dtype=dtype, ) key_value = key_value.view( 2, num_blocks, block_size, num_kv_heads, head_size, ) key_cache, value_cache = key_value.unbind(0) # KV cache for CPU attention packed_key_cache = torch.empty( num_blocks, num_kv_heads, block_size, head_size, dtype=dtype ) packed_value_cache = torch.empty_like(packed_key_cache) cu_query_lens = torch.tensor([0] + query_lens, dtype=torch.int32).cumsum( dim=0, dtype=torch.int32 ) kv_lens_tensor = torch.tensor(kv_lens, dtype=torch.int32) max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, num_blocks, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) # use reshape_and_cache to pack key_cache and value_cache slot_mapping = torch.arange(0, num_blocks * block_size, dtype=torch.int64) cpu_attn_reshape_and_cache( key=key_cache.view(-1, num_kv_heads, head_size), value=value_cache.view(-1, num_kv_heads, head_size), key_cache=packed_key_cache, value_cache=packed_value_cache, slot_mapping=slot_mapping, isa=isa, ) metadata = cpu_attn_get_scheduler_metadata( num_reqs=num_seqs, num_heads=num_query_heads, num_kv_heads=num_kv_heads, head_dim=head_size, seq_lens=kv_lens_tensor, dtype=dtype, query_start_loc=cu_query_lens, causal=True, sliding_window_size=sliding_window if sliding_window is not None else -1, isa=isa, enable_kv_split=False, ) out_without_split = torch.empty_like(query) cpu_attention_with_kv_cache( query=query, key_cache=packed_key_cache, value_cache=packed_value_cache, output=out_without_split, query_start_loc=cu_query_lens, seq_lens=kv_lens_tensor, scale=scale, causal=True, alibi_slopes=alibi_slopes, sliding_window=window_size, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, scheduler_metadata=metadata, s_aux=s_aux, ) metadata = cpu_attn_get_scheduler_metadata( num_reqs=num_seqs, num_heads=num_query_heads, num_kv_heads=num_kv_heads, head_dim=head_size, seq_lens=kv_lens_tensor, dtype=dtype, query_start_loc=cu_query_lens, causal=True, sliding_window_size=sliding_window if sliding_window is not None else -1, isa=isa, enable_kv_split=True, ) out_with_split = torch.empty_like(query) cpu_attention_with_kv_cache( query=query, key_cache=packed_key_cache, value_cache=packed_value_cache, output=out_with_split, query_start_loc=cu_query_lens, seq_lens=kv_lens_tensor, scale=scale, causal=True, alibi_slopes=alibi_slopes, sliding_window=window_size, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, scheduler_metadata=metadata, s_aux=s_aux, ) ref_output = ref_paged_attn( query=query, key_cache=key_cache, value_cache=value_cache, query_lens=query_lens, kv_lens=kv_lens, block_tables=block_tables, scale=scale, sliding_window=sliding_window, soft_cap=soft_cap, alibi_slopes=alibi_slopes, s_aux=s_aux, ) atol, rtol = 1.5e-2, 1e-2 ( torch.testing.assert_close(out_with_split, ref_output, atol=atol, rtol=rtol), f"{torch.max(torch.abs(out_with_split - ref_output))}", ) ( torch.testing.assert_close(out_without_split, ref_output, atol=atol, rtol=rtol), f"{torch.max(torch.abs(out_without_split - ref_output))}", ) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", [96, 128]) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", QTYPES) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("use_alibi", [False]) @pytest.mark.parametrize("use_sink", [False]) @pytest.mark.parametrize("isa", ["vec"]) def test_varlen_with_paged_kv_normal_vec( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: varlen_with_paged_kv( seq_lens=seq_lens, num_heads=num_heads, head_size=head_size, sliding_window=sliding_window, dtype=dtype, block_size=block_size, soft_cap=soft_cap, num_blocks=num_blocks, use_alibi=use_alibi, use_sink=use_sink, isa=isa, ) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", [96, 128]) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", [torch.bfloat16]) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("use_alibi", [False]) @pytest.mark.parametrize("use_sink", [False]) @pytest.mark.parametrize("isa", ["amx"]) @pytest.mark.skipif( not torch._C._cpu._is_amx_tile_supported(), reason="no AMX support." ) def test_varlen_with_paged_kv_normal_amx( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: varlen_with_paged_kv( seq_lens=seq_lens, num_heads=num_heads, head_size=head_size, sliding_window=sliding_window, dtype=dtype, block_size=block_size, soft_cap=soft_cap, num_blocks=num_blocks, use_alibi=use_alibi, use_sink=use_sink, isa=isa, ) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", [48]) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", [torch.bfloat16]) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("use_alibi", [False]) @pytest.mark.parametrize("use_sink", [False]) @pytest.mark.parametrize("isa", ["vec16"]) def test_varlen_with_paged_kv_normal_vec16( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: varlen_with_paged_kv( seq_lens=seq_lens, num_heads=num_heads, head_size=head_size, sliding_window=sliding_window, dtype=dtype, block_size=block_size, soft_cap=soft_cap, num_blocks=num_blocks, use_alibi=use_alibi, use_sink=use_sink, isa=isa, ) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", [96, 128]) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", QTYPES) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("use_alibi", [False]) @pytest.mark.parametrize("use_sink", [False]) @pytest.mark.parametrize("isa", ["neon"]) @pytest.mark.skipif( current_platform.get_cpu_architecture() != CpuArchEnum.ARM, reason="Not an Arm CPU.", ) def test_varlen_with_paged_kv_normal_neon( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: varlen_with_paged_kv( seq_lens=seq_lens, num_heads=num_heads, head_size=head_size, sliding_window=sliding_window, dtype=dtype, block_size=block_size, soft_cap=soft_cap, num_blocks=num_blocks, use_alibi=use_alibi, use_sink=use_sink, isa=isa, ) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", [96]) @pytest.mark.parametrize("block_size", [128]) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", [torch.bfloat16]) @pytest.mark.parametrize("soft_cap", [50]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("use_alibi", [False]) @pytest.mark.parametrize("use_sink", [False]) @pytest.mark.parametrize("isa", [get_attn_isa()]) def test_varlen_with_paged_kv_softcap( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: varlen_with_paged_kv( seq_lens=seq_lens, num_heads=num_heads, head_size=head_size, sliding_window=sliding_window, dtype=dtype, block_size=block_size, soft_cap=soft_cap, num_blocks=num_blocks, use_alibi=use_alibi, use_sink=use_sink, isa=isa, ) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", [96]) @pytest.mark.parametrize("block_size", [128]) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", [torch.bfloat16]) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("use_alibi", [True]) @pytest.mark.parametrize("use_sink", [False]) @pytest.mark.parametrize("isa", [get_attn_isa()]) def test_varlen_with_paged_kv_alibi( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: varlen_with_paged_kv( seq_lens=seq_lens, num_heads=num_heads, head_size=head_size, sliding_window=sliding_window, dtype=dtype, block_size=block_size, soft_cap=soft_cap, num_blocks=num_blocks, use_alibi=use_alibi, use_sink=use_sink, isa=isa, ) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", [96]) @pytest.mark.parametrize("block_size", [128]) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @pytest.mark.parametrize("dtype", [torch.bfloat16]) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("use_alibi", [False]) @pytest.mark.parametrize("use_sink", [True]) @pytest.mark.parametrize("isa", [get_attn_isa()]) def test_varlen_with_paged_kv_sink( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, use_alibi: bool, use_sink: bool, isa: str, ) -> None: varlen_with_paged_kv( seq_lens=seq_lens, num_heads=num_heads, head_size=head_size, sliding_window=sliding_window, dtype=dtype, block_size=block_size, soft_cap=soft_cap, num_blocks=num_blocks, use_alibi=use_alibi, use_sink=use_sink, isa=isa, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_prefix_prefill.py
tests/kernels/attention/test_prefix_prefill.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import math import random import time from collections.abc import Callable import pytest import torch import torch.nn.functional as F from vllm.attention.ops.chunked_prefill_paged_decode import chunked_prefill_paged_decode from vllm.attention.ops.prefix_prefill import context_attention_fwd from vllm.platforms import current_platform from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE NUM_HEADS = [64] NUM_QUERIES_PER_KV = [1, 64] HEAD_SIZES = [24, 128] DTYPES = [torch.float16] CUDA_DEVICES = [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)] SLIDING_WINDOW = [0, 16, 2048] KV_CACHE_DTYPES = ["auto", "fp8", "fp8_e5m2"] OPS = [chunked_prefill_paged_decode, context_attention_fwd] def create_causal_attention_mask_for_sdpa( query_lens: list[int], seq_lens: list[int], sliding_window: int = 0, device: torch.device = None, dtype: torch.dtype = None, ) -> torch.Tensor: total_queries = sum(query_lens) total_keys = sum(seq_lens) # Create a mask filled with -inf mask = torch.full( (total_queries, total_keys), float("-inf"), device=device, dtype=dtype ) query_start = 0 key_start = 0 for query_len, seq_len in zip(query_lens, seq_lens): query_end = query_start + query_len key_end = key_start + seq_len q_indices = torch.arange(query_len, device=device) k_indices = torch.arange(seq_len, device=device) q_pos_in_seq = seq_len - query_len + q_indices valid_mask = k_indices[None, :] <= q_pos_in_seq[:, None] if sliding_window > 0: valid_mask &= k_indices[None, :] >= ( q_pos_in_seq[:, None] - sliding_window + 1 ) mask[query_start:query_end, key_start:key_end][valid_mask] = 0.0 query_start = query_end key_start = key_end return mask def create_alibi_causal_mask( query_len: int, seq_len: int, alibi_slopes: torch.Tensor, device: torch.device, dtype: torch.dtype, ) -> torch.Tensor: query_pos = torch.arange( seq_len - query_len, seq_len, device=device, dtype=torch.float32 ) key_pos = torch.arange(seq_len, device=device, dtype=torch.float32) rel_pos = key_pos[None, :] - query_pos[:, None] # Apply ALiBi slopes: [num_heads, query_len, seq_len] alibi_bias = alibi_slopes[:, None, None] * rel_pos[None, :, :] alibi_bias = alibi_bias.to(dtype) # Apply causal mask: prevent attending to future positions # causal_mask[i, j] = True if key_pos[j] <= query_pos[i] causal_mask = key_pos[None, :] <= query_pos[:, None] alibi_bias = alibi_bias.masked_fill(~causal_mask[None, :, :], float("-inf")) # Add batch dimension: [1, num_heads, query_len, seq_len] # SDPA expects batch dimension even for single sequences return alibi_bias.unsqueeze(0) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("num_queries_per_kv", NUM_QUERIES_PER_KV) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPES) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOW) @pytest.mark.parametrize("op", OPS) @torch.inference_mode() def test_contexted_kv_attention( num_heads: int, num_queries_per_kv: int, head_size: int, sliding_window: int, dtype: torch.dtype, kv_cache_dtype: str, device: str, op: Callable, ) -> None: if "fp8" in kv_cache_dtype and not current_platform.has_device_capability(89): pytest.skip( "Triton limitation: fp8e4nv data type is not supported on CUDA arch < 89" ) if ( current_platform.is_rocm() and op is chunked_prefill_paged_decode and kv_cache_dtype == "fp8_e5m2" ): pytest.skip("ROCm custom paged attention does not support fp8_e5m2 KV cache") current_platform.seed_everything(0) torch.set_default_device(device) # Need this, otherwise when we capture the graph the process # for GPU 1 would run on both GPU0 and GPU1 and things would hang # # see also similar issue: https://github.com/Dao-AILab/flash-attention/issues/523 torch.cuda.set_device(device) MAX_SEQ_LEN = 1024 MAX_CTX_LEN = 1024 BS = 10 cache_size = 640 block_size = 32 max_block_per_request = 64 query_lens = [random.randint(16, MAX_SEQ_LEN) for _ in range(BS)] # ensure one sequence in batch is a decode query_lens[-1] = 1 ctx_lens = [random.randint(16, MAX_CTX_LEN) for _ in range(BS)] seq_lens = [a + b for a, b in zip(query_lens, ctx_lens)] num_kv_heads = num_heads // num_queries_per_kv num_tokens = sum(query_lens) query = torch.empty(num_tokens, num_heads, head_size, dtype=dtype) query.uniform_(-1e-3, 1e-3) output = torch.empty(num_tokens, num_heads, head_size, dtype=dtype) kv = torch.empty(sum(seq_lens), 2, num_kv_heads, head_size, dtype=dtype) kv.uniform_(-1e-3, 1e-3) key, value = kv.unbind(dim=1) if kv_cache_dtype == "auto": cache_dtype = dtype else: cache_dtype = STR_DTYPE_TO_TORCH_DTYPE[kv_cache_dtype] k_cache = torch.zeros( cache_size, block_size, num_kv_heads, head_size, dtype=cache_dtype ) v_cache = torch.zeros( cache_size, block_size, num_kv_heads, head_size, dtype=cache_dtype ) k = torch.zeros(sum(query_lens), num_kv_heads, head_size, dtype=dtype) v = torch.zeros(sum(query_lens), num_kv_heads, head_size, dtype=dtype) values = torch.arange(0, cache_size, dtype=torch.int32) values = values[torch.randperm(cache_size)] block_table = values[: BS * max_block_per_request].view(BS, max_block_per_request) b_seq_len = torch.tensor(seq_lens, dtype=torch.int32) b_ctx_len = torch.tensor(ctx_lens, dtype=torch.int32) b_start_loc = torch.cumsum(torch.tensor([0] + query_lens), dim=0).to(torch.int32) max_input_len = MAX_SEQ_LEN # copy kv to cache b_seq_start_loc = torch.cumsum(torch.tensor([0] + seq_lens[:-1]), dim=0).to( torch.int32 ) for i in range(BS): for j in range(query_lens[i]): k[b_start_loc[i] + j].copy_(key[b_seq_start_loc[i] + b_ctx_len[i] + j]) v[b_start_loc[i] + j].copy_(value[b_seq_start_loc[i] + b_ctx_len[i] + j]) cur_ctx = 0 block_id = 0 while cur_ctx < b_ctx_len[i]: start_loc = b_seq_start_loc[i] + cur_ctx if cur_ctx + block_size > b_ctx_len[i]: end_loc = b_seq_start_loc[i] + b_ctx_len[i] else: end_loc = start_loc + block_size start_slot = block_table[i, block_id] * block_size end_slot = start_slot + end_loc - start_loc k_cache.view(-1, num_kv_heads, head_size)[start_slot:end_slot].copy_( key[start_loc:end_loc] ) v_cache.view(-1, num_kv_heads, head_size)[start_slot:end_slot].copy_( value[start_loc:end_loc] ) cur_ctx += block_size block_id += 1 # transpose K_cache[num_blocks, block_size, num_kv_heads, head_size] # to K_cache[num_blocks, num_kv_heads, head_size/8, block_size, 8] k_cache = ( k_cache.view(-1, block_size, num_kv_heads, head_size // 8, 8) .permute(0, 2, 3, 1, 4) .contiguous() ) # transpose V_cache[num_blocks, block_size, num_kv_heads, head_size] # to V_cache[num_blocks, num_kv_heads, head_size, block_size] v_cache = ( v_cache.view(-1, block_size, num_kv_heads, head_size) .permute(0, 2, 3, 1) .contiguous() ) k_scale = v_scale = torch.tensor(1.0, dtype=torch.float32, device=device) # Warm up the Triton kernel by calling it once before actually measuring # generation time op( query, k, v, output, kv_cache_dtype, k_cache, v_cache, block_table, b_start_loc, b_seq_len, MAX_CTX_LEN, max_input_len, k_scale, v_scale, sliding_window=sliding_window, ) torch.cuda.synchronize() start_time = time.time() op( query, k, v, output, kv_cache_dtype, k_cache, v_cache, block_table, b_start_loc, b_seq_len, MAX_CTX_LEN, max_input_len, k_scale, v_scale, sliding_window=sliding_window, ) torch.cuda.synchronize() end_time = time.time() print(f"triton Time: {(end_time - start_time) * 1000:.2f} ms") scale = float(1.0 / (head_size**0.5)) # Reshape for SDPA: (seq_len, num_heads, head_size) -> # (1, num_heads, seq_len, head_size) query_sdpa = query.view(num_tokens, num_kv_heads, num_queries_per_kv, head_size) query_sdpa = query_sdpa.permute(1, 2, 0, 3).reshape( 1, num_heads, num_tokens, head_size ) # Expand key and value for GQA/MQA to match query heads key_sdpa = key[:, :, None, :].expand( key.shape[0], num_kv_heads, num_queries_per_kv, key.shape[-1] ) key_sdpa = key_sdpa.permute(1, 2, 0, 3).reshape( 1, num_heads, sum(seq_lens), head_size ) value_sdpa = value[:, :, None, :].expand( value.shape[0], num_kv_heads, num_queries_per_kv, value.shape[-1] ) value_sdpa = value_sdpa.permute(1, 2, 0, 3).reshape( 1, num_heads, sum(seq_lens), head_size ) attn_mask = create_causal_attention_mask_for_sdpa( query_lens, seq_lens, sliding_window, device=device, dtype=dtype ) output_ref = F.scaled_dot_product_attention( query_sdpa, key_sdpa, value_sdpa, attn_mask=attn_mask, dropout_p=0.0, scale=scale, ) torch.cuda.synchronize() start_time = time.time() output_ref = F.scaled_dot_product_attention( query_sdpa, key_sdpa, value_sdpa, attn_mask=attn_mask, dropout_p=0.0, scale=scale, ) torch.cuda.synchronize() end_time = time.time() print(f"PyTorch SDPA Time: {(end_time - start_time) * 1000:.2f} ms") # Reshape output back to (num_tokens, num_heads, head_size) output_ref = output_ref.view(num_heads, num_tokens, head_size) output_ref = output_ref.permute(1, 0, 2).contiguous() atol = 1e-3 if "fp8" in kv_cache_dtype else 1e-4 torch.testing.assert_close(output, output_ref, atol=atol, rtol=0) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("num_queries_per_kv", NUM_QUERIES_PER_KV) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPES) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("op", OPS) @torch.inference_mode() def test_contexted_kv_attention_alibi( num_heads: int, num_queries_per_kv: int, head_size: int, dtype: torch.dtype, kv_cache_dtype: str, device: str, op: Callable, ) -> None: if "fp8" in kv_cache_dtype and not current_platform.has_device_capability(89): pytest.skip( "Triton limitation: fp8e4nv data type is not supported on CUDA arch < 89" ) if ( current_platform.is_rocm() and op is chunked_prefill_paged_decode and kv_cache_dtype == "fp8_e5m2" ): pytest.skip("ROCm custom paged attention does not support fp8_e5m2 KV cache") current_platform.seed_everything(0) torch.set_default_device(device) # Need this, otherwise when we capture the graph the process # for GPU 1 would run on both GPU0 and GPU1 and things would hang # # see also similar issue: https://github.com/Dao-AILab/flash-attention/issues/523 torch.cuda.set_device(device) def _get_alibi_slopes(total_num_heads: int) -> torch.Tensor: # Fork from: vllm/vllm/model_executor/models/bloom.py#L44 closest_power_of_2 = 2 ** math.floor(math.log2(total_num_heads)) base = torch.tensor( 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), dtype=torch.float32, ) powers = torch.arange(1, 1 + closest_power_of_2, dtype=torch.int32) slopes = torch.pow(base, powers) if closest_power_of_2 != total_num_heads: extra_base = torch.tensor( 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), dtype=torch.float32, ) num_remaining_heads = min( closest_power_of_2, total_num_heads - closest_power_of_2 ) extra_powers = torch.arange( start=1, end=1 + 2 * num_remaining_heads, step=2, dtype=torch.int32 ) slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0) return slopes alibi_slopes = _get_alibi_slopes(num_heads).to(device) MAX_SEQ_LEN = 1024 MAX_CTX_LEN = 1024 BS = 10 cache_size = 640 block_size = 32 max_block_per_request = 64 query_lens = [random.randint(16, MAX_SEQ_LEN) for _ in range(BS)] ctx_lens = [random.randint(16, MAX_CTX_LEN) for _ in range(BS)] seq_lens = [a + b for a, b in zip(query_lens, ctx_lens)] num_kv_heads = num_heads // num_queries_per_kv num_tokens = sum(query_lens) query = torch.empty(num_tokens, num_heads, head_size, dtype=dtype) query.uniform_(-1e-3, 1e-3) output = torch.empty(num_tokens, num_heads, head_size, dtype=dtype) kv = torch.empty(sum(seq_lens), 2, num_kv_heads, head_size, dtype=dtype) kv.uniform_(-1e-3, 1e-3) key, value = kv.unbind(dim=1) if kv_cache_dtype == "auto": cache_dtype = dtype else: cache_dtype = STR_DTYPE_TO_TORCH_DTYPE[kv_cache_dtype] k_cache = torch.zeros( cache_size, block_size, num_kv_heads, head_size, dtype=cache_dtype ) v_cache = torch.zeros( cache_size, block_size, num_kv_heads, head_size, dtype=cache_dtype ) k = torch.zeros(sum(query_lens), num_kv_heads, head_size, dtype=dtype) v = torch.zeros(sum(query_lens), num_kv_heads, head_size, dtype=dtype) values = torch.arange(0, cache_size, dtype=torch.int32) values = values[torch.randperm(cache_size)] block_table = values[: BS * max_block_per_request].view(BS, max_block_per_request) b_seq_len = torch.tensor(seq_lens, dtype=torch.int32) b_ctx_len = torch.tensor(ctx_lens, dtype=torch.int32) b_start_loc = torch.cumsum(torch.tensor([0] + query_lens), dim=0).to(torch.int32) max_input_len = MAX_SEQ_LEN # copy kv to cache b_seq_start_loc = torch.cumsum(torch.tensor([0] + seq_lens[:-1]), dim=0).to( torch.int32 ) for i in range(BS): for j in range(query_lens[i]): k[b_start_loc[i] + j].copy_(key[b_seq_start_loc[i] + b_ctx_len[i] + j]) v[b_start_loc[i] + j].copy_(value[b_seq_start_loc[i] + b_ctx_len[i] + j]) cur_ctx = 0 block_id = 0 while cur_ctx < b_ctx_len[i]: start_loc = b_seq_start_loc[i] + cur_ctx if cur_ctx + block_size > b_ctx_len[i]: end_loc = b_seq_start_loc[i] + b_ctx_len[i] else: end_loc = start_loc + block_size start_slot = block_table[i, block_id] * block_size end_slot = start_slot + end_loc - start_loc k_cache.view(-1, num_kv_heads, head_size)[start_slot:end_slot].copy_( key[start_loc:end_loc] ) v_cache.view(-1, num_kv_heads, head_size)[start_slot:end_slot].copy_( value[start_loc:end_loc] ) cur_ctx += block_size block_id += 1 # transpose K_cache[num_blocks, block_size, num_kv_heads, head_size] # to K_cache[num_blocks, num_kv_heads, head_size/8, block_size, 8] k_cache = ( k_cache.view(-1, block_size, num_kv_heads, head_size // 8, 8) .permute(0, 2, 3, 1, 4) .contiguous() ) # transpose V_cache[num_blocks, block_size, num_kv_heads, head_size] # to V_cache[num_blocks, num_kv_heads, head_size, block_size] v_cache = ( v_cache.view(-1, block_size, num_kv_heads, head_size) .permute(0, 2, 3, 1) .contiguous() ) k_scale = v_scale = torch.tensor(1.0, dtype=torch.float32, device=device) # Warm up the Triton kernel by calling it once before actually measuring # generation time op( query, k, v, output, kv_cache_dtype, k_cache, v_cache, block_table, b_start_loc, b_seq_len, MAX_CTX_LEN, max_input_len, k_scale, v_scale, alibi_slopes=alibi_slopes, ) torch.cuda.synchronize() start_time = time.time() op( query, k, v, output, kv_cache_dtype, k_cache, v_cache, block_table, b_start_loc, b_seq_len, MAX_CTX_LEN, max_input_len, k_scale, v_scale, alibi_slopes=alibi_slopes, ) torch.cuda.synchronize() end_time = time.time() print(f"triton Time: {(end_time - start_time) * 1000:.2f} ms") scale = float(1.0 / (head_size**0.5)) # Prepare query, key, value for SDPA # Expand key and value for GQA/MQA to match query heads key_expanded = key[:, :, None, :].expand( key.shape[0], num_kv_heads, num_queries_per_kv, key.shape[-1] ) value_expanded = value[:, :, None, :].expand( value.shape[0], num_kv_heads, num_queries_per_kv, value.shape[-1] ) output_ref = torch.empty_like(output) torch.cuda.synchronize() start_time = time.time() query_start = 0 key_start = 0 for i, (query_len, seq_len) in enumerate(zip(query_lens, seq_lens)): query_end = query_start + query_len key_end = key_start + seq_len # Get query, key, value for this sequence q = query[query_start:query_end] # [query_len, num_heads, head_size] k = key_expanded[ key_start:key_end ] # [seq_len, num_kv_heads, num_queries_per_kv, head_size] v = value_expanded[ key_start:key_end ] # [seq_len, num_kv_heads, num_queries_per_kv, head_size] # Reshape for SDPA: (batch=1, num_heads, seq_len, head_size) q_sdpa = q.view(query_len, num_kv_heads, num_queries_per_kv, head_size) q_sdpa = ( q_sdpa.permute(1, 2, 0, 3) .reshape(1, num_heads, query_len, head_size) .contiguous() ) k_sdpa = ( k.permute(1, 2, 0, 3).reshape(1, num_heads, seq_len, head_size).contiguous() ) v_sdpa = ( v.permute(1, 2, 0, 3).reshape(1, num_heads, seq_len, head_size).contiguous() ) # Create ALiBi causal mask for this sequence using utility function alibi_mask = create_alibi_causal_mask( query_len, seq_len, alibi_slopes, device, dtype ) # Compute attention out = F.scaled_dot_product_attention( q_sdpa, k_sdpa, v_sdpa, attn_mask=alibi_mask, dropout_p=0.0, scale=scale, ) # Reshape output back to [query_len, num_heads, head_size] out = out.view(num_heads, query_len, head_size).permute(1, 0, 2) output_ref[query_start:query_end].copy_(out) query_start = query_end key_start = key_end torch.cuda.synchronize() end_time = time.time() print(f"PyTorch SDPA Time: {(end_time - start_time) * 1000:.2f} ms") atol = 1e-3 if "fp8" in kv_cache_dtype else 1e-6 torch.testing.assert_close(output, output_ref, atol=atol, rtol=0) # These tests are optional to only run when explicitly invoked # # pytest -v -s --optional \ # tests/kernels/test_prefix_prefill.py::test_contexted_kv_attention_f32 # # These tests are useful to test model dtype float32 on Turing devices. # We skip them to not increase the time when running tests on CI @pytest.mark.optional @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("num_queries_per_kv", NUM_QUERIES_PER_KV) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", [torch.float32]) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPES) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOW) @pytest.mark.parametrize("op", OPS) @torch.inference_mode() def test_contexted_kv_attention_f32( num_heads: int, num_queries_per_kv: int, head_size: int, sliding_window: int, dtype: torch.dtype, kv_cache_dtype: str, device: str, op: Callable, ) -> None: test_contexted_kv_attention( num_heads, num_queries_per_kv, head_size, sliding_window, dtype, kv_cache_dtype, device, op, ) @pytest.mark.optional @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("num_queries_per_kv", NUM_QUERIES_PER_KV) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", [torch.float32]) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPES) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("op", OPS) @torch.inference_mode() def test_contexted_kv_attention_alibi_f32( num_heads: int, num_queries_per_kv: int, head_size: int, dtype: torch.dtype, kv_cache_dtype: str, device: str, op: Callable, ) -> None: test_contexted_kv_attention_alibi( num_heads, num_queries_per_kv, head_size, dtype, kv_cache_dtype, device, op )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_flashinfer.py
tests/kernels/attention/test_flashinfer.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.platforms import current_platform try: import flashinfer except ImportError: if current_platform.is_rocm(): pytest.skip( "flashinfer is not supported for vLLM on ROCm.", allow_module_level=True ) import torch NUM_HEADS = [(32, 8), (6, 1)] HEAD_SIZES = [128, 256] BLOCK_SIZES = [16, 32] DTYPES = [torch.bfloat16] NUM_BLOCKS = 32768 # Large enough to test overflow in index calculation. SOFT_CAPS = [None, 30.0] SLIDING_WINDOWS = [None, 64] def ref_paged_attn( query: torch.Tensor, key_cache: torch.Tensor, value_cache: torch.Tensor, query_lens: list[int], kv_lens: list[int], block_tables: torch.Tensor, scale: float, sliding_window: int | None = None, soft_cap: float | None = None, ) -> torch.Tensor: num_seqs = len(query_lens) block_tables = block_tables.cpu().numpy() _, block_size, num_kv_heads, head_size = key_cache.shape outputs: list[torch.Tensor] = [] start_idx = 0 for i in range(num_seqs): query_len = query_lens[i] kv_len = kv_lens[i] q = query[start_idx : start_idx + query_len] q *= scale num_kv_blocks = (kv_len + block_size - 1) // block_size block_indices = block_tables[i, :num_kv_blocks] k = key_cache[block_indices].view(-1, num_kv_heads, head_size) k = k[:kv_len] v = value_cache[block_indices].view(-1, num_kv_heads, head_size) v = v[:kv_len] if q.shape[1] != k.shape[1]: k = torch.repeat_interleave(k, q.shape[1] // k.shape[1], dim=1) v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1) attn = torch.einsum("qhd,khd->hqk", q, k).float() empty_mask = torch.ones(query_len, kv_len) mask = torch.triu(empty_mask, diagonal=kv_len - query_len + 1).bool() if sliding_window is not None: sliding_window_mask = ( torch.triu( empty_mask, diagonal=kv_len - (query_len + sliding_window) + 1 ) .bool() .logical_not() ) mask |= sliding_window_mask if soft_cap is not None: attn = soft_cap * torch.tanh(attn / soft_cap) attn.masked_fill_(mask, float("-inf")) attn = torch.softmax(attn, dim=-1).to(v.dtype) out = torch.einsum("hqk,khd->qhd", attn, v) outputs.append(out) start_idx += query_len return torch.cat(outputs, dim=0) @pytest.mark.parametrize("kv_lens", [[1328, 18, 463], [1, 54, 293, 70]]) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("soft_cap", SOFT_CAPS) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @torch.inference_mode def test_flashinfer_decode_with_paged_kv( kv_lens: list[int], num_heads: tuple[int, int], head_size: int, dtype: torch.dtype, block_size: int, soft_cap: float | None, sliding_window: int | None, ) -> None: torch.set_default_device("cuda") current_platform.seed_everything(0) num_seqs = len(kv_lens) num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_kv_len = max(kv_lens) scale = head_size**-0.5 query = torch.randn(num_seqs, num_query_heads, head_size, dtype=dtype) key_value_cache = torch.randn( NUM_BLOCKS, 2, block_size, num_kv_heads, head_size, dtype=dtype ) key_cache = key_value_cache[:, 0, :, :, :].squeeze(1) value_cache = key_value_cache[:, 1, :, :, :].squeeze(1) max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, NUM_BLOCKS, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) kv_indptr = [0] kv_indices = [] kv_last_page_lens = [] for i in range(num_seqs): seq_len = kv_lens[i] assert seq_len > 0 num_blocks = (seq_len + block_size - 1) // block_size kv_indices.extend(block_tables[i, :num_blocks]) kv_indptr.append(kv_indptr[-1] + num_blocks) kv_last_page_len = seq_len % block_size if kv_last_page_len == 0: kv_last_page_len = block_size kv_last_page_lens.append(kv_last_page_len) kv_indptr = torch.tensor(kv_indptr, dtype=torch.int32) kv_indices = torch.tensor(kv_indices, dtype=torch.int32) kv_last_page_lens = torch.tensor(kv_last_page_lens, dtype=torch.int32) workspace_buffer = torch.empty(128 * 1024 * 1024, dtype=torch.int8) wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper( workspace_buffer, "NHD", use_tensor_cores=True ) wrapper.plan( kv_indptr, kv_indices, kv_last_page_lens, num_query_heads, num_kv_heads, head_size, block_size, "NONE", window_left=sliding_window - 1 if sliding_window is not None else -1, q_data_type=dtype, kv_data_type=dtype, logits_soft_cap=soft_cap, ) output = wrapper.run(query, key_value_cache) ref_output = ref_paged_attn( query=query, key_cache=key_cache, value_cache=value_cache, query_lens=[1] * num_seqs, kv_lens=kv_lens, block_tables=block_tables, scale=scale, soft_cap=soft_cap, sliding_window=sliding_window, ) ( torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=1e-2), f"{torch.max(torch.abs(output - ref_output))}", ) @pytest.mark.parametrize("seq_lens", [[(1, 1328), (5, 18), (129, 463)]]) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("soft_cap", SOFT_CAPS) @pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) @torch.inference_mode def test_flashinfer_prefill_with_paged_kv( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, dtype: torch.dtype, block_size: int, soft_cap: float | None, sliding_window: int | None, ) -> None: torch.set_default_device("cuda") current_platform.seed_everything(0) num_seqs = len(seq_lens) query_lens = [x[0] for x in seq_lens] kv_lens = [x[1] for x in seq_lens] num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_kv_len = max(kv_lens) scale = head_size**-0.5 query = torch.randn(sum(query_lens), num_query_heads, head_size, dtype=dtype) key_value_cache = torch.randn( NUM_BLOCKS, 2, block_size, num_kv_heads, head_size, dtype=dtype ) key_cache = key_value_cache[:, 0, :, :, :].squeeze(1) value_cache = key_value_cache[:, 1, :, :, :].squeeze(1) # Normalize the scale of the key and value caches to mitigate # numerical instability. key_cache /= head_size**0.5 value_cache /= head_size**0.5 max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, NUM_BLOCKS, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) qo_indptr = [0] kv_indptr = [0] kv_indices = [] kv_last_page_lens = [] for i in range(num_seqs): seq_len = kv_lens[i] assert seq_len > 0 num_blocks = (seq_len + block_size - 1) // block_size kv_indices.extend(block_tables[i, :num_blocks]) kv_indptr.append(kv_indptr[-1] + num_blocks) kv_last_page_len = seq_len % block_size if kv_last_page_len == 0: kv_last_page_len = block_size kv_last_page_lens.append(kv_last_page_len) qo_indptr.append(qo_indptr[-1] + query_lens[i]) qo_indptr = torch.tensor(qo_indptr, dtype=torch.int32) kv_indptr = torch.tensor(kv_indptr, dtype=torch.int32) kv_indices = torch.tensor(kv_indices, dtype=torch.int32) kv_last_page_lens = torch.tensor(kv_last_page_lens, dtype=torch.int32) workspace_buffer = torch.empty(128 * 1024 * 1024, dtype=torch.int8) wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper(workspace_buffer, "NHD") wrapper.plan( qo_indptr, kv_indptr, kv_indices, kv_last_page_lens, num_query_heads, num_kv_heads, head_size, block_size, window_left=sliding_window - 1 if sliding_window is not None else -1, q_data_type=dtype, kv_data_type=dtype, logits_soft_cap=soft_cap, ) output = wrapper.run( query, key_value_cache, ) ref_output = ref_paged_attn( query=query, key_cache=key_cache, value_cache=value_cache, query_lens=query_lens, kv_lens=kv_lens, block_tables=block_tables, scale=scale, soft_cap=soft_cap, sliding_window=sliding_window, ) ( torch.testing.assert_close(output, ref_output, atol=5e-2, rtol=1e-2), f"{torch.max(torch.abs(output - ref_output))}", ) @pytest.mark.parametrize("seq_lens", [[(1, 132), (5, 18)]]) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("soft_cap", SOFT_CAPS) def test_flashinfer_prefill_with_paged_fp8_kv( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, dtype: torch.dtype, block_size: int, soft_cap: float | None, ) -> None: pytest.skip("TODO: fix the accuracy issue") torch.set_default_device("cuda") current_platform.seed_everything(0) num_seqs = len(seq_lens) query_lens = [x[0] for x in seq_lens] kv_lens = [x[1] for x in seq_lens] num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_kv_len = max(kv_lens) scale = head_size**-0.5 kv_cache_dtype = torch.float8_e4m3fn query = torch.randn(sum(query_lens), num_query_heads, head_size, dtype=dtype) NUM_BLOCKS_FP8 = 2048 key_value_cache = torch.randn( NUM_BLOCKS_FP8, 2, block_size, num_kv_heads, head_size, dtype=dtype ) key_cache, value_cache = torch.chunk(key_value_cache, 2, dim=1) key_cache /= head_size**0.5 value_cache /= head_size**0.5 k_scale = key_cache.amax().item() / 448.0 v_scale = value_cache.amax().item() / 448.0 kv_cache_fp8 = torch.cat([key_cache / k_scale, value_cache / v_scale], dim=1).to( kv_cache_dtype ) assert kv_cache_fp8.shape == key_value_cache.shape max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, NUM_BLOCKS_FP8, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) qo_indptr = [0] kv_indptr = [0] kv_indices = [] kv_last_page_lens = [] for i in range(num_seqs): seq_len = kv_lens[i] assert seq_len > 0 num_blocks = (seq_len + block_size - 1) // block_size kv_indices.extend(block_tables[i, :num_blocks]) kv_indptr.append(kv_indptr[-1] + num_blocks) kv_last_page_len = seq_len % block_size if kv_last_page_len == 0: kv_last_page_len = block_size kv_last_page_lens.append(kv_last_page_len) qo_indptr.append(qo_indptr[-1] + query_lens[i]) qo_indptr = torch.tensor(qo_indptr, dtype=torch.int32) kv_indptr = torch.tensor(kv_indptr, dtype=torch.int32) kv_indices = torch.tensor(kv_indices, dtype=torch.int32) kv_last_page_lens = torch.tensor(kv_last_page_lens, dtype=torch.int32) workspace_buffer = torch.empty(128 * 1024 * 1024, dtype=torch.int8) wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper(workspace_buffer, "NHD") wrapper.plan( qo_indptr, kv_indptr, kv_indices, kv_last_page_lens, num_query_heads, num_kv_heads, head_size, block_size, q_data_type=dtype, kv_data_type=kv_cache_dtype, logits_soft_cap=soft_cap, ) output = wrapper.run(query, kv_cache_fp8, k_scale=k_scale, v_scale=v_scale) ref_output = ref_paged_attn( query=query, key_cache=key_cache.squeeze(1), value_cache=value_cache.squeeze(1), query_lens=query_lens, kv_lens=kv_lens, block_tables=block_tables, scale=scale, soft_cap=soft_cap, ) del query del block_tables # verify prefill fp8 ( torch.testing.assert_close(output, ref_output, atol=5e-2, rtol=1e-2), f"{torch.max(torch.abs(output - ref_output))}", ) @pytest.mark.parametrize("kv_lens", [[1328, 18, 463], [1, 54, 293, 70]]) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("soft_cap", SOFT_CAPS) @pytest.mark.skip(reason="TODO: fix the accuracy issue") @torch.inference_mode def test_flashinfer_decode_with_paged_fp8_kv( kv_lens: list[int], num_heads: tuple[int, int], head_size: int, dtype: torch.dtype, block_size: int, soft_cap: float | None, ) -> None: # test doesn't work for num_heads = (16,16) torch.set_default_device("cuda") current_platform.seed_everything(0) num_seqs = len(kv_lens) num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_kv_len = max(kv_lens) scale = head_size**-0.5 use_tensor_cores = True kv_cache_dtype = torch.float8_e4m3fn query = torch.randn(num_seqs, num_query_heads, head_size, dtype=dtype) NUM_BLOCKS_FP8 = 2048 key_value_cache = torch.randn( NUM_BLOCKS_FP8, 2, block_size, num_kv_heads, head_size, dtype=dtype ) key_cache, value_cache = torch.chunk(key_value_cache, 2, dim=1) key_cache /= head_size**0.5 value_cache /= head_size**0.5 k_scale = key_cache.amax().item() / 448.0 v_scale = value_cache.amax().item() / 448.0 key_cache_fp8 = (key_cache / k_scale).to(kv_cache_dtype) value_cache_fp8 = (value_cache / v_scale).to(kv_cache_dtype) assert key_cache_fp8.shape[1] == 1 and value_cache_fp8.shape[1] == 1 kv_cache_fp8 = torch.cat([key_cache_fp8, value_cache_fp8], dim=1) max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, NUM_BLOCKS_FP8, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) kv_indptr = [0] kv_indices = [] kv_last_page_lens = [] for i in range(num_seqs): seq_len = kv_lens[i] assert seq_len > 0 num_blocks = (seq_len + block_size - 1) // block_size kv_indices.extend(block_tables[i, :num_blocks]) kv_indptr.append(kv_indptr[-1] + num_blocks) kv_last_page_len = seq_len % block_size if kv_last_page_len == 0: kv_last_page_len = block_size kv_last_page_lens.append(kv_last_page_len) kv_indptr = torch.tensor(kv_indptr, dtype=torch.int32) kv_indices = torch.tensor(kv_indices, dtype=torch.int32) kv_last_page_lens = torch.tensor(kv_last_page_lens, dtype=torch.int32) workspace_buffer = torch.empty(128 * 1024 * 1024, dtype=torch.int8) wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper( workspace_buffer, "NHD", use_tensor_cores=use_tensor_cores ) wrapper.plan( kv_indptr, kv_indices, kv_last_page_lens, num_query_heads, num_kv_heads, head_size, block_size, "NONE", q_data_type=dtype, kv_data_type=kv_cache_dtype, logits_soft_cap=soft_cap, ) output = wrapper.run(query, kv_cache_fp8, k_scale=k_scale, v_scale=v_scale) key_cache = key_value_cache[:, 0, :, :, :].squeeze(1) value_cache = key_value_cache[:, 1, :, :, :].squeeze(1) ref_output = ref_paged_attn( query=query, key_cache=key_cache, value_cache=value_cache, query_lens=[1] * num_seqs, kv_lens=kv_lens, block_tables=block_tables, scale=scale, soft_cap=soft_cap, ) # Temporary fix: Increasing the tolerance. Seems like a flashinfer issue ( torch.testing.assert_close(output, ref_output, atol=2e-2, rtol=1e-2), f"{torch.max(torch.abs(output - ref_output))}", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/conftest.py
tests/kernels/attention/conftest.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.utils.torch_utils import ( create_kv_caches_with_random, create_kv_caches_with_random_flash, ) @pytest.fixture() def kv_cache_factory(): return create_kv_caches_with_random @pytest.fixture() def kv_cache_factory_flashinfer(): return create_kv_caches_with_random_flash
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_deepgemm_attention.py
tests/kernels/attention/test_deepgemm_attention.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import random import pytest import torch from vllm.platforms import current_platform from vllm.utils.deep_gemm import ( _ceil_to_ue8m0, calc_diff, fp8_mqa_logits, fp8_paged_mqa_logits, get_num_sms, get_paged_mqa_logits_metadata, ) from vllm.utils.import_utils import has_deep_gemm from vllm.utils.math_utils import cdiv def kv_cache_cast_to_fp8(x: torch.Tensor) -> torch.Tensor: # x: (num_blocks, block_size, 1, head_dim) num_blocks, block_size, num_heads, head_dim = x.shape assert num_heads == 1 x_amax = x.abs().float().amax(dim=3, keepdim=True).clamp(1e-4) sf = x_amax / 448.0 x_scaled = (x * (1.0 / sf)).to(torch.float8_e4m3fn) x_fp8 = torch.empty( (num_blocks, block_size * (head_dim + 4)), device=x.device, dtype=torch.uint8, ) x_fp8[:, : block_size * head_dim] = x_scaled.view( num_blocks, block_size * head_dim ).view(dtype=torch.uint8) x_fp8[:, block_size * head_dim :] = sf.view(num_blocks, block_size).view( dtype=torch.uint8 ) return x_fp8.view(num_blocks, block_size, num_heads, head_dim + 4) def per_custom_dims_cast_to_fp8( x: torch.Tensor, dims: tuple, use_ue8m0: bool ) -> tuple[torch.Tensor, torch.Tensor]: excluded_dims = tuple([i for i in range(x.dim()) if i not in set(dims)]) x_amax = x.abs().float().amax(dim=excluded_dims, keepdim=True).clamp(1e-4) sf = x_amax / 448.0 sf = _ceil_to_ue8m0(sf) if use_ue8m0 else sf x_scaled = (x * (1.0 / sf)).to(torch.float8_e4m3fn) return x_scaled, sf.squeeze() def _generate_cp_test_data(seq_len: int, seq_len_kv: int): assert seq_len_kv % seq_len == 0 and seq_len % 2 == 0 chunk_size = seq_len // 2 cp_size = seq_len_kv // seq_len cp_id = cp_size // 3 ks = torch.zeros(seq_len, dtype=torch.int, device="cuda") ke = torch.zeros(seq_len, dtype=torch.int, device="cuda") for i in range(chunk_size): ke[i] = cp_id * chunk_size + i ke[i + chunk_size] = (cp_size * 2 - 1 - cp_id) * chunk_size + i return ks, ke def _ref_fp8_mqa_logits( q: torch.Tensor, kv: torch.Tensor, weights: torch.Tensor, cu_seqlen_ks: torch.Tensor, cu_seqlen_ke: torch.Tensor, ): seq_len_kv = kv.shape[0] k = kv q = q.float() k = k.float() mask_lo = ( torch.arange(0, seq_len_kv, device="cuda")[None, :] >= cu_seqlen_ks[:, None] ) mask_hi = ( torch.arange(0, seq_len_kv, device="cuda")[None, :] < cu_seqlen_ke[:, None] ) mask = mask_lo & mask_hi score = torch.einsum("mhd,nd->hmn", q, k) logits = (score.relu() * weights.unsqueeze(-1).transpose(0, 1)).sum(dim=0) logits = logits.masked_fill(~mask, float("-inf")) return logits @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only") @pytest.mark.skipif(not has_deep_gemm(), reason="DeepGEMM not available") @pytest.mark.skipif( not current_platform.has_device_capability(90), reason="SM90 and SM100 only" ) def test_deepgemm_fp8_mqa_logits(): torch.manual_seed(0) random.seed(0) num_heads, head_dim = 32, 128 for seq_len in (512,): for seq_len_kv in (1024,): for disable_cp in (False, True): q = torch.randn( seq_len, num_heads, head_dim, device="cuda", dtype=torch.bfloat16, ) kv = torch.randn( seq_len_kv, head_dim, device="cuda", dtype=torch.bfloat16 ) weights = torch.randn( seq_len, num_heads, device="cuda", dtype=torch.float32 ) if disable_cp: ks = torch.zeros(seq_len, dtype=torch.int, device="cuda") ke = torch.arange(seq_len, dtype=torch.int, device="cuda") + ( seq_len_kv - seq_len ) else: ks, ke = _generate_cp_test_data(seq_len, seq_len_kv) q_fp8 = q.to(torch.float8_e4m3fn) kv_fp8 = per_custom_dims_cast_to_fp8(kv, (0,), False) logits = fp8_mqa_logits(q_fp8, kv_fp8, weights, ks, ke) ref_logits = _ref_fp8_mqa_logits( q=q, kv=kv, weights=weights, cu_seqlen_ks=ks, cu_seqlen_ke=ke, ) ref_neginf_mask = ref_logits == float("-inf") neginf_mask = logits == float("-inf") assert torch.equal(neginf_mask, ref_neginf_mask) ref_logits = ref_logits.masked_fill(ref_neginf_mask, 0) logits = logits.masked_fill(neginf_mask, 0) diff = calc_diff(logits, ref_logits) assert diff < 1e-3, f"{diff=}" def _ref_fp8_paged_mqa_logits( q: torch.Tensor, kv_cache: torch.Tensor, weights: torch.Tensor, context_lens: torch.Tensor, block_tables: torch.Tensor, max_model_len: int, ): batch_size, next_n, _, _ = q.size() _, block_size, _, _ = kv_cache.size() logits = torch.full( [batch_size * next_n, max_model_len], float("-inf"), device=q.device, dtype=torch.float32, ) context_lens_list = context_lens.tolist() for i in range(batch_size): context_len = context_lens_list[i] q_offsets = torch.arange(context_len - next_n, context_len, device="cuda") weight_slice = ( weights[i * next_n : (i + 1) * next_n, :].transpose(0, 1).contiguous() ) for block_rk in range(cdiv(context_len, block_size)): block_idx = block_tables[i][block_rk] qx, kx = q[i], kv_cache[block_idx] k_offsets = torch.arange( block_rk * block_size, (block_rk + 1) * block_size, device="cuda", ) mask = (k_offsets[None, :] < context_len) & ( k_offsets[None, :] <= q_offsets[:, None] ) s = torch.where( mask[None, :, :], (qx.transpose(0, 1) @ kx.transpose(0, 1).transpose(1, 2)).to( logits.dtype ), float("-inf"), ) s = torch.relu(s) * weight_slice[..., None] s = s.sum(dim=0) logits[ i * next_n : (i + 1) * next_n, block_rk * block_size : (block_rk + 1) * block_size, ] = torch.where(k_offsets[None, :] <= q_offsets[:, None], s, float("-inf")) return logits @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only") @pytest.mark.skipif(not has_deep_gemm(), reason="DeepGEMM not available") @pytest.mark.skipif( not current_platform.has_device_capability(90), reason="SM90 and SM100 only" ) def test_deepgemm_fp8_paged_mqa_logits(): torch.manual_seed(0) random.seed(0) max_model_len = 4096 for batch_size, next_n in [(4, 1), (2, 2)]: for heads, index_dim in [(32, 128)]: for avg_kv in (2048,): num_blocks, blocksize = max_model_len * 2, 64 q = torch.randn( (batch_size, next_n, heads, index_dim), device="cuda", dtype=torch.bfloat16, ) kv_cache = torch.randn( (num_blocks, blocksize, 1, index_dim), device="cuda", dtype=torch.bfloat16, ) weights = torch.randn( (batch_size * next_n, heads), device="cuda", dtype=torch.float32, ) context_lens = ( torch.randint(int(0.8 * avg_kv), int(1.2 * avg_kv), (batch_size,)) .cuda() .to(torch.int32) ) max_block_len = ( (context_lens.max().item() + blocksize - 1) // blocksize * blocksize ) block_tables = torch.zeros( (batch_size, max_block_len), device="cuda", dtype=torch.int32, ) counter = 0 block_idx_pool = list(range(num_blocks)) random.shuffle(block_idx_pool) for i in range(batch_size): ctx_len = int(context_lens[i].item()) for j in range((ctx_len + blocksize - 1) // blocksize): block_tables[i][j] = block_idx_pool[counter] counter += 1 q_fp8 = q.to(torch.float8_e4m3fn) kv_cache_fp8 = kv_cache_cast_to_fp8(kv_cache) schedule_metadata = get_paged_mqa_logits_metadata( context_lens, blocksize, get_num_sms() ) logits = fp8_paged_mqa_logits( q_fp8, kv_cache_fp8, weights, context_lens, block_tables, schedule_metadata, max_model_len, ) ref_logits = _ref_fp8_paged_mqa_logits( q, kv_cache, weights, context_lens, block_tables, max_model_len, ) positions = ( torch.arange(max_model_len, device="cuda") .unsqueeze(0) .expand(batch_size * next_n, -1) ) row_indices = torch.arange(batch_size * next_n, device="cuda") // next_n next_n_offset = ( torch.arange(batch_size * next_n, device="cuda") % next_n ) mask = positions <= ( context_lens[row_indices] - next_n + next_n_offset ).unsqueeze(1) logits = logits.masked_fill(~mask, 0) ref_logits = ref_logits.masked_fill(~mask, 0) diff = calc_diff(logits, ref_logits) assert diff < 1e-3, f"{diff=}"
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_flashmla.py
tests/kernels/attention/test_flashmla.py
# Adapted from: https://github.com/deepseek-ai/FlashMLA/blob/main/tests/test_flash_mla.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import math import random import pytest import torch from vllm.attention.ops.flashmla import ( flash_mla_with_kvcache, get_mla_metadata, is_flashmla_dense_supported, ) from vllm.triton_utils import triton def cal_diff( x: torch.Tensor, y: torch.Tensor, name: str, use_fp8: bool = False ) -> None: x, y = x.double(), y.double() cos_diff = 1 - 2 * (x * y).sum().item() / max((x * x + y * y).sum().item(), 1e-12) if use_fp8: assert cos_diff < 1e-4 else: assert cos_diff < 1e-5 FLASH_MLA_UNSUPPORTED_REASON = ( is_flashmla_dense_supported()[1] if not is_flashmla_dense_supported()[0] else "FlashMLA is supported" ) @pytest.mark.skipif( not is_flashmla_dense_supported()[0], reason=FLASH_MLA_UNSUPPORTED_REASON ) @pytest.mark.parametrize("b", [128]) @pytest.mark.parametrize("s_q", [1, 2]) @pytest.mark.parametrize("mean_sk", [4096, 8192, 16384]) @pytest.mark.parametrize("h_q", [16, 32, 64, 128]) @pytest.mark.parametrize("h_kv", [1]) @pytest.mark.parametrize("d", [576]) @pytest.mark.parametrize("dv", [512]) @pytest.mark.parametrize("block_size", [64]) @pytest.mark.parametrize("causal", [True]) @pytest.mark.parametrize("varlen", [False, True]) @pytest.mark.parametrize( "torch_dtype", [torch.bfloat16, torch.float16, torch.float8_e4m3fn] ) @torch.inference_mode() def test_flash_mla( b, s_q, mean_sk, h_q, h_kv, d, dv, block_size, causal, varlen, torch_dtype ): device = torch.device("cuda:0") init_dtype = torch.bfloat16 if torch_dtype == torch.float8_e4m3fn else torch_dtype torch.set_default_dtype(init_dtype) torch.set_default_device(device) torch.cuda.set_device(device) torch.manual_seed(0) random.seed(0) print( f"{b=}, {s_q=}, {mean_sk=}, {h_q=}, {h_kv=}, " f"{d=}, {dv=}, {causal=}, {varlen=}, {torch_dtype=}" ) use_fp8 = torch_dtype == torch.float8_e4m3fn cache_seqlens = torch.full((b,), mean_sk, dtype=torch.int32) if varlen: for i in range(b): cache_seqlens[i] = max(random.normalvariate(mean_sk, mean_sk / 2), s_q) total_seqlens = cache_seqlens.sum().item() max_seqlen = cache_seqlens.max().item() max_seqlen_pad = triton.cdiv(max_seqlen, 256) * 256 q = torch.randn(b, s_q, h_q, d) block_table = torch.arange( b * max_seqlen_pad // block_size, dtype=torch.int32 ).view(b, max_seqlen_pad // block_size) blocked_k = torch.randn(block_table.numel(), block_size, h_kv, d) for i in range(b): blocked_k.view(b, max_seqlen_pad, h_kv, d)[i, cache_seqlens[i].item() :] = ( float("nan") ) blocked_v = blocked_k[..., :dv] tile_scheduler_metadata, num_splits = get_mla_metadata( cache_seqlens, s_q * h_q // h_kv, h_kv ) init_dtype = q.dtype if use_fp8: fp8_dtype = torch.float8_e4m3fn descale_q = torch.ones((1), dtype=torch.float32) descale_k = torch.ones((1), dtype=torch.float32) q = q.to(fp8_dtype) blocked_k = blocked_k.to(fp8_dtype) blocked_v = blocked_v.to(fp8_dtype) else: descale_q = None descale_k = None def flash_mla(): return flash_mla_with_kvcache( q, blocked_k, block_table, cache_seqlens, dv, tile_scheduler_metadata, num_splits, causal=causal, descale_q=descale_q, descale_k=descale_k, ) def scaled_dot_product_attention(query, key, value, is_causal=False): query = query.float() key = key.float() value = value.float() key = key.repeat_interleave(h_q // h_kv, dim=0) value = value.repeat_interleave(h_q // h_kv, dim=0) attn_weight = query @ key.transpose(-2, -1) / math.sqrt(query.size(-1)) if is_causal: s_q = query.shape[-2] s_k = key.shape[-2] attn_bias = torch.zeros(s_q, s_k, dtype=query.dtype) temp_mask = torch.ones(s_q, s_k, dtype=torch.bool).tril(diagonal=s_k - s_q) attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf")) attn_bias.to(query.dtype) attn_weight += attn_bias lse = attn_weight.logsumexp(dim=-1) attn_weight = torch.softmax(attn_weight, dim=-1, dtype=torch.float32) return attn_weight @ value, lse def ref_mla(): q_ = (q.to(torch.float) * descale_q).to(init_dtype) if use_fp8 else q blocked_k_ = ( (blocked_k.to(torch.float) * descale_k).to(init_dtype) if use_fp8 else blocked_k ) blocked_v_ = ( (blocked_v.to(torch.float) * descale_k).to(init_dtype) if use_fp8 else blocked_v ) out = torch.empty(b, s_q, h_q, dv, dtype=torch.float32) lse = torch.empty(b, h_q, s_q, dtype=torch.float32) for i in range(b): begin = i * max_seqlen_pad end = begin + cache_seqlens[i] out_i, lse_i = scaled_dot_product_attention( q_[i].transpose(0, 1), blocked_k_.view(-1, h_kv, d)[begin:end].transpose(0, 1), blocked_v_.view(-1, h_kv, dv)[begin:end].transpose(0, 1), is_causal=causal, ) out[i] = out_i.transpose(0, 1) lse[i] = lse_i return out, lse out_flash, lse_flash = flash_mla() out_torch, lse_torch = ref_mla() cal_diff(out_flash, out_torch, "out", use_fp8) cal_diff(lse_flash, lse_torch, "lse") t = triton.testing.do_bench(flash_mla) FLOPS = s_q * total_seqlens * h_q * (d + dv) * 2 bytes = (total_seqlens * h_kv * d + b * s_q * h_q * d) * ( torch.finfo(torch_dtype).bits // 8 ) + (b * s_q * h_q * dv) * (torch.finfo(init_dtype).bits // 8) print( f"{t:.3f} ms, {FLOPS / 10**9 / t:.0f} TFLOPS,", f"{bytes / 10**6 / t:.0f} GB/s" )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_triton_unified_attention.py
tests/kernels/attention/test_triton_unified_attention.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.attention.ops.triton_unified_attention import unified_attention from vllm.platforms import current_platform from vllm.utils.math_utils import next_power_of_2 NUM_HEADS = [(4, 4), (8, 2)] HEAD_SIZES = [128, 256] BLOCK_SIZES = [16] DTYPES = [torch.bfloat16] QDTYPES = ( [None, torch.float8_e4m3fn] if not current_platform.is_rocm() else [None, torch.float8_e4m3fnuz] ) # one value large enough to test overflow in index calculation. # one value small enough to test the schema op check NUM_BLOCKS = [32768, 2048] # 0: use 2D kernel for decode # 8: use 3D kernel for decode SEQ_THRESHOLD_3D_VALUES = [0, 8] def ref_paged_attn( query: torch.Tensor, key_cache: torch.Tensor, value_cache: torch.Tensor, query_lens: list[int], kv_lens: list[int], block_tables: torch.Tensor, scale: float, sliding_window: int | None = None, soft_cap: float | None = None, ) -> torch.Tensor: num_seqs = len(query_lens) block_tables = block_tables.cpu().numpy() _, block_size, num_kv_heads, head_size = key_cache.shape outputs: list[torch.Tensor] = [] start_idx = 0 for i in range(num_seqs): query_len = query_lens[i] kv_len = kv_lens[i] q = query[start_idx : start_idx + query_len] q *= scale num_kv_blocks = (kv_len + block_size - 1) // block_size block_indices = block_tables[i, :num_kv_blocks] k = key_cache[block_indices].view(-1, num_kv_heads, head_size) k = k[:kv_len] v = value_cache[block_indices].view(-1, num_kv_heads, head_size) v = v[:kv_len] if q.shape[1] != k.shape[1]: k = torch.repeat_interleave(k, q.shape[1] // k.shape[1], dim=1) v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1) attn = torch.einsum("qhd,khd->hqk", q, k).float() empty_mask = torch.ones(query_len, kv_len) mask = torch.triu(empty_mask, diagonal=kv_len - query_len + 1).bool() if sliding_window is not None: sliding_window_mask = ( torch.triu( empty_mask, diagonal=kv_len - (query_len + sliding_window) + 1 ) .bool() .logical_not() ) mask |= sliding_window_mask if soft_cap is not None and soft_cap > 0: attn = soft_cap * torch.tanh(attn / soft_cap) attn.masked_fill_(mask, float("-inf")) attn = torch.softmax(attn, dim=-1).to(v.dtype) out = torch.einsum("hqk,khd->qhd", attn, v) outputs.append(out) start_idx += query_len return torch.cat(outputs, dim=0) @pytest.mark.parametrize( "seq_lens", [[(1, 1328), (5, 18), (129, 463)], [(1, 523), (1, 37), (1, 2011)]] ) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("sliding_window", [None, 64, 128, 256]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("soft_cap", [None, 50.0]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("q_dtype", QDTYPES) @pytest.mark.parametrize("seq_threshold_3D", SEQ_THRESHOLD_3D_VALUES) @torch.inference_mode() def test_triton_unified_attn( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, q_dtype: torch.dtype | None, seq_threshold_3D: int, ) -> None: torch.set_default_device("cuda") current_platform.seed_everything(0) num_seqs = len(seq_lens) query_lens = [x[0] for x in seq_lens] kv_lens = [x[1] for x in seq_lens] num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_query_len = max(query_lens) max_kv_len = max(kv_lens) window_size = (sliding_window - 1, 0) if sliding_window is not None else (-1, -1) scale = head_size**-0.5 query = torch.randn(sum(query_lens), num_query_heads, head_size, dtype=dtype) key_cache = torch.randn( num_blocks, block_size, num_kv_heads, head_size, dtype=dtype ) value_cache = torch.randn_like(key_cache) cu_query_lens = torch.tensor([0] + query_lens, dtype=torch.int32).cumsum( dim=0, dtype=torch.int32 ) kv_lens = torch.tensor(kv_lens, dtype=torch.int32) max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, num_blocks, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) output = torch.empty_like(query) maybe_quantized_query = query maybe_quantized_key_cache = key_cache maybe_quantized_value_cache = value_cache q_descale = None k_descale = None v_descale = None if q_dtype is not None: # QKV are drawn from N(0, 1): no need for a fp8 scaling factor maybe_quantized_query = query.to(q_dtype) maybe_quantized_key_cache = key_cache.to(q_dtype) maybe_quantized_value_cache = value_cache.to(q_dtype) scale_shape = (num_seqs, num_kv_heads) q_descale = None # Not yet supported k_descale = torch.rand(scale_shape, dtype=torch.float32) v_descale = torch.rand(scale_shape, dtype=torch.float32) num_par_softmax_segments = 16 head_size_padded = next_power_of_2(head_size) softmax_segm_output = torch.empty( (seq_threshold_3D, num_query_heads, num_par_softmax_segments, head_size_padded), dtype=torch.float32, ) softmax_segm_max = torch.empty( (seq_threshold_3D, num_query_heads, num_par_softmax_segments), dtype=torch.float32, ) softmax_segm_expsum = torch.empty( (seq_threshold_3D, num_query_heads, num_par_softmax_segments), dtype=torch.float32, ) unified_attention( q=maybe_quantized_query, k=maybe_quantized_key_cache, v=maybe_quantized_value_cache, out=output, cu_seqlens_q=cu_query_lens, seqused_k=kv_lens, max_seqlen_q=max_query_len, max_seqlen_k=max_kv_len, softmax_scale=scale, causal=True, window_size=window_size, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, q_descale=q_descale, k_descale=k_descale, v_descale=v_descale, seq_threshold_3D=seq_threshold_3D, num_par_softmax_segments=num_par_softmax_segments, softmax_segm_output=softmax_segm_output, softmax_segm_max=softmax_segm_max, softmax_segm_expsum=softmax_segm_expsum, ) ref_output = ref_paged_attn( query=query, key_cache=key_cache, value_cache=value_cache, query_lens=query_lens, kv_lens=kv_lens, block_tables=block_tables, scale=scale, sliding_window=sliding_window, soft_cap=soft_cap, ) atol, rtol = 1.5e-2, 1e-2 if q_dtype is not None: atol, rtol = 1.5e-1, 1.5e-1 ( torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol), f"{torch.max(torch.abs(output - ref_output))}", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_attention.py
tests/kernels/attention/test_attention.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import random import pytest import torch from tests.kernels.allclose_default import get_default_atol, get_default_rtol from tests.kernels.utils import opcheck from vllm import _custom_ops as ops from vllm.attention.layer import Attention from vllm.attention.layers.mm_encoder_attention import MMEncoderAttention from vllm.platforms import current_platform from vllm.utils.mem_utils import get_max_shared_memory_bytes FLOAT32_BYTES = torch.finfo(torch.float).bits // 8 # This will change depending on the compute capability. # - 512 as a buffer MAX_SEQ_LEN = get_max_shared_memory_bytes() // FLOAT32_BYTES - 512 # There may not be enough gpu memory due to large NUM_BLOCKS. # Reduce NUM_BLOCKS when it happens. NUM_BLOCKS = 4321 # Arbitrary values for testing PARTITION_SIZE = 512 PARTITION_SIZE_ROCM = 256 DTYPES = [torch.bfloat16] NUM_GEN_SEQS = [7] # Arbitrary values for testing NUM_PREFILL_SEQS = [3] # Arbitrary values for testing NUM_HEADS = [(40, 40), (64, 8)] # Arbitrary values for testing # This should be sync with get_supported_head_sizes() in # vllm.attention.ops.paged_attn.PagedAttention HEAD_SIZES = [32, 80, 128, 256] BLOCK_SIZES = [16, 32] USE_ALIBI = [False, True] KV_CACHE_DTYPE = ["auto", "fp8"] SEEDS = [0] CUDA_DEVICES = [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)] def ref_masked_attention( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, scale: float, attn_mask: torch.Tensor | None = None, ) -> torch.Tensor: attn_weights = scale * torch.einsum("qhd,khd->hqk", query, key).float() if attn_mask is not None: attn_weights = attn_weights + attn_mask.float() attn_weights = torch.softmax(attn_weights, dim=-1).to(value.dtype) out = torch.einsum("hqk,khd->qhd", attn_weights, value) return out def ref_single_query_cached_kv_attention( output: torch.Tensor, query: torch.Tensor, num_queries_per_kv: int, key_cache: torch.Tensor, value_cache: torch.Tensor, block_tables: torch.Tensor, seq_lens: torch.Tensor, scale: float, alibi_slopes: torch.Tensor | None, ) -> None: num_query_heads = query.shape[1] num_kv_heads = value_cache.shape[1] head_size = value_cache.shape[2] block_size = value_cache.shape[3] num_seqs = query.shape[0] block_tables_lst = block_tables.cpu().tolist() seq_lens_lst = seq_lens.cpu().tolist() for i in range(num_seqs): q = query[i].unsqueeze(0) block_table = block_tables_lst[i] seq_len = int(seq_lens_lst[i]) keys_lst: list[torch.Tensor] = [] values_lst: list[torch.Tensor] = [] for j in range(seq_len): block_number = int(block_table[j // block_size]) block_offset = j % block_size k = key_cache[block_number, :, :, block_offset, :] k = k.reshape(num_kv_heads, head_size) keys_lst.append(k) v = value_cache[block_number, :, :, block_offset] values_lst.append(v) keys = torch.stack(keys_lst, dim=0) values = torch.stack(values_lst, dim=0) if num_queries_per_kv > 1: # Handle MQA and GQA keys = torch.repeat_interleave(keys, num_queries_per_kv, dim=1) values = torch.repeat_interleave(values, num_queries_per_kv, dim=1) alibi_bias = None if alibi_slopes is not None: # Create the ALiBi bias used in the paged attention kernel. position_ids = torch.arange(seq_len).int() alibi_bias = (position_ids - seq_len + 1).float() alibi_bias = alibi_slopes.view(-1, 1, 1) * alibi_bias.view(1, 1, -1) out = ref_masked_attention(q, keys, values, scale, alibi_bias) out = out.view(num_query_heads, head_size) output[i].copy_(out, non_blocking=True) @pytest.mark.parametrize( "version", ["v1", "v2"] if not current_platform.is_rocm() else ["v1", "v2", "rocm"] ) @pytest.mark.parametrize("num_seqs", NUM_GEN_SEQS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("use_alibi", USE_ALIBI) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) def test_paged_attention( kv_cache_factory, version: str, num_seqs: int, num_heads: tuple[int, int], head_size: int, use_alibi: bool, block_size: int, dtype: torch.dtype, kv_cache_dtype: str, seed: int, device: str, ) -> None: if (kv_cache_dtype == "fp8" and head_size % 16) or ( version == "rocm" and head_size not in (64, 128) ): pytest.skip() if ( version == "rocm" and current_platform.is_navi() and ( kv_cache_dtype == "fp8" or head_size != 128 or block_size != 16 or use_alibi ) ): pytest.skip() global PARTITION_SIZE current_platform.seed_everything(seed) torch.set_default_device(device) scale = float(1.0 / (head_size**0.5)) num_query_heads, num_kv_heads = num_heads query = torch.empty(num_seqs, num_query_heads, head_size, dtype=dtype) query.uniform_(-scale, scale) assert num_query_heads % num_kv_heads == 0 num_queries_per_kv = num_query_heads // num_kv_heads alibi_slopes = None if use_alibi: alibi_slopes = torch.randn(num_query_heads, dtype=torch.float) seq_lens = [random.randint(1, MAX_SEQ_LEN) for _ in range(num_seqs)] seq_lens[-1] = MAX_SEQ_LEN max_seq_len = max(seq_lens) seq_lens = torch.tensor(seq_lens, dtype=torch.int) # Create the block tables. max_num_blocks_per_seq = (max_seq_len + block_size - 1) // block_size block_tables_lst: list[list[int]] = [] for _ in range(num_seqs): block_table = [ random.randint(0, NUM_BLOCKS - 1) for _ in range(max_num_blocks_per_seq) ] block_tables_lst.append(block_table) block_tables = torch.tensor(block_tables_lst, dtype=torch.int) # Create the KV caches. key_caches, value_caches = kv_cache_factory( NUM_BLOCKS, block_size, 1, num_kv_heads, head_size, kv_cache_dtype, dtype, seed, device, ) key_cache, value_cache = key_caches[0], value_caches[0] # Using default kv_scale k_scale = v_scale = torch.tensor(1.0, dtype=torch.float32, device=device) # Call the paged attention kernel. output = torch.empty_like(query) if version == "v1": ops.paged_attention_v1( output, query, key_cache, value_cache, num_kv_heads, scale, block_tables, seq_lens, block_size, max_seq_len, alibi_slopes, kv_cache_dtype, k_scale, v_scale, ) opcheck( torch.ops._C.paged_attention_v1, ( output, query, key_cache, value_cache, num_kv_heads, scale, block_tables, seq_lens, block_size, max_seq_len, alibi_slopes, kv_cache_dtype, k_scale, v_scale, 0, 0, 0, 64, 0, ), cond=(head_size == HEAD_SIZES[0] and block_size == BLOCK_SIZES[0]), ) elif version in ("v2", "rocm"): if current_platform.is_rocm() and version == "rocm": PARTITION_SIZE = PARTITION_SIZE_ROCM num_partitions = (max_seq_len + PARTITION_SIZE - 1) // PARTITION_SIZE assert PARTITION_SIZE % block_size == 0 num_seqs, num_heads, head_size = output.shape tmp_output = torch.empty( size=(num_seqs, num_heads, num_partitions, head_size), dtype=output.dtype, ) exp_sums = torch.empty( size=(num_seqs, num_heads, num_partitions), dtype=torch.float32, ) max_logits = torch.empty_like(exp_sums) if version == "v2": ops.paged_attention_v2( output, exp_sums, max_logits, tmp_output, query, key_cache, value_cache, num_kv_heads, scale, block_tables, seq_lens, block_size, max_seq_len, alibi_slopes, kv_cache_dtype, k_scale, v_scale, ) opcheck( torch.ops._C.paged_attention_v2, ( output, exp_sums, max_logits, tmp_output, query, key_cache, value_cache, num_kv_heads, scale, block_tables, seq_lens, block_size, max_seq_len, alibi_slopes, kv_cache_dtype, k_scale, v_scale, 0, 0, 0, 64, 0, ), cond=(head_size == HEAD_SIZES[0] and block_size == BLOCK_SIZES[0]), ) else: ops.paged_attention_rocm( output, exp_sums, max_logits, tmp_output, query, key_cache, value_cache, num_kv_heads, scale, block_tables, seq_lens, None, block_size, max_seq_len, alibi_slopes, kv_cache_dtype, k_scale, v_scale, ) opcheck( torch.ops._rocm_C.paged_attention, ( output, exp_sums, max_logits, tmp_output, query, key_cache, value_cache, num_kv_heads, scale, block_tables, seq_lens, None, block_size, max_seq_len, alibi_slopes, kv_cache_dtype, k_scale, v_scale, ), cond=(head_size == HEAD_SIZES[0] and block_size == BLOCK_SIZES[0]), ) else: raise AssertionError(f"Unknown version: {version}") # Run the reference implementation. if kv_cache_dtype == "fp8": # Convert cache data back to dtype. x = 16 // torch.tensor([], dtype=dtype).element_size() key_cache_shape = (NUM_BLOCKS, num_kv_heads, head_size // x, block_size, x) dequantized_key_cache = torch.empty( size=key_cache_shape, dtype=dtype, device=device ) ops.convert_fp8(dequantized_key_cache, key_cache) key_cache = dequantized_key_cache value_cache_shape = value_cache.shape dequantized_value_cache = torch.empty( size=value_cache_shape, dtype=dtype, device=device ) ops.convert_fp8(dequantized_value_cache, value_cache) value_cache = dequantized_value_cache ref_output = torch.empty_like(query) ref_single_query_cached_kv_attention( ref_output, query, num_queries_per_kv, key_cache, value_cache, block_tables, seq_lens, scale, alibi_slopes, ) # NOTE(woosuk): Due to the kernel-level differences in the two # implementations, there is a small numerical difference in the two # outputs. Thus, we use a relaxed tolerance for the test. atol = get_default_atol(output) if current_platform.is_rocm() else 1e-3 rtol = get_default_rtol(output) if current_platform.is_rocm() else 1e-5 # NOTE(zhaoyang): FP8 KV Cache will introduce quantization error, # so we use a relaxed tolerance for the test. atol, rtol = 1e-3, 1e-5 if kv_cache_dtype == "fp8": atol, rtol = 1e-2, 1e-5 torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol) def ref_multi_query_kv_attention( cu_seq_lens: list[int], query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, scale: float, alibi_bias: list[torch.Tensor] | None, dtype: torch.dtype, ) -> torch.Tensor: num_seqs = len(cu_seq_lens) - 1 ref_outputs: list[torch.Tensor] = [] if alibi_bias: assert len(alibi_bias) == num_seqs for i in range(num_seqs): start_idx = cu_seq_lens[i] end_idx = cu_seq_lens[i + 1] seq_len = end_idx - start_idx # Create attention mask. ALiBi already includes a tril causal mask. if alibi_bias: attn_mask = alibi_bias[i] else: attn_mask = torch.triu( torch.ones(seq_len, seq_len, dtype=dtype), diagonal=1 ) attn_mask = attn_mask * torch.finfo(dtype).min attn_mask = attn_mask.to(dtype=dtype) ref_output = ref_masked_attention( query[start_idx:end_idx], key[start_idx:end_idx], value[start_idx:end_idx], scale, attn_mask=attn_mask, ) ref_outputs.append(ref_output) return torch.cat(ref_outputs, dim=0) @pytest.mark.parametrize("attention_cls", [Attention, MMEncoderAttention]) def test_num_heads_not_divisble_by_num_kv_heads(attention_cls: type) -> None: head_size = 64 scale = float(1.0 / (head_size**0.5)) num_heads = 16 num_kv_heads = 5 with pytest.raises(AssertionError): _ = attention_cls( num_heads=num_heads, head_size=head_size, scale=scale, num_kv_heads=num_kv_heads, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_attention_selector.py
tests/kernels/attention/test_attention_selector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from unittest.mock import patch import pytest import torch from vllm.attention.backends.registry import AttentionBackendEnum from vllm.attention.selector import _cached_get_attn_backend, get_attn_backend from vllm.config import AttentionConfig, VllmConfig, set_current_vllm_config from vllm.platforms import current_platform from vllm.platforms.cpu import CpuPlatform from vllm.platforms.cuda import CudaPlatform from vllm.platforms.rocm import RocmPlatform @pytest.fixture(autouse=True) def clear_cache(): """Clear lru cache to ensure each test case runs without caching.""" _cached_get_attn_backend.cache_clear() # Define MLA and non-MLA backends separately DEVICE_MLA_BACKENDS = { "cuda": [ "TRITON_MLA", "FLASHMLA", "FLASHINFER_MLA", "FLASH_ATTN_MLA", "CUTLASS_MLA", ], "hip": ["TRITON_MLA", "ROCM_AITER_MLA"], "cpu": [], } DEVICE_REGULAR_ATTN_BACKENDS = { "cuda": ["FLASHINFER", "FLASH_ATTN"], "hip": ["ROCM_ATTN"], "cpu": ["CPU_ATTN"], } DEVICE_MLA_BLOCK_SIZES = { "cuda": [16, 64], # CUDA supports both standard and extended block sizes "hip": [16, 1], # HIP requires special handling for block_size=1 # "cpu": [16] # CPU uses fixed block size from test cases "cpu": [], # FIXME(woosuk): Temporarily disable CPU tests } def generate_params(): is_rocm = current_platform.is_rocm() params = [] device_list = ["cuda", "cpu"] if not is_rocm else ["hip", "cpu"] for use_mla in [True, False]: for device in device_list: backends = ( DEVICE_MLA_BACKENDS[device] if use_mla else DEVICE_REGULAR_ATTN_BACKENDS[device] ) for name in backends: block_sizes = DEVICE_MLA_BLOCK_SIZES[device] if use_mla else [16] for block_size in block_sizes: params.append( pytest.param( device, name, use_mla, block_size, id=f"{device}_{name}_mla_{str(use_mla)[0]}_blks{block_size}", ) ) return params @pytest.mark.parametrize("device, name, use_mla, block_size", generate_params()) def test_backend_selection( device: str, name: str, use_mla: bool, block_size: int, ): """Test attention backend selection with valid device-backend pairs.""" # Create AttentionConfig with the specified backend attention_config = AttentionConfig(backend=AttentionBackendEnum[name]) vllm_config = VllmConfig(attention_config=attention_config) with set_current_vllm_config(vllm_config): if device == "cpu": with patch("vllm.platforms.current_platform", CpuPlatform()): backend = get_attn_backend(16, torch.float16, None, block_size) assert backend.get_name() == "CPU_ATTN" elif device == "hip": with patch("vllm.platforms.current_platform", RocmPlatform()): if use_mla: # ROCm MLA backend logic: # - TRITON_MLA: supported when block_size != 1 # - ROCM_AITER_MLA: supported when block_size == 1 # If backend is forced but doesn't match block_size, # should raise ValueError if name == "TRITON_MLA" and block_size == 1: # TRITON_MLA doesn't support block_size == 1 with pytest.raises(ValueError) as exc_info: get_attn_backend( 16, torch.float16, None, block_size, use_mla=use_mla ) assert f"The selected backend, {name}" in str(exc_info.value) else: # Valid backend-block_size combination backend = get_attn_backend( 16, torch.float16, None, block_size, use_mla=use_mla ) expected = name assert backend.get_name() == expected else: backend = get_attn_backend( 16, torch.float16, None, block_size, use_mla=use_mla ) expected = "ROCM_ATTN" assert backend.get_name() == expected elif device == "cuda": with patch("vllm.platforms.current_platform", CudaPlatform()): capability = torch.cuda.get_device_capability() if use_mla: # CUDA MLA backend logic: # - CUTLASS_MLA: only supported with block_size == 128 # and Blackwell GPUs (SM 10.x), V1 only # - FLASHINFER_MLA: only supported on Blackwell GPUs # (SM 10.x), V1 only # - FLASHMLA: only supported with block_size == 64 # - FLASH_ATTN_MLA: V1 only # - TRITON_MLA: fallback for other cases if name == "CUTLASS_MLA": if block_size != 128: # CUTLASS_MLA only supports block_size == 128 pytest.skip("CUTLASS_MLA only supports block_size 128") if capability[0] != 10: pytest.skip("CUTLASS MLA is not supported on this platform") backend = get_attn_backend( 576, torch.float16, None, block_size, use_mla=use_mla ) expected = "CUTLASS_MLA" assert backend.get_name() == expected elif name == "FLASHINFER_MLA": if capability[0] != 10: pytest.skip( "FlashInfer MLA is not supported on this platform" ) if block_size not in [32, 64]: # FlashInfer MLA only supports block_size 32 or 64 pytest.skip( "FlashInfer MLA only supports block_size 32 or 64" ) backend = get_attn_backend( 576, torch.float16, None, block_size, use_mla=use_mla ) expected = "FLASHINFER_MLA" assert backend.get_name() == expected elif name == "FLASHMLA": if block_size != 64: # FlashMLA only supports block_size == 64 pytest.skip("FlashMLA only supports block_size 64") from vllm.v1.attention.backends.mla.flashmla import ( is_flashmla_dense_supported, ) is_supported, _ = is_flashmla_dense_supported() if not is_supported: pytest.skip("FlashMLA not supported on this platform") backend = get_attn_backend( 576, torch.float16, None, block_size, use_mla=use_mla, ) expected = name assert backend.get_name() == expected elif name == "FLASH_ATTN_MLA": from vllm.attention.utils.fa_utils import ( flash_attn_supports_mla, ) if not flash_attn_supports_mla(): pytest.skip( "FlashAttention MLA not supported on this platform" ) backend = get_attn_backend( 576, torch.float16, None, block_size, use_mla=use_mla ) expected = "FLASH_ATTN_MLA" assert backend.get_name() == expected else: # TRITON_MLA or other fallback backend = get_attn_backend( 576, torch.float16, None, block_size, use_mla=use_mla ) expected = "TRITON_MLA" assert backend.get_name() == expected elif name == "FLASHINFER": backend = get_attn_backend( 64, torch.float16, None, block_size, use_mla=use_mla ) expected = "FLASHINFER" assert backend.get_name() == expected elif name == "FLASH_ATTN": backend = get_attn_backend( 32, torch.float16, None, block_size, use_mla=use_mla ) expected = "FLASH_ATTN" assert backend.get_name() == expected @pytest.mark.parametrize("device", ["cpu", "cuda"]) def test_fp32_fallback(device: str): """Test attention backend selection with fp32.""" # Use default config (no backend specified) vllm_config = VllmConfig() with set_current_vllm_config(vllm_config): if device == "cpu": with patch("vllm.platforms.current_platform", CpuPlatform()): backend = get_attn_backend(16, torch.float32, None, 16) assert backend.get_name() == "CPU_ATTN" elif device == "cuda": with patch("vllm.platforms.current_platform", CudaPlatform()): backend = get_attn_backend(16, torch.float32, None, 16) assert backend.get_name() == "FLEX_ATTENTION" def test_flash_attn(monkeypatch: pytest.MonkeyPatch): """Test FlashAttn validation.""" pytest.skip( "Skipping as current backend selector does not " "handle fallbacks when a backend is explicitly set." ) attention_config = AttentionConfig(backend=AttentionBackendEnum.FLASH_ATTN) vllm_config = VllmConfig(attention_config=attention_config) with set_current_vllm_config(vllm_config): # Unsupported CUDA arch monkeypatch.setattr(torch.cuda, "get_device_capability", lambda _=None: (7, 5)) backend = get_attn_backend(16, torch.float16, None, 16) assert backend.get_name() != "FLASH_ATTN" # Reset the monkeypatch for subsequent tests monkeypatch.undo() # Unsupported data type backend = get_attn_backend(16, torch.float8_e4m3fn, None, 16) assert backend.get_name() != "FLASH_ATTN" # Unsupported kv cache data type backend = get_attn_backend(16, torch.float16, "fp8", 16) assert backend.get_name() != "FLASH_ATTN" # Unsupported block size backend = get_attn_backend(16, torch.float16, None, 8) assert backend.get_name() != "FLASH_ATTN" # flash-attn is not installed import sys original_module = sys.modules.get("vllm_flash_attn") monkeypatch.setitem(sys.modules, "vllm_flash_attn", None) backend = get_attn_backend(16, torch.float16, None, 16) assert backend.get_name() != "FLASH_ATTN" # Restore the original module if it existed if original_module is not None: monkeypatch.setitem(sys.modules, "vllm_flash_attn", original_module) else: monkeypatch.delitem(sys.modules, "vllm_flash_attn", raising=False) # Unsupported head size backend = get_attn_backend(17, torch.float16, None, 16) assert backend.get_name() != "FLASH_ATTN" def test_invalid_backend(): """Test that invalid attention backend names raise ValueError.""" with ( pytest.raises(ValueError), ): # Invalid backend name should raise ValueError when creating enum AttentionConfig(backend=AttentionBackendEnum["INVALID"])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_rocm_attention_selector.py
tests/kernels/attention/test_rocm_attention_selector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.attention.backends.registry import AttentionBackendEnum from vllm.attention.selector import _cached_get_attn_backend, get_attn_backend from vllm.config import AttentionConfig, VllmConfig, set_current_vllm_config from vllm.platforms.rocm import RocmPlatform @pytest.fixture(autouse=True) def clear_cache(): """Clear lru cache to ensure each test case runs without caching.""" _cached_get_attn_backend.cache_clear() @pytest.mark.skip(reason="Skipped for now. Should be revisited.") def test_selector(monkeypatch: pytest.MonkeyPatch): # Set the current platform to ROCm using monkeypatch monkeypatch.setattr("vllm.attention.selector.current_platform", RocmPlatform()) # Test standard ROCm attention attention_config = AttentionConfig(backend=AttentionBackendEnum.ROCM_ATTN) vllm_config = VllmConfig(attention_config=attention_config) with set_current_vllm_config(vllm_config): backend = get_attn_backend(16, torch.float16, torch.float16, 16, False) assert backend.get_name() == "ROCM_FLASH" or backend.get_name() == "TRITON_ATTN" # MLA test for deepseek related # Change the attention backend to triton MLA attention_config = AttentionConfig(backend=AttentionBackendEnum.TRITON_MLA) vllm_config = VllmConfig(attention_config=attention_config) with set_current_vllm_config(vllm_config): backend = get_attn_backend(576, torch.bfloat16, "auto", 16, False, use_mla=True) assert backend.get_name() == "TRITON_MLA" # If attention backend is None # If use_mla is true # The selected backend is triton MLA attention_config = AttentionConfig(backend=None) vllm_config = VllmConfig(attention_config=attention_config) with set_current_vllm_config(vllm_config): backend = get_attn_backend(576, torch.bfloat16, "auto", 16, False, use_mla=True) assert backend.get_name() == "TRITON_MLA" # Change the attention backend to AITER MLA attention_config = AttentionConfig(backend=AttentionBackendEnum.ROCM_AITER_MLA) vllm_config = VllmConfig(attention_config=attention_config) with set_current_vllm_config(vllm_config): backend = get_attn_backend(576, torch.bfloat16, "auto", 1, False, use_mla=True) assert backend.get_name() == "ROCM_AITER_MLA" # If attention backend is None # If use_mla is true # If VLLM_ROCM_USE_AITER is enabled # The selected backend is ROCM_AITER_MLA with monkeypatch.context() as m: m.setenv("VLLM_ROCM_USE_AITER", "1") attention_config = AttentionConfig(backend=None) vllm_config = VllmConfig(attention_config=attention_config) with set_current_vllm_config(vllm_config): backend = get_attn_backend( 576, torch.bfloat16, "auto", 1, False, use_mla=True ) assert backend.get_name() == "ROCM_AITER_MLA"
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_flashmla_sparse.py
tests/kernels/attention/test_flashmla_sparse.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch def test_sparse_flashmla_metadata_smoke(): import vllm.attention.ops.flashmla as fm ok, reason = fm.is_flashmla_sparse_supported() if not ok: pytest.skip(reason) device = torch.device("cuda") batch_size = 1 seqlen_q = 1 num_heads_q = 128 num_heads_k = 1 q_seq_per_hk = seqlen_q * num_heads_q // num_heads_k topk = 128 cache_seqlens = torch.zeros(batch_size, dtype=torch.int32, device=device) tile_md, num_splits = fm.get_mla_metadata( cache_seqlens, q_seq_per_hk, num_heads_k, num_heads_q=num_heads_q, topk=topk, is_fp8_kvcache=True, ) assert tile_md.dtype == torch.int32 assert num_splits.dtype == torch.int32 def test_sparse_flashmla_decode_smoke(): import vllm.attention.ops.flashmla as fm ok, reason = fm.is_flashmla_sparse_supported() if not ok: pytest.skip(reason) device = torch.device("cuda") batch_size = 1 seqlen_q = 1 num_heads_q = 1 head_dim_k = 576 head_dim_v = 512 num_heads_k = 1 page_block_size = 64 bytes_per_token = 656 topk = 128 # Metadata q_seq_per_hk = seqlen_q * num_heads_q // num_heads_k # q_heads_per_hk = num_heads_q // num_heads_k cache_seqlens = torch.zeros(batch_size, dtype=torch.int32, device=device) tile_md, num_splits = fm.get_mla_metadata( cache_seqlens, q_seq_per_hk, num_heads_k, num_heads_q=num_heads_q, topk=topk, is_fp8_kvcache=True, ) # Inputs q = torch.zeros( (batch_size, seqlen_q, num_heads_q, head_dim_k), dtype=torch.bfloat16, device=device, ) k_cache = torch.zeros( (1, page_block_size, num_heads_k, bytes_per_token), dtype=torch.uint8, device=device, ) indices = torch.zeros( (batch_size, seqlen_q, topk), dtype=torch.int32, device=device ) block_table = torch.zeros((batch_size, 128), dtype=torch.int32, device=device) out, lse = fm.flash_mla_with_kvcache( q, k_cache, block_table, cache_seqlens, head_dim_v, tile_md, num_splits, indices=indices, is_fp8_kvcache=True, ) assert out.shape[0] == batch_size assert out.shape[-1] == head_dim_v assert lse.shape[0] == batch_size def test_sparse_flashmla_prefill_smoke(): import vllm.attention.ops.flashmla as fm ok, reason = fm.is_flashmla_sparse_supported() if not ok: pytest.skip(reason) device = torch.device("cuda") s_q = 1 s_kv = 1 h_q = 64 # kernel expects multiple of 64 h_kv = 1 d_qk = 576 d_v = 512 topk = 128 q = torch.zeros((s_q, h_q, d_qk), dtype=torch.bfloat16, device=device) kv = torch.zeros((s_kv, h_kv, d_qk), dtype=torch.bfloat16, device=device) indices = torch.zeros((s_q, h_kv, topk), dtype=torch.int32, device=device) out, max_logits, lse = fm.flash_mla_sparse_prefill(q, kv, indices, 1.0, d_v) assert out.shape == (s_q, h_q, d_v) assert max_logits.shape == (s_q, h_q) assert lse.shape == (s_q, h_q)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_flashinfer_mla_decode.py
tests/kernels/attention/test_flashinfer_mla_decode.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch import torch.nn.functional as F from torch import Tensor from vllm.platforms import current_platform FLASHINFER_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024 if not current_platform.has_device_capability(100): pytest.skip( reason="FlashInfer MLA Requires compute capability of 10 or above.", allow_module_level=True, ) else: from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla def ref_mla( out: Tensor, # (bs, num_heads, v_head_dim) query: Tensor, # (bs, num_heads, head_dim) kv_cache: Tensor, # (num_blocks, block_size, head_dim) scale: float, block_tables: Tensor, # (bs, max_num_blocks) seq_lens: Tensor, # (bs,) ): bs, num_heads, v_head_dim = out.shape head_dim = query.shape[2] for i in range(bs): # gather and flatten KV-cache kv = kv_cache[block_tables[i]] # (max_num_blocks, block_size, head_dim) kv = kv.view(1, -1, head_dim)[:, : seq_lens[i]] # (1, seq_len, head_dim) v = kv[:, :, :v_head_dim] q = query[i].view(num_heads, 1, head_dim) o = F.scaled_dot_product_attention(q, kv, v, scale=scale, enable_gqa=True) out[i] = o.view(num_heads, v_head_dim) return out @pytest.mark.parametrize("dtype", [torch.bfloat16]) @pytest.mark.parametrize("bs", [1, 2, 4, 16]) @pytest.mark.parametrize("block_size", [32, 64]) def test_flashinfer_mla_decode(dtype: torch.dtype, bs: int, block_size: int): torch.set_default_device("cuda") torch.manual_seed(42) # Deepseek R1 config num_heads = 128 kv_lora_rank = 512 qk_nope_head_dim = 128 qk_rope_head_dim = 64 qk_head_dim = kv_lora_rank + qk_rope_head_dim scale = (qk_nope_head_dim + qk_rope_head_dim) ** -0.5 MAX_SEQ_LEN = 1024 seq_lens = [torch.randint(2, MAX_SEQ_LEN, (1,)).item() for _ in range(bs)] seq_lens[-1] = MAX_SEQ_LEN max_seq_len = max(seq_lens) seq_lens_tensor = torch.tensor(seq_lens, dtype=torch.int32) # Generate block tables with random but unique block IDs # From https://github.com/flashinfer-ai/flashinfer/pull/1222 blocks_per_seq = (seq_lens_tensor + block_size - 1) // block_size max_num_blocks_per_seq = max(blocks_per_seq.max().item(), 4) total_blocks_needed = sum(blocks_per_seq) # Get random unique IDs for all blocks all_block_ids = torch.randperm(total_blocks_needed) block_id = 0 block_tables = torch.zeros( (bs, max_num_blocks_per_seq), dtype=torch.int32, ) # Populate block tables and track block assignments block_id = 0 for i in range(bs): num_blocks_needed = blocks_per_seq[i] block_tables[i, :num_blocks_needed] = all_block_ids[ block_id : block_id + num_blocks_needed ] block_id += num_blocks_needed kv_cache = torch.randn(block_tables.numel(), block_size, qk_head_dim).to(dtype) q = torch.randn(bs, num_heads, qk_head_dim).to(dtype) out_ref = q.new_zeros(bs, num_heads, kv_lora_rank) ref_mla(out_ref, q, kv_cache, scale, block_tables, seq_lens_tensor) workspace_buffer = torch.zeros( FLASHINFER_WORKSPACE_BUFFER_SIZE, dtype=torch.uint8, device=q.device, ) # Flashinfer MLA expects the query to be of shape # (bs, q_len_per_request, num_heads, qk_head_dim), # where q_len_per_request is the MTP query length (=1 without MTP) q = q.unsqueeze(1) out_ans = trtllm_batch_decode_with_kv_cache_mla( query=q, kv_cache=kv_cache.unsqueeze(1), workspace_buffer=workspace_buffer, qk_nope_head_dim=qk_nope_head_dim, kv_lora_rank=kv_lora_rank, qk_rope_head_dim=qk_rope_head_dim, block_tables=block_tables, seq_lens=seq_lens_tensor, max_seq_len=max_seq_len, bmm1_scale=scale, ) out_ans = out_ans.squeeze(1) torch.testing.assert_close(out_ans, out_ref, atol=1e-2, rtol=1e-2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_merge_attn_states.py
tests/kernels/attention/test_merge_attn_states.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm._custom_ops import merge_attn_states as merge_attn_states_cuda from vllm.attention.ops.triton_merge_attn_states import ( merge_attn_states as merge_attn_states_triton, ) from vllm.platforms import current_platform # Naive PyTorch Implements section 2.2 of https://www.arxiv.org/pdf/2501.01005 # can be used to combine partial attention results (in the split-KV case) def merge_attn_states_torch( output: torch.Tensor, # [NUM_TOKENS, NUM_HEADS, HEAD_SIZE] prefix_output: torch.Tensor, # [NUM_TOKENS, NUM_HEADS, HEAD_SIZE] prefix_lse: torch.Tensor, # [NUM_HEADS, NUM_TOKENS] suffix_output: torch.Tensor, # [NUM_TOKENS, NUM_HEADS, HEAD_SIZE] suffix_lse: torch.Tensor, # [NUM_HEADS, NUM_TOKENS] output_lse: torch.Tensor | None = None, # [NUM_HEADS, NUM_TOKENS] ): p_lse = prefix_lse s_lse = suffix_lse # inf -> -inf p_lse[p_lse == torch.inf] = -torch.inf s_lse[s_lse == torch.inf] = -torch.inf # max_lse [NUM_HEADS, NUM_TOKENS] max_lse = torch.maximum(p_lse, s_lse) p_lse = p_lse - max_lse s_lse = s_lse - max_lse p_lse_exp = torch.exp(p_lse) s_lse_exp = torch.exp(s_lse) out_se = p_lse_exp + s_lse_exp if output_lse is not None: output_lse = torch.log(out_se) + max_lse p_scale = p_lse_exp / out_se # [NUM_HEADS, NUM_TOKENS] s_scale = s_lse_exp / out_se # [NUM_HEADS, NUM_TOKENS] p_scale = torch.transpose(p_scale, 0, 1).unsqueeze(2) # [NUM_TOKENS, NUM_HEADS, 1] s_scale = torch.transpose(s_scale, 0, 1).unsqueeze(2) # [NUM_TOKENS, NUM_HEADS, 1] output = prefix_output * p_scale + suffix_output * s_scale return output, output_lse NUM_BATCH_TOKENS = [256, 512, 613, 1024, 1536, 4096] NUM_QUERY_HEADS = [4, 8, 16, 32, 48, 64] HEAD_SIZES = [32, 48, 64, 96, 128, 256] DTYPES = [torch.float32, torch.half, torch.bfloat16] all_case_info: list[tuple] = [] def generate_markdown_table(): global all_case_info table_header = ( "| tokens | heads | headsize | dtype " "| device | torch | triton | cuda | speedup |" ) table_separator = "| --- | --- | --- | --- | --- | --- | --- | --- | --- |" def shortly_dtype(dtype: torch.dtype) -> str: return str(dtype).removeprefix("torch.") def shortly_device(device: str) -> str: return device.removeprefix("NVIDIA").strip() print(table_header) print(table_separator) for info in all_case_info: ( num_tokens, num_heads, head_size, dtype, device, avg_time_torch_kernel, avg_time_triton_kernel, avg_time_cuda_kernel, performance_improved, ) = info dtype = shortly_dtype(dtype) device = shortly_device(device) print( f"| {num_tokens} | {num_heads} | {head_size} " f"| {dtype} | {device} | {avg_time_torch_kernel:.5f}ms " f"| {avg_time_triton_kernel:.5f}ms " f"| {avg_time_cuda_kernel:.5f}ms " f"| {performance_improved:.4f}x |" ) @pytest.mark.parametrize("num_tokens", NUM_BATCH_TOKENS) @pytest.mark.parametrize("num_query_heads", NUM_QUERY_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("output_dtype", DTYPES) @torch.inference_mode() def test_merge_attn_states( num_tokens: int, num_query_heads: int, head_size: int, output_dtype: torch.dtype ): if not current_platform.is_cuda(): pytest.skip( "Currently only support compare triton merge_attn_states " "with custom cuda merge_attn_states kernel" ) NUM_TOKENS = num_tokens NUM_HEADS = num_query_heads HEAD_SIZE = head_size print( f"\nNUM_TOKENS:{NUM_TOKENS}, NUM_HEADS:{NUM_HEADS}, " f"HEAD_SIZE:{HEAD_SIZE}, DTYPE: {output_dtype}, " f"Device: {current_platform.get_device_name()}" ) # prefix_lse and suffix_lse contain inf and normal values prefix_lse = torch.randn(NUM_HEADS, NUM_TOKENS, dtype=torch.float32, device="cuda") suffix_lse = torch.randn(NUM_HEADS, NUM_TOKENS, dtype=torch.float32, device="cuda") # Generate boolean masks mask_prefix = torch.rand(NUM_HEADS, NUM_TOKENS) < 0.1 mask_suffix = torch.rand(NUM_HEADS, NUM_TOKENS) < 0.1 # Ensure that the same position is not True at the same time combined_mask = torch.logical_and(mask_prefix, mask_suffix) mask_prefix = torch.logical_and(mask_prefix, ~combined_mask) mask_suffix = torch.logical_and(mask_suffix, ~combined_mask) prefix_lse[mask_prefix] = float("inf") suffix_lse[mask_suffix] = float("inf") # Other input tensors (need to be initialized but # no actual calculation needed) output = torch.zeros( (NUM_TOKENS, NUM_HEADS, HEAD_SIZE), dtype=output_dtype, device="cuda" ) output_lse = torch.zeros( (NUM_HEADS, NUM_TOKENS), dtype=torch.float32, device="cuda" ) prefix_output = torch.randn( (NUM_TOKENS, NUM_HEADS, HEAD_SIZE), dtype=output_dtype, device="cuda" ) suffix_output = torch.randn( (NUM_TOKENS, NUM_HEADS, HEAD_SIZE), dtype=output_dtype, device="cuda" ) warmup_times = 2 repeat_times = 20 output_torch = output.clone() output_lse_torch = output_lse.clone() total_time_torch_kernel = 0 start = torch.Event(enable_timing=True) end = torch.Event(enable_timing=True) # 0. Run the Torch kernel prefix_lse_torch = prefix_lse.clone() suffix_lse_torch = suffix_lse.clone() for _ in range(warmup_times): output_torch, output_lse_torch = merge_attn_states_torch( output_torch, prefix_output, prefix_lse_torch, suffix_output, suffix_lse_torch, output_lse_torch, ) torch.cuda.synchronize() for _ in range(repeat_times): start.record() output_torch, output_lse_torch = merge_attn_states_torch( output_torch, prefix_output, prefix_lse_torch, suffix_output, suffix_lse_torch, output_lse_torch, ) end.record() torch.cuda.synchronize() total_time_torch_kernel += start.elapsed_time(end) avg_time_torch_kernel = total_time_torch_kernel / repeat_times # 1. Run the Triton kernel output_ref_triton = output.clone() output_lse_ref_triton = output_lse.clone() total_time_triton_kernel = 0 start = torch.Event(enable_timing=True) end = torch.Event(enable_timing=True) for _ in range(warmup_times): merge_attn_states_triton( output_ref_triton, prefix_output, prefix_lse, suffix_output, suffix_lse, output_lse_ref_triton, ) torch.cuda.synchronize() for _ in range(repeat_times): start.record() merge_attn_states_triton( output_ref_triton, prefix_output, prefix_lse, suffix_output, suffix_lse, output_lse_ref_triton, ) end.record() torch.cuda.synchronize() total_time_triton_kernel += start.elapsed_time(end) avg_time_triton_kernel = total_time_triton_kernel / repeat_times # 2. Run the CUDA kernel total_time_cuda_kernel = 0 output_cuda = output.clone() output_lse_cuda = output_lse.clone() for _ in range(warmup_times): merge_attn_states_cuda( output_cuda, prefix_output, prefix_lse, suffix_output, suffix_lse, output_lse_cuda, ) torch.cuda.synchronize() for _ in range(repeat_times): start.record() merge_attn_states_cuda( output_cuda, prefix_output, prefix_lse, suffix_output, suffix_lse, output_lse_cuda, ) end.record() torch.cuda.synchronize() total_time_cuda_kernel += start.elapsed_time(end) avg_time_cuda_kernel = total_time_cuda_kernel / repeat_times # 3. Performance compare performance_improved = avg_time_triton_kernel / avg_time_cuda_kernel print(f" Torch time: {avg_time_torch_kernel:.6f}ms") print(f"Triton time: {avg_time_triton_kernel:.6f}ms") print( f" CUDA time: {avg_time_cuda_kernel:.6f}ms, " f"Performance: {performance_improved:.5f}x" ) print("-" * 100) # 4. Correctness compare # Liger Kernel: Efficient Triton Kernels for LLM Training # https://arxiv.org/pdf/2410.10989, 3.3 Correctness # use rtol = 1e-2 for bfloat16. rtol = 1e-2 if output_dtype == torch.bfloat16 else 1e-3 def diff(a: torch.Tensor, b: torch.Tensor): max_diff = torch.max(torch.abs(a.float() - b.float())) return max_diff # Use Triton output as reference because we want to replace # the Triton kernel with custom CUDA kernel for merge attn # states operation. output_ref = output_ref_triton output_lse_ref = output_lse_ref_triton torch.testing.assert_close( output_cuda.float(), output_ref.float(), atol=1e-3, rtol=rtol ) print("Output all match, max abs diff:") print(f"(Triton vs Torch) : {diff(output_torch, output_ref)}") print(f" (CUDA vs Torch) : {diff(output_torch, output_cuda)}") print(f" (CUDA vs Triton): {diff(output_ref, output_cuda)}") print("-" * 100) torch.testing.assert_close( output_lse_cuda.float(), output_lse_ref.float(), atol=1e-3, rtol=rtol ) print("Output LSE all match, max abs diff:") print(f"(Triton vs Torch) : {diff(output_lse_torch, output_lse_ref)}") print(f" (CUDA vs Torch) : {diff(output_lse_torch, output_lse_cuda)}") print(f" (CUDA vs Triton): {diff(output_lse_ref, output_lse_cuda)}") print("-" * 100) print( "All output values test passed! All inf values " "are correctly replaced with -inf." ) print("-" * 100) device = current_platform.get_device_name() all_case_info.append( ( NUM_TOKENS, NUM_HEADS, HEAD_SIZE, output_dtype, device, avg_time_torch_kernel, avg_time_triton_kernel, avg_time_cuda_kernel, performance_improved, ) ) if len(all_case_info) == ( len(NUM_BATCH_TOKENS) * len(HEAD_SIZES) * len(NUM_QUERY_HEADS) * len(DTYPES) ): generate_markdown_table()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_mla_decode_cpu.py
tests/kernels/attention/test_mla_decode_cpu.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch import torch.nn.functional as F from torch import Tensor import vllm._custom_ops as ops from vllm.platforms import current_platform from vllm.utils.math_utils import cdiv def ref_mla( out: Tensor, # (bs, num_heads, v_head_dim) query: Tensor, # (bs, num_heads, head_dim) kv_cache: Tensor, # (num_blocks, block_size, head_dim) scale: float, block_tables: Tensor, # (bs, max_num_blocks) seq_lens: Tensor, # (bs,) ): bs, num_heads, v_head_dim = out.shape head_dim = query.shape[2] for i in range(bs): # gather and flatten KV-cache kv = kv_cache[block_tables[i]] # (max_num_blocks, block_size, head_dim) kv = kv.view(1, -1, head_dim)[:, : seq_lens[i]] # (1, seq_len, head_dim) v = kv[:, :, :v_head_dim] q = query[i].view(num_heads, 1, head_dim) o = F.scaled_dot_product_attention(q, kv, v, scale=scale, enable_gqa=True) out[i] = o.view(num_heads, v_head_dim) return out @pytest.mark.parametrize("bs", [4]) @pytest.mark.parametrize("mean_seq_len", [256]) @pytest.mark.parametrize("h_q", [16]) @pytest.mark.parametrize("d", [576]) @pytest.mark.parametrize("dv", [512]) @pytest.mark.parametrize("block_size", [16]) @pytest.mark.parametrize("dtype", [torch.float, torch.half, torch.bfloat16]) @pytest.mark.parametrize("varlen", [False, True]) @pytest.mark.cpu_model @pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only") def test_mla_decode_cpu( bs: int, mean_seq_len: int, h_q: int, d: int, dv: int, block_size: int, dtype: torch.dtype, varlen: bool, ): torch.set_default_dtype(dtype) torch.manual_seed(0) scale = d ** (-0.5) if varlen: seq_lens = torch.empty(bs).normal_(mean_seq_len, mean_seq_len / 2) seq_lens = seq_lens.clip(2).to(torch.int32) else: seq_lens = torch.full((bs,), mean_seq_len, dtype=torch.int32) max_seq_len = seq_lens.max().item() seqlen_pad = cdiv(max_seq_len, 256) * 256 # is this necessary? q = torch.randn(bs, h_q, d) block_table = torch.arange(bs * seqlen_pad // block_size, dtype=torch.int32) block_table = block_table.view(bs, seqlen_pad // block_size) kv_cache = torch.randn(block_table.numel(), block_size, d) for i, seq_len in enumerate(seq_lens.tolist()): kv_cache.view(bs, seqlen_pad, d)[i, seq_len:] = float("nan") out_mla = q.new_zeros(bs, h_q, dv) ops.mla_decode_kvcache_cpu(out_mla, q, kv_cache, scale, block_table, seq_lens) out_ref = q.new_zeros(bs, h_q, dv) ref_mla(out_ref, q, kv_cache, scale, block_table, seq_lens) assert not out_mla.isnan().any(), "Likely read out of bounds" torch.testing.assert_close(out_mla, out_ref)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_aiter_flash_attn.py
tests/kernels/attention/test_aiter_flash_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch import vllm.v1.attention.backends.rocm_aiter_fa # noqa: F401 from vllm.attention.utils.fa_utils import is_flash_attn_varlen_func_available from vllm.platforms import current_platform NUM_HEADS = [(4, 4), (8, 2)] HEAD_SIZES = [128, 256] BLOCK_SIZES = [16] DTYPES = [torch.bfloat16] QDTYPES = [None] # one value large enough to test overflow in index calculation. # one value small enough to test the schema op check NUM_BLOCKS = [32768, 2048] def ref_paged_attn( query: torch.Tensor, key_cache: torch.Tensor, value_cache: torch.Tensor, query_lens: list[int], kv_lens: list[int], block_tables: torch.Tensor, scale: float, sliding_window: int | None = None, soft_cap: float | None = None, ) -> torch.Tensor: num_seqs = len(query_lens) block_tables = block_tables.cpu().numpy() _, block_size, num_kv_heads, head_size = key_cache.shape outputs: list[torch.Tensor] = [] start_idx = 0 for i in range(num_seqs): query_len = query_lens[i] kv_len = kv_lens[i] q = query[start_idx : start_idx + query_len] q *= scale num_kv_blocks = (kv_len + block_size - 1) // block_size block_indices = block_tables[i, :num_kv_blocks] k = key_cache[block_indices].view(-1, num_kv_heads, head_size) k = k[:kv_len] v = value_cache[block_indices].view(-1, num_kv_heads, head_size) v = v[:kv_len] if q.shape[1] != k.shape[1]: k = torch.repeat_interleave(k, q.shape[1] // k.shape[1], dim=1) v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1) attn = torch.einsum("qhd,khd->hqk", q, k).float() empty_mask = torch.ones(query_len, kv_len) mask = torch.triu(empty_mask, diagonal=kv_len - query_len + 1).bool() if sliding_window is not None: sliding_window_mask = ( torch.triu( empty_mask, diagonal=kv_len - (query_len + sliding_window) + 1 ) .bool() .logical_not() ) mask |= sliding_window_mask if soft_cap is not None: attn = soft_cap * torch.tanh(attn / soft_cap) attn.masked_fill_(mask, float("-inf")) attn = torch.softmax(attn, dim=-1).to(v.dtype) out = torch.einsum("hqk,khd->qhd", attn, v) outputs.append(out) start_idx += query_len return torch.cat(outputs, dim=0) @pytest.mark.skipif(not current_platform.is_rocm(), reason="Only ROCm is supported") @pytest.mark.parametrize( "seq_lens", [[(10, 1328), (5, 18), (129, 463)], [(8, 523), (24, 37), (3, 2011)]] ) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("block_size", BLOCK_SIZES) @pytest.mark.parametrize("sliding_window", [None, 256]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("soft_cap", [None]) @pytest.mark.parametrize("num_blocks", NUM_BLOCKS) @pytest.mark.parametrize("q_dtype", QDTYPES) @torch.inference_mode() def test_varlen_with_paged_kv( seq_lens: list[tuple[int, int]], num_heads: tuple[int, int], head_size: int, sliding_window: int | None, dtype: torch.dtype, block_size: int, soft_cap: float | None, num_blocks: int, q_dtype: torch.dtype | None, ) -> None: if not is_flash_attn_varlen_func_available(): pytest.skip("flash_attn_varlen_func required to run this test.") torch.set_default_device("cuda") current_platform.seed_everything(0) num_seqs = len(seq_lens) query_lens = [x[0] for x in seq_lens] kv_lens = [x[1] for x in seq_lens] num_query_heads = num_heads[0] num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_query_len = max(query_lens) max_kv_len = max(kv_lens) window_size = (sliding_window - 1, 0) if sliding_window is not None else (-1, -1) scale = head_size**-0.5 query = torch.randn(sum(query_lens), num_query_heads, head_size, dtype=dtype) key_cache = torch.randn( num_blocks, block_size, num_kv_heads, head_size, dtype=dtype ) value_cache = torch.randn_like(key_cache) cu_query_lens = torch.tensor([0] + query_lens, dtype=torch.int32).cumsum( dim=0, dtype=torch.int32 ) cu_seq_lens = torch.tensor([0] + kv_lens, dtype=torch.int32).cumsum( dim=0, dtype=torch.int32 ) kv_lens = torch.tensor(kv_lens, dtype=torch.int32) max_num_blocks_per_seq = (max_kv_len + block_size - 1) // block_size block_tables = torch.randint( 0, num_blocks, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32 ) output = torch.empty_like(query) maybe_quantized_query = query maybe_quantized_key_cache = key_cache maybe_quantized_value_cache = value_cache k_descale = None v_descale = None if q_dtype is not None: # QKV are drawn from N(0, 1): no need for a fp8 scaling factor maybe_quantized_query = query.to(q_dtype) maybe_quantized_key_cache = key_cache.to(q_dtype) maybe_quantized_value_cache = value_cache.to(q_dtype) scale_shape = (num_seqs, num_kv_heads) k_descale = torch.ones(scale_shape, dtype=torch.float32) v_descale = torch.ones(scale_shape, dtype=torch.float32) torch.ops.vllm.flash_attn_varlen_func( maybe_quantized_query, maybe_quantized_key_cache, maybe_quantized_value_cache, out=output, cu_seqlens_q=cu_query_lens, max_seqlen_q=max_query_len, max_seqlen_k=max_kv_len, softmax_scale=scale, alibi_slopes=None, window_size=window_size, block_table=block_tables, cu_seqlens_k=cu_seq_lens, k_scale=k_descale, v_scale=v_descale, ) ref_output = ref_paged_attn( query=query, key_cache=key_cache, value_cache=value_cache, query_lens=query_lens, kv_lens=kv_lens, block_tables=block_tables, scale=scale, sliding_window=sliding_window, soft_cap=soft_cap, ) atol, rtol = 2e-2, 2e-2 if q_dtype is not None: atol, rtol = 1.5e-1, 1.5e-1 ( torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol), f"{torch.max(torch.abs(output - ref_output))}", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/attention/test_lightning_attn.py
tests/kernels/attention/test_lightning_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.model_executor.layers.lightning_attn import linear_decode_forward_triton from vllm.platforms import current_platform NUM_HEADS = [4, 8] HEAD_SIZES = [64] BATCH_SIZES = [1, 2] SEQ_LENGTHS = [16] DTYPES = [torch.float32] def reference_lightning_attention(q, k, v, ed, block_size, kv_history): """Reference implementation of lightning attention core algorithm The difference from the main implementation is that this processes each step sequentially, instead of using parallelized triton kernels """ B, H, S, D = q.shape E = v.shape[-1] dtype = q.dtype output = torch.zeros((B, H, S, E), dtype=dtype, device=q.device) # Use clone() to ensure an independent copy if kv_history is None: kv_cache = torch.zeros((B, H, D, E), dtype=dtype, device=q.device) else: kv_cache = kv_history.clone() # More efficient implementation # Convert decay factors to matrix form decay = torch.exp(-ed).view(1, -1, 1, 1) if ed.dim() == 1 else torch.exp(-ed) for b in range(B): for step in range(S): # Process all heads at once for this position q_bs = q[b, :, step] # [H, D] k_bs = k[b, :, step] # [H, D] v_bs = v[b, :, step] # [H, E] # Calculate KV outer products for all heads for h in range(H): # Calculate KV outer product kv_outer = torch.outer(k_bs[h], v_bs[h]) # Update KV cache with decay # Note: Using the same order as in the Triton kernel kv_cache[b, h] = decay[0, h, 0, 0] * kv_cache[b, h] + kv_outer # Calculate attention output output[b, h, step] = torch.matmul(q_bs[h], kv_cache[b, h]) # Match the shape returned by the actual implementation # The actual implementation returns a tensor of shape [B, H, 2, D, E] # where dimension 2 contains both KV and KV history kv_reshaped = kv_cache.unsqueeze(2) # [B, H, 1, D, E] final_kv_cache = torch.cat([kv_reshaped, kv_reshaped], dim=2) # [B, H, 2, D, E] return output, final_kv_cache def reference_linear_decode(q, k, v, kv_caches, slope_rate, slot_idx): """Reference implementation: linear attention decode function""" B, H, _, D = q.shape output = torch.zeros(B, H * D, dtype=q.dtype, device=q.device) # Calculate decay factors once (more efficient) decay = torch.exp(-slope_rate).view(-1, 1, 1) # [H, 1, 1] # Process each batch for b in range(B): slot_id = slot_idx[b].item() # Skip padding positions if slot_id == -1: continue # Process all heads at once for this batch q_b = q[b, :, 0] # [H, D] k_b = k[b, :, 0] # [H, D] v_b = v[b, :, 0] # [H, D] # Process each attention head for h in range(H): # Get current query, key and value q_bh = q_b[h] k_bh = k_b[h] v_bh = v_b[h] # Get cache kv_cache_old = kv_caches[b, h] # Calculate new key-value outer product kv_outer = torch.outer(k_bh, v_bh) # Apply decay and update cache kv_new = kv_outer + decay[h, 0, 0] * kv_cache_old # Calculate output out_h = torch.matmul(q_bh, kv_new) # Update output and cache output[b, h * D : (h + 1) * D] = out_h kv_caches[b, h] = kv_new return output @pytest.mark.parametrize("batch_size", BATCH_SIZES) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @torch.inference_mode() def test_linear_decode_forward_triton( batch_size: int, num_heads: int, head_size: int, dtype: torch.dtype, ): torch.set_default_device("cuda") torch.manual_seed(42) torch.cuda.manual_seed_all(42) current_platform.seed_everything(42) base = 0.01 q = base * torch.randn(batch_size, num_heads, 1, head_size, dtype=dtype) k = base * torch.randn(batch_size, num_heads, 1, head_size, dtype=dtype) v = base * torch.randn(batch_size, num_heads, 1, head_size, dtype=dtype) kv_caches = base * torch.randn( batch_size, num_heads, head_size, head_size, dtype=dtype, device="cuda" ) kv_caches_copy = kv_caches.clone() slope_rate = torch.zeros(num_heads, device="cuda") for h in range(num_heads): slope_rate[h] = 0.1 * (h + 1) slot_idx = torch.arange(batch_size, device="cuda") triton_output = linear_decode_forward_triton( q, k, v, kv_caches, slope_rate, slot_idx ) reference_output = reference_linear_decode( q, k, v, kv_caches_copy, slope_rate, slot_idx ) torch.testing.assert_close(triton_output, reference_output, rtol=1e-1, atol=1e-1) torch.testing.assert_close(kv_caches, kv_caches_copy, rtol=1e-1, atol=1e-1) assert triton_output.shape == (batch_size, num_heads * head_size) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @torch.inference_mode() def test_linear_decode_forward_triton_with_padding( num_heads: int, head_size: int, dtype: torch.dtype, ): torch.set_default_device("cuda") torch.manual_seed(42) torch.cuda.manual_seed_all(42) current_platform.seed_everything(42) batch_size = 4 base = 0.01 q = base * torch.randn(batch_size, num_heads, 1, head_size, dtype=dtype) k = base * torch.randn(batch_size, num_heads, 1, head_size, dtype=dtype) v = base * torch.randn(batch_size, num_heads, 1, head_size, dtype=dtype) kv_caches = base * torch.randn( batch_size, num_heads, head_size, head_size, dtype=dtype, device="cuda" ) kv_caches_copy = kv_caches.clone() slope_rate = torch.zeros(num_heads, device="cuda") for h in range(num_heads): slope_rate[h] = 0.1 * (h + 1) slot_idx = torch.tensor([0, 1, -1, 2], device="cuda") triton_output = linear_decode_forward_triton( q, k, v, kv_caches, slope_rate, slot_idx ) reference_output = reference_linear_decode( q, k, v, kv_caches_copy, slope_rate, slot_idx ) padding_mask = (slot_idx != -1).unsqueeze(1).expand(-1, num_heads * head_size) triton_masked = triton_output[padding_mask] reference_masked = reference_output[padding_mask] atol, rtol = 1.5e-1, 1.5e-1 valid_indices = slot_idx != -1 for i in range(batch_size): if valid_indices[i] > 0: torch.testing.assert_close( kv_caches[i], kv_caches_copy[i], rtol=rtol, atol=atol ) torch.testing.assert_close(triton_masked, reference_masked, rtol=rtol, atol=atol) assert triton_output.shape == (batch_size, num_heads * head_size) @pytest.mark.parametrize("batch_size", BATCH_SIZES) @pytest.mark.parametrize("num_heads", NUM_HEADS) @pytest.mark.parametrize("head_size", HEAD_SIZES) @pytest.mark.parametrize("seq_len", SEQ_LENGTHS) @pytest.mark.parametrize("dtype", DTYPES) @torch.inference_mode() def test_lightning_attention_reference( batch_size: int, num_heads: int, head_size: int, seq_len: int, dtype: torch.dtype, ): torch.set_default_device("cuda") torch.manual_seed(42) torch.cuda.manual_seed_all(42) current_platform.seed_everything(42) base = 0.01 q = base * torch.randn(batch_size, num_heads, seq_len, head_size, dtype=dtype) k = base * torch.randn(batch_size, num_heads, seq_len, head_size, dtype=dtype) v = base * torch.randn(batch_size, num_heads, seq_len, head_size, dtype=dtype) ed = torch.zeros(num_heads, device="cuda") for h in range(num_heads): ed[h] = 0.1 * (h + 1) kv_history = base * torch.randn( batch_size, num_heads, head_size, head_size, dtype=dtype, device="cuda" ) kv_history_clone = kv_history.clone() ref_output, ref_kv_cache = reference_lightning_attention( q, k, v, ed, 256, kv_history ) from vllm.model_executor.layers.lightning_attn import lightning_attention actual_output, actual_kv_cache = lightning_attention( q, k, v, ed, 256, kv_history_clone ) atol, rtol = 1.5e-1, 1.5e-1 torch.testing.assert_close(ref_output, actual_output, rtol=rtol, atol=atol) torch.testing.assert_close(ref_kv_cache, actual_kv_cache, rtol=rtol, atol=atol) assert ref_output.shape == (batch_size, num_heads, seq_len, head_size) assert ref_kv_cache.shape == actual_kv_cache.shape
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_flashinfer_scaled_mm.py
tests/kernels/quantization/test_flashinfer_scaled_mm.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm import _custom_ops as ops from vllm.platforms import current_platform from vllm.utils.flashinfer import flashinfer_scaled_fp8_mm if not current_platform.has_device_capability(100): pytest.skip( reason="Flashinfer FP8 gemms requires compute capability of 10.0 or above.", allow_module_level=True, ) DTYPES = [torch.float16, torch.bfloat16] # m, n, k SHAPES = [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)] PAD_SHAPES = [(150, 128, 64), (128, 128, 96)] SHAPES.extend(PAD_SHAPES) SEEDS = [42] CUDA_DEVICES = ["cuda:0"] @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("shape", SHAPES) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("autotune", [False, True]) @torch.inference_mode() def test_flashinfer_fp8_gemm( dtype: torch.dtype, shape: tuple[int, int, int], use_bias: bool, seed: int, device: str, autotune: bool, ) -> None: current_platform.seed_everything(seed) m, n, k = shape a = torch.randn((m, k), dtype=dtype, device=device) b = torch.randn((n, k), dtype=dtype, device=device) / k a_fp8, a_scale = ops.scaled_fp8_quant(a) b_fp8, b_scale = ops.scaled_fp8_quant(b) expected_out = torch.mm( a_scale * a_fp8.to(dtype=torch.float32), b_scale * b_fp8.to(dtype=torch.float32).t(), ).to(dtype=dtype) if use_bias: bias = torch.randn((n,), dtype=dtype, device=device) expected_out = expected_out + bias else: bias = None import flashinfer with flashinfer.autotune(autotune): out = flashinfer_scaled_fp8_mm( a_fp8, b_fp8.t(), a_scale, b_scale, dtype, bias=bias, ) torch.testing.assert_close(out, expected_out, atol=1e-2, rtol=1e-2)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_triton_scaled_mm.py
tests/kernels/quantization/test_triton_scaled_mm.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Tests for the triton_scaled_mm kernel Run `pytest tests/kernels/quantization/test_triton_scaled_mm.py`. """ import importlib import pytest import torch from vllm.platforms import current_platform device = "cuda" triton_scaled_mm_module = importlib.import_module( "vllm.model_executor.layers.quantization.compressed_tensors.triton_scaled_mm" ) triton_scaled_mm = triton_scaled_mm_module.triton_scaled_mm def torch_scaled_mm( a: torch.Tensor, b: torch.Tensor, scale_a: torch.Tensor, scale_b: torch.Tensor, out_dtype: type[torch.dtype], bias: torch.Tensor | None = None, ) -> torch.Tensor: out = torch.mm(a.to(torch.float32), b.to(torch.float32)) out = scale_a * out out = scale_b.T * out out = out.to(out_dtype) if bias is not None: out = out + bias return out def get_8bit_types(): types = [torch.int8] if current_platform.supports_fp8(): types.append(current_platform.fp8_dtype()) return types # This test is to check regressions for int8 support on ROCm. @pytest.mark.parametrize( "model_path", [ "neuralmagic/Llama-3.2-1B-quantized.w8a8", ], ) @pytest.mark.parametrize("max_tokens", [32]) @pytest.mark.parametrize("num_logprobs", [10]) @pytest.mark.skipif(not current_platform.is_rocm(), reason="Should only run on ROCm") def test_rocm_compressed_tensors_w8a8( vllm_runner, example_prompts, model_path, max_tokens, num_logprobs ): dtype = "bfloat16" with vllm_runner(model_path, dtype=dtype) as vllm_model: vllm_model.generate_greedy_logprobs(example_prompts, max_tokens, num_logprobs) MNK_FACTORS = [ (1, 256, 128), (33, 256, 496), (64, 971, 1024), (64, 20486, 128), (512, 256, 496), (512, 20486, 1024), ] @pytest.mark.parametrize("M,N,K", MNK_FACTORS) @pytest.mark.parametrize("out_dtype", [torch.bfloat16]) @pytest.mark.parametrize("in_dtype", get_8bit_types()) @pytest.mark.parametrize("use_scalar_scale_a", [True, False]) @pytest.mark.parametrize("use_scalar_scale_b", [True, False]) @pytest.mark.parametrize("use_bias", [True, False]) def test_scaled_mm( M, N, K, in_dtype, out_dtype, use_scalar_scale_a, use_scalar_scale_b, use_bias ): is_floating_point_type = lambda t: torch.tensor([1, 1], dtype=t).is_floating_point() current_platform.seed_everything(0) # NOTE: There are cases, where if the matrix is large enough, an output # like 65504.4 can be produced, and can easily turn into inf when # multiplied when using float16/bfloat16. This means one function, e.g., # testing function, and another function, e.g. golden function, can # produce a non-inf value while the other produces an inf value, and # will cause assert_close/allclose to fail, even though if overflow # wouldn't have occurred, the values would have been "close." # # So, the values here are kept small enough to avoid this situation. if is_floating_point_type(in_dtype): a = (0.25 * torch.rand((M, K), dtype=torch.float32, device=device)).to(in_dtype) b = (0.25 * torch.rand((K, N), dtype=torch.float32, device=device)).to(in_dtype) else: a = torch.randint(-32, 32, (M, K), dtype=in_dtype, device=device) b = torch.randint(-32, 32, (K, N), dtype=in_dtype, device=device) if use_scalar_scale_a: scale_a = torch.rand((1, 1), device=device) else: scale_a = 0.25 * torch.rand((M, 1), device=device) if use_scalar_scale_b: scale_b = torch.rand((1, 1), device=device) else: scale_b = 0.25 * torch.rand((N, 1), device=device) bias = None if use_bias: bias = torch.rand((N,), device=device, dtype=out_dtype) c_check = triton_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias) c_actual = torch_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias) torch.testing.assert_close(c_check, c_actual, rtol=1e-1, atol=1e-1)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_marlin_gemm.py
tests/kernels/quantization/test_marlin_gemm.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Tests for the marlin kernel. Run `pytest tests/kernels/quantization/test_marlin_gemm.py`. """ import itertools import pytest import torch from tests.kernels.utils import DEFAULT_OPCHECK_TEST_UTILS, opcheck from tests.quantization.utils import is_quant_method_supported from vllm import _custom_ops as ops from vllm.model_executor.layers.quantization.gptq_marlin_24 import ( GPTQ_MARLIN_24_MAX_PARALLEL, GPTQ_MARLIN_24_MIN_THREAD_N, GPTQ_MARLIN_24_SUPPORTED_GROUP_SIZES, GPTQ_MARLIN_24_SUPPORTED_QUANT_TYPES, ) from vllm.model_executor.layers.quantization.utils.int8_utils import ( per_token_quant_int8, ) from vllm.model_executor.layers.quantization.utils.marlin_utils import ( marlin_make_empty_g_idx, marlin_make_workspace_new, marlin_permute_bias, marlin_permute_scales, query_marlin_supported_quant_types, ) from vllm.model_executor.layers.quantization.utils.marlin_utils_fp4 import ( rand_marlin_weight_mxfp4_like, rand_marlin_weight_nvfp4_like, ) from vllm.model_executor.layers.quantization.utils.marlin_utils_fp8 import ( marlin_quant_fp8_torch, ) from vllm.model_executor.layers.quantization.utils.marlin_utils_test import ( MarlinWorkspace, awq_marlin_quantize, get_weight_perm, marlin_quantize, marlin_weights, ) from vllm.model_executor.layers.quantization.utils.marlin_utils_test_24 import ( marlin_24_quantize, ) from vllm.model_executor.layers.quantization.utils.quant_utils import ( awq_pack, gptq_pack, gptq_quantize_weights, quantize_weights, sort_weights, ) from vllm.platforms import current_platform from vllm.scalar_type import scalar_types if current_platform.is_rocm(): pytest.skip( "These tests require gptq_marlin_repack," "marlin_int4_fp8_preprocess, gptq_marlin_24_gemm," "or gptq_marlin_gemm which are not supported on ROCm.", allow_module_level=True, ) ACT_ORDER_OPTS = [False, True] K_FULL_OPTS = [False, True] USE_ATOMIC_ADD_OPTS = [False, True] USE_FP32_REDUCE_OPTS = [True] MARLIN_K_CHUNKS = [128] MARLIN_N_CHUNKS = [64, 256] MARLIN_24_K_CHUNKS = [128] MARLIN_24_N_CHUNKS = [512] HQQ_SUPPORTED_GROUP_SIZES = [64] MARLIN_REPACK_NK_FACTORS = [ (4, 8), (7, 5), (13, 11), ] MNK_FACTORS = [ (1, 1, 1), (1, 4, 8), (26, 37, 13), (257, 13, 11), ] DTYPES = [torch.float16, torch.bfloat16] DENSE_MARLIN_QUANT_TEST_CONFIGS = [ # AWQ-INT4 {"b_type": scalar_types.uint4, "group_blocks": [-1, 2, 4, 8]}, # GPTQ-INT4 { "b_type": scalar_types.uint4b8, "support_act_order": True, "group_blocks": [-1, 2, 4, 8], }, # GPTQ-INT8 { "b_type": scalar_types.uint8b128, "support_act_order": True, "group_blocks": [-1, 2, 4, 8], }, # FP8 {"b_type": scalar_types.float8_e4m3fn, "group_blocks": [-1, 8]}, # NVFP4 {"b_type": scalar_types.float4_e2m1f, "group_blocks": [1]}, # MXFP4 { "a_type": [scalar_types.bfloat16], "b_type": scalar_types.float4_e2m1f, "group_blocks": [2], }, # AWQ-INT4 with INT8 activation { "a_type": [scalar_types.int8], "b_type": scalar_types.uint4, "group_blocks": [-1, 2, 4, 8], }, # GPTQ-INT4 with INT8 activation { "a_type": [scalar_types.int8], "b_type": scalar_types.uint4b8, "group_blocks": [-1, 2, 4, 8], }, # GPTQ-INT4 with FP8 activation { "a_type": [scalar_types.float8_e4m3fn], "b_type": scalar_types.uint4b8, "group_blocks": [-1, 2, 4, 8], }, # AWQ-INT4 with FP8 activation { "a_type": [scalar_types.float8_e4m3fn], "b_type": scalar_types.uint4, "group_blocks": [-1, 2, 4, 8], }, # MXFP4 with FP8 activation { "a_type": [scalar_types.float8_e4m3fn], "b_type": scalar_types.float4_e2m1f, "c_type": [scalar_types.bfloat16], "group_blocks": [2], }, ] def compute_max_diff(output, output_ref): return torch.mean(torch.abs(output - output_ref)) / torch.mean( torch.abs(output_ref) ) def rand_data(shape, dtype=torch.float16): return torch.randn(shape, dtype=dtype, device="cuda") @pytest.mark.skipif( not is_quant_method_supported("gptq_marlin"), reason="Marlin is not supported on this GPU type.", ) def test_marlin_int4_fp8_preprocess_without_zp(): qweight_unpacked = torch.randint( 0, 16, size=(2048, 2048), dtype=torch.int32, device="cuda" ) qweight_packed = qweight_unpacked[:, ::2] * 16 + qweight_unpacked[:, 1::2] qweight_packed = qweight_packed.to(torch.int8).view(torch.int32) cuda_res = ops.marlin_int4_fp8_preprocess(qweight_packed) torch_res = torch.where( qweight_unpacked >= 8, qweight_unpacked - 8, 15 - qweight_unpacked ) torch_res = torch_res[:, ::2] * 16 + torch_res[:, 1::2] torch_res = torch_res.to(torch.int8).view(torch.int32) assert (cuda_res == torch_res).all() @pytest.mark.skipif( not is_quant_method_supported("gptq_marlin"), reason="Marlin is not supported on this GPU type.", ) def test_marlin_int4_fp8_preprocess_awq(): group_size = 128 qweight_unpacked = torch.randint( 0, 16, size=(2048, 2048), dtype=torch.int32, device="cuda" ) qzeros_unpacked = torch.randint( 0, 16, size=(2048 // group_size, 2048), dtype=torch.int32, device="cuda" ) qweight_packed = qweight_unpacked[:, ::2] * 16 + qweight_unpacked[:, 1::2] qweight_packed = qweight_packed.to(torch.int8).view(torch.int32) qzeros_packed = qzeros_unpacked[:, ::2] * 16 + qzeros_unpacked[:, 1::2] qzeros_packed = qzeros_packed.to(torch.int8).view(torch.int32) cuda_res = ops.marlin_int4_fp8_preprocess(qweight_packed, qzeros_packed) repeated_zp = qzeros_unpacked.repeat_interleave(group_size, 0) torch_res = qweight_unpacked - repeated_zp torch_res[torch_res < 0] = 15 - qweight_unpacked[torch_res < 0] torch_res = torch_res[:, ::2] * 16 + torch_res[:, 1::2] torch_res = torch_res.to(torch.int8).view(torch.int32) assert (cuda_res == torch_res).all() @pytest.mark.skipif( not is_quant_method_supported("gptq_marlin"), reason="Marlin is not supported on this GPU type.", ) @pytest.mark.parametrize("k_chunk", MARLIN_K_CHUNKS) @pytest.mark.parametrize("n_chunk", MARLIN_N_CHUNKS) @pytest.mark.parametrize("quant_type", query_marlin_supported_quant_types(False, False)) @pytest.mark.parametrize("act_order", ACT_ORDER_OPTS) @pytest.mark.parametrize("is_a_8bit", [True, False]) @pytest.mark.parametrize("nk_factors", MARLIN_REPACK_NK_FACTORS) def test_gptq_marlin_repack( k_chunk, n_chunk, quant_type, act_order, is_a_8bit, nk_factors ): n_factor, k_factor = nk_factors size_k = k_chunk * k_factor size_n = n_chunk * n_factor group_size = 128 # Filter act_order if act_order: if group_size == -1: return if group_size == size_k: return if is_a_8bit: return # Normalize group_size if group_size == -1: group_size = size_k assert group_size <= size_k # Create input b_weight = rand_data((size_k, size_n)) # Quantize (and apply act_order if provided) w_ref, q_w, s, g_idx, rand_perm = gptq_quantize_weights( b_weight, quant_type, group_size, act_order ) # Pack to GPTQ format q_w_gptq = gptq_pack(q_w, quant_type.size_bits, size_k, size_n) # For act_order, sort the "weights" and "g_idx" so that group ids are # increasing sort_indices = torch.empty(0, dtype=torch.int, device=b_weight.device) if act_order: q_w, g_idx, sort_indices = sort_weights(q_w, g_idx) # Pack to Marlin format weight_perm = get_weight_perm(quant_type.size_bits, is_a_8bit) marlin_q_w_1 = marlin_weights( q_w, size_k, size_n, quant_type.size_bits, weight_perm, is_a_8bit ) opcheck( torch.ops._C.gptq_marlin_repack, (q_w_gptq, sort_indices, size_k, size_n, quant_type.size_bits, is_a_8bit), ) # Run Marlin repack GPU kernel marlin_q_w_2 = ops.gptq_marlin_repack( q_w_gptq, sort_indices, size_k, size_n, quant_type.size_bits, is_a_8bit ) torch.cuda.synchronize() torch.testing.assert_close(marlin_q_w_1, marlin_q_w_2) @pytest.mark.skipif( not is_quant_method_supported("gptq_marlin"), reason="Marlin is not supported on this GPU type.", ) @pytest.mark.parametrize("k_chunk", MARLIN_K_CHUNKS) @pytest.mark.parametrize("n_chunk", MARLIN_N_CHUNKS) @pytest.mark.parametrize("quant_type", query_marlin_supported_quant_types(True)) @pytest.mark.parametrize("is_a_8bit", [True, False]) @pytest.mark.parametrize("nk_factors", MARLIN_REPACK_NK_FACTORS) def test_awq_marlin_repack(k_chunk, n_chunk, quant_type, is_a_8bit, nk_factors): n_factor, k_factor = nk_factors size_k = k_chunk * k_factor size_n = n_chunk * n_factor group_size = 128 # Create input b_weight = rand_data((size_k, size_n)) # Quantize w_ref, q_w, s, zp = quantize_weights( b_weight, quant_type, group_size, zero_points=True ) # Pack to AWQ format q_w_awq = awq_pack(q_w, quant_type.size_bits, size_k, size_n) # Pack to Marlin format weight_perm = get_weight_perm(quant_type.size_bits, is_a_8bit) marlin_q_w_1 = marlin_weights( q_w, size_k, size_n, quant_type.size_bits, weight_perm, is_a_8bit ) opcheck( torch.ops._C.awq_marlin_repack, (q_w_awq, size_k, size_n, quant_type.size_bits, is_a_8bit), ) # Run Marlin repack GPU kernel marlin_q_w_2 = ops.awq_marlin_repack( q_w_awq, size_k, size_n, quant_type.size_bits, is_a_8bit ) torch.cuda.synchronize() torch.testing.assert_close(marlin_q_w_1, marlin_q_w_2) def marlin_generate_valid_test_cases(): all_combinations = itertools.product( DENSE_MARLIN_QUANT_TEST_CONFIGS, MNK_FACTORS, MARLIN_N_CHUNKS, MARLIN_K_CHUNKS, ACT_ORDER_OPTS, K_FULL_OPTS, USE_ATOMIC_ADD_OPTS, USE_FP32_REDUCE_OPTS, ) def is_invalid( a_type, b_type, c_type, group_blocks, size_m, size_n, size_k, act_order, is_k_full, use_atomic_add, use_fp32_reduce, ): if use_atomic_add: if use_fp32_reduce: return False if ( c_type == scalar_types.bfloat16 and torch.cuda.get_device_capability()[0] < 9 ): return False group_size = group_blocks if group_blocks <= 0 else group_blocks * 16 if group_size > 0 and size_k % group_size != 0: return False if act_order and group_size in [-1, size_k]: return False if group_size == size_k: return False if not act_order and is_k_full: return False return a_type.size_bits < 16 or a_type is c_type cases = [] for case in all_combinations: quant_test_config, mnk_factors, n_chunk, k_chunk, act_order, *_ = case size_m = mnk_factors[0] size_n = mnk_factors[1] * n_chunk size_k = mnk_factors[2] * k_chunk if act_order and not quant_test_config.get("support_act_order", False): continue f16_types = [scalar_types.float16, scalar_types.bfloat16] inner_combinations = itertools.product( quant_test_config.get("a_type", f16_types), [quant_test_config["b_type"]], quant_test_config.get("c_type", f16_types), quant_test_config["group_blocks"], ) for sub_case in inner_combinations: if ( sub_case[0] == scalar_types.float8_e4m3fn and current_platform.get_device_capability() not in [89, 120] ): continue args = sub_case + (size_m, size_n, size_k) + case[4:] if is_invalid(*args): cases.append(args) return cases @pytest.mark.skipif( not is_quant_method_supported("gptq_marlin"), reason="Marlin is not supported on this GPU type.", ) @pytest.mark.parametrize( ( "a_type, b_type, c_type, group_blocks," "size_m, size_n, size_k, act_order, is_k_full," "use_atomic_add, use_fp32_reduce" ), marlin_generate_valid_test_cases(), ) def test_gptq_marlin_gemm( a_type, b_type, c_type, group_blocks, size_m, size_n, size_k, act_order, is_k_full, use_atomic_add, use_fp32_reduce, ): has_zp = b_type in [scalar_types.uint4, scalar_types.uint8] group_size = group_blocks if group_blocks <= 0 else group_blocks * 16 if c_type == scalar_types.float16: dtype = torch.float16 elif c_type == scalar_types.bfloat16: dtype = torch.bfloat16 else: raise RuntimeError("unsupported c_type") if a_type == scalar_types.int8: a_dtype = torch.int8 elif a_type == scalar_types.float8_e4m3fn: a_dtype = torch.float8_e4m3fn else: a_dtype = dtype a_input = rand_data((size_m, size_k), dtype=dtype) b_weight = rand_data((size_k, size_n), dtype=dtype) if b_type == scalar_types.float4_e2m1f: if group_size == 16: w_ref, marlin_q_w, marlin_s, marlin_s2 = rand_marlin_weight_nvfp4_like( b_weight.T, group_size, input_dtype=a_dtype ) else: w_ref, marlin_q_w, marlin_s = rand_marlin_weight_mxfp4_like( b_weight.T, group_size, input_dtype=a_dtype ) marlin_s2 = None g_idx = None sort_indices = None marlin_zp = None elif b_type == scalar_types.float8_e4m3fn: w_ref, marlin_q_w, marlin_s = marlin_quant_fp8_torch( b_weight.T, group_size, input_dtype=a_dtype ) g_idx = None sort_indices = None marlin_zp = None marlin_s2 = None elif has_zp: w_ref, marlin_q_w, marlin_s, marlin_zp = awq_marlin_quantize( b_weight, b_type, group_size, input_dtype=a_dtype ) g_idx = None sort_indices = None marlin_s2 = None else: w_ref, marlin_q_w, marlin_s, g_idx, sort_indices, _ = marlin_quantize( b_weight, b_type, group_size, act_order, input_dtype=a_dtype ) marlin_zp = None marlin_s2 = None workspace = marlin_make_workspace_new(w_ref.device) if a_type == scalar_types.int8: a_input, a_scales = per_token_quant_int8(a_input) a_input_ref = a_input.to(a_scales.dtype) * a_scales.view(-1, 1) a_input_ref = a_input_ref.to(dtype) if group_size != -1: a_scales = a_scales / 4096 * marlin_s.max() a_scales = a_scales.float() marlin_s = marlin_s / marlin_s.max() * 4096 marlin_s = marlin_s.round().to(torch.int16).view(dtype) elif a_type == scalar_types.float8_e4m3fn: a_input, a_scales = ops.scaled_fp8_quant(a_input, use_per_token_if_dynamic=True) a_input_ref = a_input.to(a_scales.dtype) * a_scales.view(-1, 1) a_input_ref = a_input_ref.to(dtype) else: assert a_type.size_bits == 16 a_input_ref = a_input a_scales = None output = torch.empty((size_m, size_n), dtype=dtype, device=a_input.device) output = ops.gptq_marlin_gemm( a_input, output, marlin_q_w, None, marlin_s, a_scales, marlin_s2, marlin_zp, g_idx, sort_indices, workspace, b_type, a_input.shape[0], b_weight.shape[1], a_input.shape[1], is_k_full=is_k_full, use_atomic_add=use_atomic_add, use_fp32_reduce=use_fp32_reduce, is_zp_float=False, ) output_ref = torch.matmul(a_input_ref, w_ref) max_diff = compute_max_diff(output, output_ref) assert max_diff < 0.04 # TODO: find better way to test this? @torch.compile(fullgraph=True) def marlin_24_gemm_tester( a_input, marlin_24_q_w_comp, marlin_24_meta, marlin_24_s, scratch, quant_type, size_m, size_n, size_k, ): return ops.gptq_marlin_24_gemm( a_input, marlin_24_q_w_comp, marlin_24_meta, marlin_24_s, scratch, quant_type, size_m, size_n, size_k, ) @pytest.mark.skipif( not is_quant_method_supported("gptq_marlin"), reason="Marlin is not supported on this GPU type.", ) @pytest.mark.parametrize("k_chunk", MARLIN_24_K_CHUNKS) @pytest.mark.parametrize("n_chunk", MARLIN_24_N_CHUNKS) @pytest.mark.parametrize("quant_type", GPTQ_MARLIN_24_SUPPORTED_QUANT_TYPES) @pytest.mark.parametrize("group_size", GPTQ_MARLIN_24_SUPPORTED_GROUP_SIZES) @pytest.mark.parametrize("mnk_factors", MNK_FACTORS) def test_gptq_marlin_24_gemm(k_chunk, n_chunk, quant_type, group_size, mnk_factors): m_factor, n_factor, k_factor = mnk_factors size_m = m_factor size_k = k_chunk * k_factor size_n = n_chunk * n_factor a_input = rand_data((size_m, size_k)) b_weight = rand_data((size_k, size_n)) (w_24_ref, marlin_24_q_w_comp, marlin_24_meta, marlin_24_s) = marlin_24_quantize( b_weight, quant_type, group_size ) workspace_24 = MarlinWorkspace( size_n, GPTQ_MARLIN_24_MIN_THREAD_N, GPTQ_MARLIN_24_MAX_PARALLEL ) output_ref = torch.matmul(a_input, w_24_ref) opcheck( torch.ops._C.gptq_marlin_24_gemm, ( a_input, marlin_24_q_w_comp, marlin_24_meta, marlin_24_s, workspace_24.scratch, quant_type.id, a_input.shape[0], b_weight.shape[1], a_input.shape[1], ), test_utils=DEFAULT_OPCHECK_TEST_UTILS, ) output = marlin_24_gemm_tester( a_input, marlin_24_q_w_comp, marlin_24_meta, marlin_24_s, workspace_24.scratch, quant_type, a_input.shape[0], b_weight.shape[1], a_input.shape[1], ) torch.cuda.synchronize() max_diff = compute_max_diff(output, output_ref) assert max_diff < 0.04 @pytest.mark.skipif( not is_quant_method_supported("gptq_marlin"), reason="Marlin is not supported on this GPU type.", ) @pytest.mark.parametrize("k_chunk", MARLIN_K_CHUNKS) @pytest.mark.parametrize("n_chunk", MARLIN_N_CHUNKS) @pytest.mark.parametrize("group_size", HQQ_SUPPORTED_GROUP_SIZES) @pytest.mark.parametrize("mnk_factors", MNK_FACTORS) @pytest.mark.parametrize("use_fp32_reduce", USE_FP32_REDUCE_OPTS) def test_hqq_marlin_gemm( k_chunk, n_chunk, group_size, mnk_factors, use_fp32_reduce, ): m_factor, n_factor, k_factor = mnk_factors size_m = m_factor size_k = k_chunk * k_factor size_n = n_chunk * n_factor quant_type = scalar_types.uint4 a_input = rand_data((size_m, size_k)) dev = a_input.device b_weight = torch.randint(0, 10, (size_n, size_k), dtype=torch.uint8, device=dev) scale = rand_data((size_n, size_k // group_size)) zero = rand_data((size_n, size_k // group_size)) gptq_w_q = gptq_pack(b_weight.transpose(1, 0), 4, size_k, size_n) sort_indices = torch.empty(0, dtype=torch.int, device=dev) marlin_w_q = ops.gptq_marlin_repack(gptq_w_q, sort_indices, size_k, size_n, 4).to( dev ) marlin_s = marlin_permute_scales( scale.transpose(1, 0), size_k, size_n, group_size ).to(dev) marlin_zp = marlin_permute_scales( zero.transpose(1, 0), size_k, size_n, group_size ).to(dev) g_idx = marlin_make_empty_g_idx(dev) g_idx_sort_indices = marlin_make_empty_g_idx(dev) workspace = marlin_make_workspace_new(b_weight.device) output = ops.gptq_marlin_gemm( a_input, None, marlin_w_q, None, marlin_s, None, None, marlin_zp, g_idx, g_idx_sort_indices, workspace, quant_type, a_input.shape[0], b_weight.shape[0], a_input.shape[1], is_k_full=True, use_fp32_reduce=use_fp32_reduce, is_zp_float=True, ) b_flat = b_weight.reshape(-1, group_size) zp_flat = zero.reshape(-1, 1) s_flat = scale.reshape(-1, 1) dequant = (b_flat - zp_flat) * s_flat output_ref = torch.matmul(a_input, dequant.reshape(b_weight.shape).transpose(1, 0)) torch.cuda.synchronize() max_diff = compute_max_diff(output, output_ref) assert max_diff < 0.04 def test_marlin_gemm_subset_input(): quant_type = scalar_types.uint4b8 group_size = 128 size_m, size_k, size_n = 32, 1024, 2048 big_m = size_m * 2 big_k = size_k * 2 a_input = rand_data((big_m, big_k))[8 : size_m + 8, 8 : size_k + 8] b_weight = rand_data((size_k, size_n)) w_ref, marlin_q_w, marlin_s, g_idx, sort_indices, _ = marlin_quantize( b_weight, quant_type, group_size, False ) marlin_zp = marlin_make_empty_g_idx(marlin_s.device) workspace = marlin_make_workspace_new(a_input.device) output = ops.gptq_marlin_gemm( a_input, None, marlin_q_w, None, marlin_s, None, None, marlin_zp, g_idx, sort_indices, workspace, quant_type, a_input.shape[0], b_weight.shape[1], a_input.shape[1], is_k_full=True, use_atomic_add=False, use_fp32_reduce=True, is_zp_float=False, ) output_ref = torch.matmul(a_input, w_ref) torch.cuda.synchronize() max_diff = compute_max_diff(output, output_ref) assert max_diff < 0.04 @pytest.mark.parametrize("size_m", [1, 256]) def test_marlin_gemm_with_bias(size_m): quant_type = scalar_types.uint4b8 group_size = 128 size_k, size_n = 1024, 2048 a_input = rand_data((size_m, size_k)) b_weight = rand_data((size_k, size_n)) b_bias = rand_data((size_n,)) * 10 marlin_bias = marlin_permute_bias(b_bias) w_ref, marlin_q_w, marlin_s, g_idx, sort_indices, _ = marlin_quantize( b_weight, quant_type, group_size, False ) marlin_zp = marlin_make_empty_g_idx(marlin_s.device) workspace = marlin_make_workspace_new(a_input.device) output = ops.gptq_marlin_gemm( a_input, None, marlin_q_w, marlin_bias, marlin_s, None, None, marlin_zp, g_idx, sort_indices, workspace, quant_type, a_input.shape[0], b_weight.shape[1], a_input.shape[1], is_k_full=True, use_atomic_add=False, use_fp32_reduce=True, is_zp_float=False, ) output_ref = torch.matmul(a_input, w_ref) + b_bias.view(1, -1) torch.cuda.synchronize() max_diff = compute_max_diff(output, output_ref) assert max_diff < 0.04
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_scaled_mm_kernel_selection.py
tests/kernels/quantization/test_scaled_mm_kernel_selection.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Tests for ScaledMM kernel selection logic (CPU-only) Run `pytest tests/kernels/quantization/test_scaled_mm_kernel_selection.py`. """ import inspect from abc import ABC import pytest from vllm.model_executor.layers.quantization.kernels.scaled_mm import ( ScaledMMLinearLayerConfig, ) from vllm.model_executor.layers.quantization.kernels.scaled_mm.aiter import ( AiterScaledMMLinearKernel, ) from vllm.model_executor.layers.quantization.kernels.scaled_mm.cpu import ( CPUScaledMMLinearKernel, ) from vllm.model_executor.layers.quantization.kernels.scaled_mm.ScaledMMLinearKernel import ( # noqa: E501 ScaledMMLinearKernel, ) pytestmark = pytest.mark.cpu_test def test_is_supported_is_abstract(): """Test that is_supported() is properly defined as abstract.""" assert issubclass(ScaledMMLinearKernel, ABC) assert hasattr(ScaledMMLinearKernel, "is_supported") def test_cpu_kernel_implements_is_supported(): """Test that CPUScaledMMLinearKernel implements is_supported() method.""" assert hasattr(CPUScaledMMLinearKernel, "is_supported"), ( "CPUScaledMMLinearKernel missing is_supported() method" ) # Verify it's a classmethod by checking if it can be called with the class # and by checking the method type assert inspect.ismethod(CPUScaledMMLinearKernel.is_supported) or inspect.isfunction( CPUScaledMMLinearKernel.is_supported ), "CPUScaledMMLinearKernel.is_supported() should be a classmethod" # Verify it can be called as a classmethod result, reason = CPUScaledMMLinearKernel.is_supported() assert isinstance(result, bool), "is_supported() should return a bool" assert reason is None or isinstance(reason, str), "reason should be str or None" def test_aiter_kernel_implements_is_supported(): """Test that AiterScaledMMLinearKernel implements is_supported() method.""" assert hasattr(AiterScaledMMLinearKernel, "is_supported"), ( "AiterScaledMMLinearKernel missing is_supported() method" ) # Verify it's a classmethod by checking if it can be called with the class # and by checking the method type assert inspect.ismethod( AiterScaledMMLinearKernel.is_supported ) or inspect.isfunction(AiterScaledMMLinearKernel.is_supported), ( "AiterScaledMMLinearKernel.is_supported() should be a classmethod" ) # Verify it can be called as a classmethod # (will return False on CPU, which is expected) result, reason = AiterScaledMMLinearKernel.is_supported() assert isinstance(result, bool), "is_supported() should return a bool" assert reason is None or isinstance(reason, str), "reason should be str or None" # On CPU, it should return False with a reason about requiring ROCm # This validates the method works correctly even on non-ROCm platforms def test_cpu_kernel_accepts_all_configs(): """Test that CPUScaledMMLinearKernel accepts all config combinations.""" configs = [ ScaledMMLinearLayerConfig( is_channelwise=False, is_static_input_scheme=True, input_symmetric=True, ), ScaledMMLinearLayerConfig( is_channelwise=True, is_static_input_scheme=False, input_symmetric=False, ), ] for config in configs: can_impl, reason = CPUScaledMMLinearKernel.can_implement(config) assert can_impl, ( f"CPUScaledMMLinearKernel should accept config {config}: {reason}" )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_awq.py
tests/kernels/quantization/test_awq.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from tests.kernels.utils import opcheck from vllm import _custom_ops as ops # noqa: F401 @pytest.mark.skipif( not hasattr(torch.ops._C, "awq_dequantize"), reason="AWQ is not supported on this GPU type.", ) def test_awq_dequantize_opcheck(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: m.setenv("VLLM_USE_TRITON_AWQ", "0") qweight = torch.randint( -2000000000, 2000000000, (8192, 256), device="cuda", dtype=torch.int32 ) scales = torch.rand((64, 2048), device="cuda", dtype=torch.float16) zeros = torch.empty((64, 256), device="cuda", dtype=torch.int32) split_k_iters = 0 thx = 0 thy = 0 opcheck( torch.ops._C.awq_dequantize, (qweight, scales, zeros, split_k_iters, thx, thy), ) @pytest.mark.skip(reason="Not working; needs investigation.") @pytest.mark.skipif( not hasattr(torch.ops._C, "awq_gemm"), reason="AWQ is not supported on this GPU type.", ) def test_awq_gemm_opcheck(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: m.setenv("VLLM_USE_TRITON_AWQ", "0") input = torch.rand((2, 8192), device="cuda", dtype=torch.float16) qweight = torch.randint( -2000000000, 2000000000, (8192, 256), device="cuda", dtype=torch.int32 ) scales = torch.empty((64, 2048), device="cuda", dtype=torch.float16) qzeros = torch.randint( -2000000000, 2000000000, (64, 256), device="cuda", dtype=torch.int32 ) split_k_iters = 8 opcheck(torch.ops._C.awq_gemm, (input, qweight, scales, qzeros, split_k_iters))
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_flashinfer_nvfp4_scaled_mm.py
tests/kernels/quantization/test_flashinfer_nvfp4_scaled_mm.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from nvfp4_utils import ( FLOAT4_E2M1_MAX, FLOAT8_E4M3_MAX, convert_swizzled_to_linear, dequantize_nvfp4_to_dtype, ) from vllm import _custom_ops as ops from vllm.platforms import current_platform from vllm.utils.flashinfer import flashinfer_scaled_fp4_mm if not current_platform.has_device_capability(100): pytest.skip( reason="Nvfp4 Requires compute capability of 10 or above.", allow_module_level=True, ) DTYPES = [torch.float16, torch.bfloat16] # m, n, k SHAPES = [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)] PAD_SHAPES = [(150, 128, 64), (128, 128, 96)] SHAPES.extend(PAD_SHAPES) SEEDS = [42] CUDA_DEVICES = ["cuda:0"] def get_ref_results( a_fp4, b_fp4, a_sf, b_sf, a_global_scale, b_global_scale, m, n, dtype, block_size, device, ): _, m_k = a_fp4.shape _, n_k = b_fp4.shape assert m_k == n_k a_in_dtype = dequantize_nvfp4_to_dtype( a_fp4, a_sf, a_global_scale, dtype=dtype, device=device, block_size=block_size ) b_in_dtype = dequantize_nvfp4_to_dtype( b_fp4, b_sf, b_global_scale, dtype=dtype, device=device, block_size=block_size ) return torch.matmul(a_in_dtype, b_in_dtype.t()) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("shape", SHAPES) @pytest.mark.parametrize("seed", SEEDS) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.parametrize("backend", ["cutlass", "trtllm"]) @pytest.mark.parametrize("autotune", [False, True]) @torch.inference_mode() def test_flashinfer_nvfp4_gemm( dtype: torch.dtype, shape: tuple[int, int, int], seed: int, device: str, backend: str, autotune: bool, ) -> None: if backend == "trtllm" and dtype == torch.float16: pytest.skip("Only torch.bfloat16 is supported for TRTLLM FP4 GEMM operations") current_platform.seed_everything(seed) m, n, packed_k = shape k = packed_k * 2 block_size = 16 a_dtype = torch.randn((m, k), dtype=dtype, device=device) b_dtype = torch.randn((n, k), dtype=dtype, device=device) a_global_scale = ( (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1) ).to(torch.float32) b_global_scale = ( (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(b_dtype.flatten(), dim=-1) ).to(torch.float32) alpha = 1.0 / (a_global_scale * b_global_scale) # ops.scaled_fp4_quant returns swizzled scales, while weights # from checkpoints are in linear scales. # So instead of needing to swizzle for cutlass as in modelopt.py, # we need to unswizzle for trtllm here. a_fp4, a_scale_interleaved = ops.scaled_fp4_quant(a_dtype, a_global_scale) b_fp4, b_scale_interleaved = ops.scaled_fp4_quant(b_dtype, b_global_scale) # get_ref_results unswizzles the scales internally. expected_out = get_ref_results( a_fp4, b_fp4, a_scale_interleaved, b_scale_interleaved, a_global_scale, b_global_scale, m, n, dtype, block_size, device, ) import flashinfer if backend == "trtllm": epilogue_tile_m = 128 b_fp4 = flashinfer.shuffle_matrix_a(b_fp4.view(torch.uint8), epilogue_tile_m) b_scale_interleaved = convert_swizzled_to_linear( b_scale_interleaved, n, k, block_size ) b_scale_interleaved = ( flashinfer.shuffle_matrix_sf_a( b_scale_interleaved.view(torch.uint8), epilogue_tile_m ) .reshape(b_scale_interleaved.shape) .view(torch.float8_e4m3fn) ) with flashinfer.autotune(autotune): out = flashinfer_scaled_fp4_mm( a_fp4, b_fp4, a_scale_interleaved, b_scale_interleaved, alpha, dtype, backend=backend, ) torch.testing.assert_close(out, expected_out.to(dtype=dtype), atol=1e-1, rtol=1e-1)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_gguf.py
tests/kernels/quantization/test_gguf.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from pathlib import Path import pytest import torch from gguf import GGMLQuantizationType, GGUFReader, ReaderTensor, dequantize from huggingface_hub import snapshot_download import vllm._custom_ops as ops from vllm.model_executor.layers.fused_moe import fused_experts from vllm.model_executor.layers.quantization.gguf import _fused_moe_gguf from vllm.platforms import current_platform GGUF_SAMPLE = snapshot_download("Isotr0py/test-gguf-sample") GGUF_SAMPLE_MOE = snapshot_download("SzymonOzog/test-gguf-moe-sample") def get_gguf_sample_tensors( hidden_size: int, quant_type: GGMLQuantizationType ) -> list[ReaderTensor]: sample_dir = GGUF_SAMPLE filename = f"Quant_{quant_type.name}_{hidden_size}.gguf" sample_file = Path(sample_dir) / filename return GGUFReader(sample_file).tensors def get_gguf_MoE_tensors( hidden_size: int, quant_type: GGMLQuantizationType ) -> list[ReaderTensor]: sample_dir = GGUF_SAMPLE_MOE filename = f"Quant_{quant_type.name}_{hidden_size}.gguf" sample_file = Path(sample_dir) / filename return GGUFReader(sample_file).tensors DTYPES = [torch.bfloat16] # [torch.half, torch.bfloat16, torch.float32] # Hidden_size for testing, must match the sample file in HF repo, # we have `hidden_size = 256, 1024` for test in HF repo currently. HIDDEN_SIZES = [256, 1024] NUM_TOKENS = [7, 2050] # Arbitrary values for testing SEEDS = [0] QUANT_TYPES = [ # i-matrix GGMLQuantizationType.IQ1_M, GGMLQuantizationType.IQ1_S, GGMLQuantizationType.IQ2_S, GGMLQuantizationType.IQ2_XS, GGMLQuantizationType.IQ3_S, GGMLQuantizationType.IQ3_XXS, GGMLQuantizationType.IQ4_NL, GGMLQuantizationType.IQ4_XS, # k-quants GGMLQuantizationType.Q2_K, GGMLQuantizationType.Q3_K, GGMLQuantizationType.Q4_K, GGMLQuantizationType.Q5_K, GGMLQuantizationType.Q6_K, # standard quantization GGMLQuantizationType.Q4_0, GGMLQuantizationType.Q5_0, GGMLQuantizationType.Q8_0, ] @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("quant_type", QUANT_TYPES) @torch.inference_mode() def test_dequantize( hidden_size: int, dtype: torch.dtype, quant_type: GGMLQuantizationType ): tensors = get_gguf_sample_tensors(hidden_size, quant_type) for tensor in tensors: shape_str = tensor.name.split("_")[-1] shape = map(int, shape_str.split("x")) ref_output = torch.tensor( dequantize(tensor.data, quant_type), device="cuda" ).to(dtype) output = ops.ggml_dequantize( torch.tensor(tensor.data, device="cuda"), quant_type, *list(shape), dtype ) torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=4e-2) @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("quant_type", QUANT_TYPES) @torch.inference_mode() def test_mmvq(hidden_size: int, dtype: torch.dtype, quant_type: GGMLQuantizationType): current_platform.seed_everything(0) tensors = get_gguf_sample_tensors(hidden_size, quant_type) x = torch.rand((1, hidden_size), dtype=dtype, device="cuda") for tensor in tensors: weight = torch.tensor(dequantize(tensor.data, quant_type), device="cuda").to( dtype ) ref_output = x @ weight.T qweight = torch.tensor(tensor.data, device="cuda") output = ops.ggml_mul_mat_vec_a8(qweight, x, quant_type, qweight.shape[0]).to( dtype ) torch.testing.assert_close(output, ref_output, atol=1, rtol=1e-1) @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize( "quant_type", [ # k-quants GGMLQuantizationType.Q2_K, GGMLQuantizationType.Q3_K, GGMLQuantizationType.Q4_K, GGMLQuantizationType.Q5_K, GGMLQuantizationType.Q6_K, # standard quants GGMLQuantizationType.Q4_0, GGMLQuantizationType.Q5_0, GGMLQuantizationType.Q8_0, ], ) @torch.inference_mode() def test_mmq( num_tokens: int, hidden_size: int, dtype: torch.dtype, quant_type: GGMLQuantizationType, ): current_platform.seed_everything(0) tensors = get_gguf_sample_tensors(hidden_size, quant_type) x = torch.rand((num_tokens, hidden_size), dtype=dtype, device="cuda") for tensor in tensors: weight = torch.tensor(dequantize(tensor.data, quant_type), device="cuda").to( dtype ) ref_output = x @ weight.T qweight = torch.tensor(tensor.data, device="cuda") output = ops.ggml_mul_mat_a8(qweight, x, quant_type, qweight.shape[0]) atols = {torch.half: 1, torch.bfloat16: 1.5, torch.float: 1.2} # test matrix has inputs centered around 0 and lower precision from # bfloat16 tends to accumulate and can greatly inflate rtol # since outputs are also very close to 0 rtols = {torch.half: 1e-1, torch.bfloat16: 1e4, torch.float: 2e1} torch.testing.assert_close( output, ref_output, atol=atols[dtype], rtol=rtols[dtype] ) @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("hidden_size", [512]) @pytest.mark.parametrize("top_k", [4, 8]) @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("quant_type", QUANT_TYPES) @torch.inference_mode() def test_moe( num_tokens: int, hidden_size: int, dtype: torch.dtype, quant_type: GGMLQuantizationType, top_k: int, ): current_platform.seed_everything(0) H, E = 1024, 256 x = torch.rand((num_tokens, H), dtype=dtype, device="cuda") topk_weights = torch.rand(num_tokens, top_k, device="cuda", dtype=dtype) topk_ids = torch.randint( 0, E, (num_tokens, top_k), device="cuda", dtype=torch.int32 ) tensors = get_gguf_MoE_tensors(hidden_size, quant_type) w13 = tensors[0] w2 = tensors[1] w13_dequant = torch.tensor(dequantize(w13.data, quant_type), device="cuda").to( dtype ) w2_dequant = torch.tensor(dequantize(w2.data, quant_type), device="cuda").to(dtype) output = _fused_moe_gguf( x, torch.tensor(w13.data, device="cuda"), torch.tensor(w2.data, device="cuda"), topk_weights, topk_ids, quant_type, quant_type, "silu", ) ref_output = fused_experts( x, w13_dequant, w2_dequant, topk_weights, topk_ids ).reshape(output.shape) torch.testing.assert_close(output, ref_output, atol=1, rtol=1e-1)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_int8_kernel.py
tests/kernels/quantization/test_int8_kernel.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Adapted from https://github.com/sgl-project/sglang/blob/main/test/srt/test_int8_kernel.py import itertools import pytest import torch from vllm.model_executor.layers.activation import SiluAndMul from vllm.model_executor.layers.fused_moe import fused_experts from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig from vllm.model_executor.layers.quantization.utils.int8_utils import ( per_token_quant_int8, ) from vllm.platforms import current_platform if current_platform.get_device_capability() < (7, 0): pytest.skip("INT8 Triton requires CUDA 7.0 or higher", allow_module_level=True) def native_w8a8_per_token_matmul(A, B, As, Bs, output_dtype=torch.float16): """Matrix multiplication function that supports per-token input quantization and per-column weight quantization""" A = A.to(torch.float32) B = B.to(torch.float32) assert A.shape[-1] == B.shape[-1], "Dimension mismatch" assert B.ndim == 2 and B.is_contiguous(), "B must be a 2D contiguous tensor" # Reshape input M = A.numel() // A.shape[-1] B = B.t() # Transpose weight matrix N, K = B.shape origin_C_shape = A.shape[:-1] + (K,) A = A.reshape(M, N) # As is per-token [M, 1], Bs is per-column [1, K] C = torch.matmul(A, B) # [M, K] C = As * C * Bs.view(1, -1) # Broadcast per-column scale return C.reshape(origin_C_shape).to(output_dtype) def torch_w8a8_per_column_moe(a, w1, w2, w1_s, w2_s, topk, topk_weight, topk_ids): """This function performs fused moe with per-column int8 quantization using native torch.""" B, D = a.shape # Perform per-token quantization a_q, a_s = per_token_quant_int8(a) # Repeat tokens to match topk a_q = a_q.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) # Also repeat the scale a_s = a_s.view(B, -1, 1).repeat(1, topk, 1).reshape(-1, 1) # [B*topk, 1] out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device) # Calculate routing topk_weight = topk_weight.view(-1) topk_ids = topk_ids.view(-1) # Process each expert for i in range(w1.shape[0]): mask = topk_ids == i if mask.sum(): # First MLP layer: note that a_s is now per-token inter_out = native_w8a8_per_token_matmul( a_q[mask], w1[i], a_s[mask], w1_s[i], output_dtype=a.dtype ) # Activation function act_out = SiluAndMul().forward_native(inter_out) # Quantize activation output with per-token act_out_q, act_out_s = per_token_quant_int8(act_out) # Second MLP layer out[mask] = native_w8a8_per_token_matmul( act_out_q, w2[i], act_out_s, w2_s[i], output_dtype=a.dtype ) # Apply routing weights and sum return ( out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype) ).sum(dim=1) @pytest.fixture(autouse=True, scope="module") def setup_cuda(): """Sets the default CUDA device for all tests in this module.""" torch.set_default_device("cuda") DTYPES = [torch.half, torch.bfloat16] M = [1, 33] N = [128, 1024] K = [256, 4096] E = [8] TOP_KS = [2, 6] SEEDS = [0] @pytest.mark.parametrize( "M, N, K, E, topk, dtype, seed", itertools.product(M, N, K, E, TOP_KS, DTYPES, SEEDS), ) @torch.inference_mode() def test_w8a8_fp8_fused_moe(M, N, K, E, topk, dtype, seed): torch.manual_seed(seed) # Initialize int8 quantization parameters factor_for_scale = 1e-2 int8_max = 127 int8_min = -128 # Input tensor # M * K a = torch.randn((M, K), dtype=dtype) / 10 # Generate int8 weights w1_fp32 = (torch.rand((E, 2 * N, K), dtype=torch.float32) - 0.5) * 2 w1 = (w1_fp32 * int8_max).clamp(min=int8_min, max=int8_max).to(torch.int8) w2_fp32 = (torch.rand((E, K, N), dtype=torch.float32) - 0.5) * 2 w2 = (w2_fp32 * int8_max).clamp(min=int8_min, max=int8_max).to(torch.int8) # Generate scale for each column (per-column quantization) w1_s = torch.rand(E, 2 * N, device=w1_fp32.device) * factor_for_scale w2_s = torch.rand(E, K, device=w2_fp32.device) * factor_for_scale score = torch.randn((M, E), dtype=dtype) score = torch.softmax(score, dim=-1, dtype=torch.float32) topk_weights, topk_ids = torch.topk(score, topk) ref_out = torch_w8a8_per_column_moe( a, w1, w2, w1_s, w2_s, topk, topk_weights, topk_ids ) quant_config = FusedMoEQuantConfig.make( torch.int8, per_act_token_quant=True, block_shape=None, w1_scale=w1_s, w2_scale=w2_s, ) out = fused_experts( a, w1, w2, topk_weights, topk_ids, quant_config=quant_config, ) # Check results rel_diff = torch.mean( torch.abs(out.to(torch.float32) - ref_out.to(torch.float32)) ) / torch.mean(torch.abs(ref_out.to(torch.float32))) assert rel_diff < 0.05
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/tests/kernels/quantization/test_cutlass_scaled_mm.py
tests/kernels/quantization/test_cutlass_scaled_mm.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Tests for cutlass kernels Run `pytest tests/kernels/quantization/test_cutlass_scaled_mm.py`. """ import random import pytest import torch from tests.kernels.utils import baseline_scaled_mm, opcheck, to_fp8, to_int8 from vllm import _custom_ops as ops from vllm.platforms import current_platform from vllm.utils.math_utils import cdiv if not current_platform.is_cuda(): pytest.skip("These tests use CUTLASS which requires CUDA", allow_module_level=True) MNK_FACTORS = [ (1, 256, 128), (1, 16384, 1024), (1, 24576, 496), (16, 256, 496), (16, 16384, 128), (16, 24576, 4096), (32, 8192, 4096), (32, 16384, 4096), (33, 1024, 1024), (33, 8192, 128), (64, 2048, 496), (64, 16384, 1024), (100, 8192, 496), (128, 32768, 4096), (256, 4096, 4096), (512, 256, 1024), (512, 8192, 4096), (512, 16384, 128), (512, 24576, 128), ] CUDA_DEVICES = [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)] # -1 means full extent in that dimension TENSORWISE_GROUP_SHAPE = (-1, -1) PER_TOKEN_GROUP_SHAPE = (1, -1) PER_OUT_CH_GROUP_SHAPE = (-1, 1) capability = current_platform.get_device_capability() capability = capability[0] * 10 + capability[1] def rand_int8(shape: tuple, device: str = "cuda"): return to_int8(torch.rand(shape, device=device) * 255 - 128) def group_scale_helper(shape, group_shape): return [shape[i] if s < 0 else s for i, s in enumerate(group_shape)] def scale_shape(shape, group_shape): assert len(shape) == len(group_shape) group_shape = group_scale_helper(shape, group_shape) return tuple(cdiv(shape[i], group_shape[i]) for i in range(len(group_shape))) def cutlass_fp8_gemm_helper( m: int, n: int, k: int, a_scale_group_shape: tuple, b_scale_group_shape: tuple, use_bias: bool, out_dtype: type[torch.dtype] = torch.bfloat16, device: str = "cuda", ): # Test for a cutlass kernel with per-token activation quantization # and per-output channel weight quantization. a = to_fp8(torch.randn((m, k), device=device)) b = to_fp8(torch.randn((n, k), device=device).t()) a_scales_shape = scale_shape(a.shape, a_scale_group_shape) b_scales_shape = scale_shape(b.shape, b_scale_group_shape) scale_a = torch.randn(a_scales_shape, device=device, dtype=torch.float32) scale_b = torch.randn(b_scales_shape, device=device, dtype=torch.float32) # make scales M-major for blockwise quant, doesn't affect 1D scales scale_a = scale_a.t().contiguous().t() # make scales K-major for blockwise quant, doesn't affect 1D scales scale_b = scale_b.t().contiguous().t() bias = torch.rand((n,), device=device, dtype=out_dtype) * 10 if use_bias else None out = ops.cutlass_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias) baseline = baseline_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias) torch.testing.assert_close(out, baseline, rtol=5e-1, atol=1.5e-1) opcheck(torch.ops._C.cutlass_scaled_mm, (out, a, b, scale_a, scale_b, bias)) def cutlass_int8_gemm_helper( m: int, n: int, k: int, a_scale_group_shape: tuple, b_scale_group_shape: tuple, use_bias: bool, out_dtype: type[torch.dtype] = torch.bfloat16, device: str = "cuda", ): # Test for a cutlass kernel with per-token activation quantization # and per-output channel weight quantization. a = to_int8(torch.randn((m, k), device=device) * 5) b = to_int8(torch.randn((n, k), device=device).t() * 5) a_scales_shape = scale_shape(a.shape, a_scale_group_shape) b_scales_shape = scale_shape(b.shape, b_scale_group_shape) scale_a = torch.randn(a_scales_shape, device=device, dtype=torch.float32) scale_b = torch.randn(b_scales_shape, device=device, dtype=torch.float32) bias = torch.rand((n,), device=device, dtype=out_dtype) * 10 if use_bias else None out = ops.cutlass_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias) baseline = baseline_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias) torch.testing.assert_close(out, baseline, rtol=1e-1, atol=1e0) opcheck(torch.ops._C.cutlass_scaled_mm, (out, a, b, scale_a, scale_b, bias)) @pytest.mark.parametrize("m,n,k", MNK_FACTORS) @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.skipif( not current_platform.has_device_capability(89), reason="FP8 is not supported on this GPU type.", ) def test_cutlass_fp8_gemm( m: int, n: int, k: int, a_scale_group_shape, b_scale_group_shape, use_bias: bool ): cutlass_fp8_gemm_helper(m, n, k, a_scale_group_shape, b_scale_group_shape, use_bias) @pytest.mark.parametrize("m,n,k", MNK_FACTORS) @pytest.mark.parametrize( "a_scale_group_shape,b_scale_group_shape", [((1, 128), (128, 128))] ) @pytest.mark.parametrize("use_bias", [False]) @pytest.mark.skipif( not current_platform.has_device_capability(90), reason="FP8 blockwise is not supported on this GPU type.", ) def test_cutlass_fp8_blockwise_scale_gemm( m: int, n: int, k: int, a_scale_group_shape, b_scale_group_shape, use_bias: bool ): if k % b_scale_group_shape[0] != 0 or n % b_scale_group_shape[1] != 0: return if m % a_scale_group_shape[0] != 0 or k % a_scale_group_shape[1] != 0: return if m % 4 != 0 and current_platform.has_device_capability(100): return cutlass_fp8_gemm_helper(m, n, k, a_scale_group_shape, b_scale_group_shape, use_bias) @pytest.mark.parametrize("m,n,k", MNK_FACTORS) @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("use_bias", [True, False]) def test_cutlass_int8_gemm( m: int, n: int, k: int, a_scale_group_shape, b_scale_group_shape, use_bias: bool ): cutlass_int8_gemm_helper( m, n, k, a_scale_group_shape, b_scale_group_shape, use_bias ) @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("out_dtype", [torch.bfloat16, torch.float16]) @pytest.mark.parametrize("use_bias", [True, False]) def test_cutlass_int8_gemm_output_dtype( a_scale_group_shape, b_scale_group_shape, out_dtype: type[torch.dtype], use_bias: bool, ): cutlass_int8_gemm_helper( 512, 512, 512, a_scale_group_shape, b_scale_group_shape, use_bias, out_dtype=out_dtype, ) @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("out_dtype", [torch.bfloat16, torch.float16]) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.skipif( not current_platform.has_device_capability(89), reason="FP8 is not supported on this GPU type.", ) def test_cutlass_fp8_gemm_output_dtype( a_scale_group_shape, b_scale_group_shape, out_dtype: type[torch.dtype], use_bias: bool, ): cutlass_fp8_gemm_helper( 512, 512, 512, a_scale_group_shape, b_scale_group_shape, use_bias, out_dtype=out_dtype, ) @pytest.mark.parametrize( "a_scale_group_shape,b_scale_group_shape", [((1, 128), (128, 128))] ) @pytest.mark.parametrize("out_dtype", [torch.bfloat16, torch.float16]) @pytest.mark.parametrize("use_bias", [False]) @pytest.mark.skipif( not current_platform.has_device_capability(90), reason="FP8 blockwise is not supported on this GPU type.", ) def test_cutlass_fp8_blockwise_scale_gemm_dtype( a_scale_group_shape, b_scale_group_shape, out_dtype: type[torch.dtype], use_bias: bool, ): cutlass_fp8_gemm_helper( 512, 512, 512, a_scale_group_shape, b_scale_group_shape, use_bias, out_dtype=out_dtype, ) @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.parametrize("device", CUDA_DEVICES) @pytest.mark.skipif( not current_platform.has_device_capability(89), reason="FP8 is not supported on this GPU type.", ) def test_cutlass_fp8_gemm_devices( a_scale_group_shape, b_scale_group_shape, use_bias: bool, device: str ): cutlass_fp8_gemm_helper( 512, 512, 512, a_scale_group_shape, b_scale_group_shape, use_bias, torch.bfloat16, device, ) @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.parametrize("device", CUDA_DEVICES) def test_cutlass_int8_gemm_devices( a_scale_group_shape, b_scale_group_shape, use_bias: bool, device: str ): cutlass_int8_gemm_helper( 512, 512, 512, a_scale_group_shape, b_scale_group_shape, use_bias, out_dtype=torch.bfloat16, device=device, ) # For the following two tests: # N and K correspond to the size of the weight matrix and likely to be multiples # of a large power of two. In any case, the kernel will have a naive fallback # when N and K are not divisible by 16. But M is the number of tokens and the # kernel must handle any M thrown at it. @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.skipif( not current_platform.has_device_capability(89), reason="FP8 is not supported on this GPU type.", ) def test_cutlass_fp8_gemm_m_sweep( a_scale_group_shape, b_scale_group_shape, use_bias: bool ): for nk in range(32, 128, 32): for m in range(1, 128): cutlass_fp8_gemm_helper( m, nk, nk, a_scale_group_shape, b_scale_group_shape, use_bias ) @pytest.mark.parametrize( "a_scale_group_shape", [PER_TOKEN_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize( "b_scale_group_shape", [PER_OUT_CH_GROUP_SHAPE, TENSORWISE_GROUP_SHAPE] ) @pytest.mark.parametrize("use_bias", [True, False]) def test_cutlass_int8_gemm_m_sweep( a_scale_group_shape, b_scale_group_shape, use_bias: bool ): for nk in range(32, 128, 32): for m in range(1, 128): cutlass_int8_gemm_helper( m, nk, nk, a_scale_group_shape, b_scale_group_shape, use_bias ) @pytest.mark.parametrize("m", [32, 64, 128]) @pytest.mark.parametrize("n", [16, 32, 64]) @pytest.mark.parametrize("k", [64, 128, 256]) @pytest.mark.parametrize("out_dtype", [torch.bfloat16, torch.float16]) @pytest.mark.skip def test_cutlass_int8_azp_bias_fold(m: int, n: int, k: int, out_dtype: torch.dtype): # Currently, the test is failing because folding azp into # 16-bit bias loses too much precision scale_a = torch.randn((1, 1), device="cuda", dtype=torch.float32) / 10 scale_b = torch.randn((1, n), device="cuda", dtype=torch.float32) / 10 aq_i8 = rand_int8((m, k)) bq_i8 = rand_int8((n, k)).t() aq_i32 = aq_i8.to(dtype=torch.int32) bq_i32 = bq_i8.to(dtype=torch.int32) aq_f32 = aq_i8.to(dtype=torch.float32) bq_f32 = bq_i8.to(dtype=torch.float32) b_dq = scale_b * bq_f32 azp_a = torch.rand((1,), device="cuda", dtype=torch.float32) * 10 + 1.5 azp_aq_i8 = (azp_a / scale_a).to(dtype=torch.int8) azp_a = azp_aq_i8.to(dtype=torch.float32) * scale_a # correct for rounding a_dq = scale_a * (aq_i32 + azp_aq_i8).to(dtype=torch.float32) torch.testing.assert_close(a_dq, scale_a * aq_f32 + azp_a) baseline_dq = torch.mm(a_dq, b_dq).to(out_dtype) J = torch.ones((1, k), device="cuda", dtype=torch.float32) azp_bias = (azp_a * scale_b * (J @ bq_f32)).to(out_dtype) assert azp_bias.shape == (1, n) assert azp_bias[0, :].shape == (n,) baseline_q = ( scale_a.to(device="cpu") * scale_b.to(device="cpu") * ((aq_i32 + azp_aq_i8).to(device="cpu") @ bq_i32.to(device="cpu")) ).to(dtype=out_dtype, device="cuda") out = ops.cutlass_scaled_mm( aq_i8, bq_i8, scale_a, scale_b, out_dtype=out_dtype, bias=azp_bias[0, :] ) torch.testing.assert_close(out, baseline_dq, rtol=1e-2, atol=1e0) torch.testing.assert_close(out, baseline_q, rtol=1e-2, atol=1e0) @pytest.mark.parametrize("m", [32, 64, 128]) @pytest.mark.parametrize("n", [16, 32, 64]) @pytest.mark.parametrize("k", [64, 128, 256]) @pytest.mark.parametrize("out_dtype", [torch.bfloat16, torch.float16]) @pytest.mark.parametrize("use_bias", [True, False]) @pytest.mark.parametrize("azp_per_token", [True, False]) def test_cutlass_int8_azp( m: int, n: int, k: int, out_dtype: torch.dtype, use_bias: bool, azp_per_token: bool ): m_azp = m if azp_per_token else 1 scale_a = torch.randn((m_azp, 1), device="cuda", dtype=torch.float32) / 10 scale_b = torch.randn((1, n), device="cuda", dtype=torch.float32) / 10 aq_i8 = rand_int8((m, k)) aq_i32 = aq_i8.to(dtype=torch.int32) aq_f32 = aq_i8.to(dtype=torch.float32) bq_i8 = rand_int8((n, k)).t() bq_i32 = bq_i8.to(dtype=torch.int32) bq_f32 = bq_i8.to(dtype=torch.float32) b_dq = scale_b * bq_f32 azp_a = torch.rand((m_azp, 1), device="cuda", dtype=torch.float32) * 10 + 1.5 azp_aq_i8 = (azp_a / scale_a).to(dtype=torch.int8) azp_a = azp_aq_i8.to(dtype=torch.float32) * scale_a # correct for rounding a_dq = scale_a * (aq_i32 - azp_aq_i8).to(dtype=torch.float32) torch.testing.assert_close(a_dq, scale_a * aq_f32 - azp_a, rtol=1e-4, atol=1e-3) if use_bias: bias = torch.rand((1, n), device="cuda", dtype=out_dtype) * 10 + 2.5 else: bias = torch.zeros((1, n), device="cuda", dtype=out_dtype) baseline_dq = (torch.mm(a_dq, b_dq) + bias).to(out_dtype) # int32 mm not supported on CUDA a_noazp_i32_cpu = (aq_i32 - azp_aq_i8).to(device="cpu") cq = (a_noazp_i32_cpu @ bq_i32.to(device="cpu")).to(device="cuda") baseline_q = (scale_a * scale_b * cq + bias).to(dtype=out_dtype) # Hadamard is just the sum of the cols azp_adj_i32 = bq_i32.sum(dim=0, keepdim=True, dtype=torch.int32) azp_i32 = azp_aq_i8.to(dtype=torch.int32) func_bias = bias if use_bias else None if azp_per_token: out = ops.cutlass_scaled_mm_azp( aq_i8, bq_i8, scale_a, scale_b, out_dtype, azp_adj_i32, azp_i32, func_bias ) else: azp_with_adj_i32 = azp_i32 * azp_adj_i32 out = ops.cutlass_scaled_mm_azp( aq_i8, bq_i8, scale_a, scale_b, out_dtype, azp_with_adj_i32, None, func_bias ) # bfloat16 precision is 7-bit mantissa -> 2^-8 ~ 0.4% # float16 precision is 10-bit mantissa -> 2^-11 ~ 0.05% rtol = 1e-2 if out_dtype == torch.bfloat16 else 1e-3 atol = 1e-3 torch.testing.assert_close(out, baseline_dq, rtol=rtol, atol=atol) torch.testing.assert_close(out, baseline_q, rtol=rtol, atol=atol) if azp_per_token: opcheck( torch.ops._C.cutlass_scaled_mm_azp, (out, aq_i8, bq_i8, scale_a, scale_b, azp_adj_i32, azp_i32, func_bias), ) else: opcheck( torch.ops._C.cutlass_scaled_mm_azp, (out, aq_i8, bq_i8, scale_a, scale_b, azp_with_adj_i32, None, func_bias), ) # Test working with a subset of A and B def test_cutlass_subset(): big_m, big_n, big_k = 1024, 1024, 1024 m, n, k = 512, 512, 512 whole_a = to_int8(torch.randn((big_m, big_k), device="cuda") * 5) whole_b = to_int8(torch.randn((big_n, big_k), device="cuda").t() * 5) a = whole_a[0:m, 0:k] b = whole_b[0:k, 0:n] scale_a = torch.randn((1, 1), device="cuda", dtype=torch.float32) / 10 scale_b = torch.randn((1, 1), device="cuda", dtype=torch.float32) / 10 out = ops.cutlass_scaled_mm(a, b, scale_a, scale_b, out_dtype=torch.bfloat16) baseline = baseline_scaled_mm(a, b, scale_a, scale_b, out_dtype=torch.bfloat16) torch.testing.assert_close(out, baseline, rtol=1e-1, atol=1e0) # Test to make sure cuda graphs work class CutlassLayer(torch.nn.Module): def __init__(self, b, scale_a, scale_b, out_dtype): super().__init__() self.b = b self.scale_a = scale_a self.scale_b = scale_b self.out_dtype = out_dtype def forward(self, a): return ops.cutlass_scaled_mm( a, self.b, self.scale_a, self.scale_b, self.out_dtype ) @pytest.mark.parametrize("per_act_token", [True, False]) @pytest.mark.parametrize("per_out_ch", [True, False]) def test_cutlass_cuda_graph(per_act_token: bool, per_out_ch: bool): m, n, k = 512, 512, 512 a = to_int8(torch.randn((m, k), device="cuda")) b = to_int8(torch.randn((n, k), device="cuda").t()) m_a_scales = m if per_act_token else 1 n_b_scales = n if per_out_ch else 1 scale_a = torch.randn((m_a_scales, 1), device="cuda", dtype=torch.float32) / 10 scale_b = torch.randn((1, n_b_scales), device="cuda", dtype=torch.float32) / 10 # Construct a trivial model with a single layer that calls a CUTLASS kernel model = CutlassLayer(b, scale_a, scale_b, torch.bfloat16) # Run the model with a cuda graph stream = torch.cuda.Stream() with torch.cuda.stream(stream): g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): out = model(a) out.zero_() g.replay() baseline = torch.mm( scale_a * a.to(dtype=torch.float32), scale_b * b.to(dtype=torch.float32) ).to(torch.bfloat16) torch.testing.assert_close(out, baseline, rtol=1e-1, atol=1e0) def test_cutlass_support_opcheck(): opcheck(torch.ops._C.cutlass_scaled_mm_supports_fp8, (capability,)) @pytest.mark.parametrize("num_experts", [8, 64]) @pytest.mark.parametrize("per_act_token", [True, False]) @pytest.mark.parametrize("per_out_ch", [True, False]) @pytest.mark.parametrize("use_bias", [False]) @pytest.mark.skipif( (lambda x: x is None or not ops.cutlass_group_gemm_supported(x.to_int()))( current_platform.get_device_capability() ), reason="Grouped gemm is not supported on this GPU type.", ) def test_cutlass_fp8_group_gemm( num_experts: int, per_act_token: bool, per_out_ch: bool, use_bias: bool ): # Device and dtype setup device = "cuda" out_dtype = torch.half # Create separate A, B, C tensors for each group a_tensors = [] b_tensors = [] a_scales_tensors = [] b_scales_tensors = [] baseline_tensors = [] expert_offsets = torch.zeros((num_experts + 1), device=device, dtype=torch.int64) problem_sizes = torch.zeros((num_experts, 3), device=device, dtype=torch.int32) if not per_act_token: one_scale_a = torch.randn((1, 1), device=device, dtype=torch.float32) alignment = 16 # 128 // 8 # For variation, each group has dimensions n_g = alignment * random.randint(1, 64) k_g = alignment * random.randint(1, 64) for g in range(num_experts): m_g = alignment * random.randint(1, 64) expert_offsets[g + 1] = expert_offsets[g] + m_g problem_sizes[g][0] = m_g problem_sizes[g][1] = n_g problem_sizes[g][2] = k_g m_a_scales = m_g if per_act_token else 1 n_b_scales = n_g if per_out_ch else 1 # Create group-specific A and B (FP8) and output (FP16/FP32) a_g = to_fp8(torch.randn((m_g, k_g), device=device)) b_g = to_fp8(torch.randn((n_g, k_g), device=device).t()) a_tensors.append(a_g) b_tensors.append(b_g) # Set up A/B scales scale_b = torch.randn((1, n_b_scales), device=device, dtype=torch.float32) b_scales_tensors.append(scale_b) if per_act_token: scale_a = torch.randn((m_a_scales, 1), device=device, dtype=torch.float32) a_scales_tensors.append(scale_a) else: scale_a = one_scale_a # Compute baseline result for this group baseline_g = baseline_scaled_mm(a_g, b_g, scale_a, scale_b, out_dtype, None) baseline_tensors.append(baseline_g) a_tensors_stacked = torch.empty( (expert_offsets[num_experts], k_g), device=device, dtype=torch.float8_e4m3fn ) b_tensors_stacked = torch.empty( (num_experts, n_g, k_g), device=device, dtype=torch.float8_e4m3fn ) for g in range(num_experts): a_tensors_stacked[expert_offsets[g] : expert_offsets[g + 1]] = a_tensors[g] b_tensors_stacked[g] = b_tensors[g].t() b_tensors_stacked = b_tensors_stacked.transpose(1, 2) if per_act_token: a_scales_tensors_stacked = torch.empty( (expert_offsets[num_experts], 1), device=device, dtype=torch.float32 ) for g in range(num_experts): a_scales_tensors_stacked[expert_offsets[g] : expert_offsets[g + 1]] = ( a_scales_tensors[g] ) else: a_scales_tensors_stacked = one_scale_a b_scales_tensors_stacked = torch.empty( (num_experts, n_b_scales), device=device, dtype=torch.float32 ) for g in range(num_experts): b_scales_tensors_stacked[g] = b_scales_tensors[g] out_tensors_stacked = torch.zeros( (expert_offsets[num_experts], n_g), device=device, dtype=out_dtype ) ab_strides = torch.full( (num_experts,), a_tensors_stacked.stride(0), device="cuda", dtype=torch.int64 ) c_strides = torch.full( (num_experts,), out_tensors_stacked.stride(0), device="cuda", dtype=torch.int64 ) ops.cutlass_moe_mm( out_tensors_stacked, a_tensors_stacked, b_tensors_stacked, a_scales_tensors_stacked, b_scales_tensors_stacked, expert_offsets[:-1], problem_sizes, ab_strides, ab_strides, c_strides, per_act_token, per_out_ch, ) # Validate each group's result against the baseline for g in range(num_experts): baseline = baseline_tensors[g] c = out_tensors_stacked[expert_offsets[g] : expert_offsets[g + 1]] torch.testing.assert_close(c, baseline, rtol=1e-2, atol=5e-4)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false