sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
vllm-project/vllm:tests/models/multimodal/pooling/test_siglip.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any import pytest from transformers import SiglipModel from ....conftest import IMAGE_ASSETS, HfRunner, PromptImageInput, VllmRunner from ...utils import check_embeddings_close HF_TEXT_PROMPTS = [ "a photo of a stop sign", "a photo of a cherry blossom", ] HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts( { "stop_sign": "", "cherry_blossom": "", } ) MODELS = [ "google/siglip-base-patch16-224", "google/siglip2-base-patch16-224", # Different image embedding dim than text_config.hidden_size "google/siglip2-giant-opt-patch16-384", ] def _run_test( hf_runner: type[HfRunner], vllm_runner: type[VllmRunner], input_texts: list[str], input_images: PromptImageInput, model: str, *, dtype: str, tokenization_kwargs: dict[str, Any] | None = None, attention_config: dict[str, Any] | None = None, ) -> None: if tokenization_kwargs is None: tokenization_kwargs = {} with vllm_runner( model, runner="pooling", dtype=dtype, enforce_eager=True, max_model_len=64, gpu_memory_utilization=0.7, attention_config=attention_config, ) as vllm_model: vllm_outputs = vllm_model.embed( input_texts, images=input_images, tokenization_kwargs=tokenization_kwargs ) with hf_runner(model, dtype=dtype, auto_cls=SiglipModel) as hf_model: all_inputs = hf_model.get_inputs( input_texts, images=input_images, tokenization_kwargs=tokenization_kwargs ) all_outputs = [] for inputs in all_inputs: inputs = hf_model.wrap_device(inputs) if "pixel_values" in inputs: pooled_output = hf_model.model.get_image_features( pixel_values=inputs.pixel_values, ).squeeze(0) else: pooled_output = hf_model.model.get_text_features( input_ids=inputs.input_ids, ).squeeze(0) all_outputs.append(pooled_output.tolist()) hf_outputs = all_outputs check_embeddings_close( embeddings_0_lst=hf_outputs, embeddings_1_lst=vllm_outputs, name_0="hf", name_1="vllm", ) @pytest.mark.parametrize("model", MODELS) @pytest.mark.parametrize("dtype", ["float"]) def test_models_text( hf_runner, vllm_runner, image_assets, siglip_attention_config, model: str, dtype: str, ) -> None: input_texts_images = [(text, None) for text in HF_TEXT_PROMPTS] input_texts = [text for text, _ in input_texts_images] input_images = [image for _, image in input_texts_images] _run_test( hf_runner, vllm_runner, input_texts, input_images, # type: ignore model, dtype=dtype, tokenization_kwargs={ "padding": "max_length", "max_length": 64, }, # siglip2 was trained with this padding setting. attention_config=siglip_attention_config, ) @pytest.mark.parametrize("model", MODELS) @pytest.mark.parametrize("dtype", ["float"]) def test_models_image( hf_runner, vllm_runner, image_assets, siglip_attention_config, model: str, dtype: str, ) -> None: input_texts_images = [ (text, asset.pil_image) for text, asset in zip(HF_IMAGE_PROMPTS, image_assets) ] input_texts = [text for text, _ in input_texts_images] input_images = [image for _, image in input_texts_images] _run_test( hf_runner, vllm_runner, input_texts, input_images, model, dtype=dtype, attention_config=siglip_attention_config, ) @pytest.mark.parametrize("model", MODELS) @pytest.mark.parametrize("dtype", ["float"]) def test_models_text_image_no_crash( vllm_runner, image_assets, siglip_attention_config, model: str, dtype: str, ) -> None: texts = [HF_TEXT_PROMPTS[0]] images = [image_assets[0].pil_image] with vllm_runner( model, runner="pooling", dtype=dtype, enforce_eager=True, max_model_len=64, gpu_memory_utilization=0.7, attention_config=siglip_attention_config, ) as vllm_model: with pytest.raises(ValueError, match="not both"): vllm_model.embed(texts, images=images) vllm_model.embed(texts) vllm_model.embed([""], images=images)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/models/multimodal/pooling/test_siglip.py", "license": "Apache License 2.0", "lines": 145, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/platform_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import multiprocessing from collections.abc import Sequence from concurrent.futures.process import ProcessPoolExecutor from functools import cache from typing import Any import torch def cuda_is_initialized() -> bool: """Check if CUDA is initialized.""" if not torch.cuda._is_compiled(): return False return torch.cuda.is_initialized() def xpu_is_initialized() -> bool: """Check if XPU is initialized.""" if not torch.xpu._is_compiled(): return False return torch.xpu.is_initialized() def cuda_get_device_properties( device, names: Sequence[str], init_cuda=False ) -> tuple[Any, ...]: """Get specified CUDA device property values without initializing CUDA in the current process.""" if init_cuda or cuda_is_initialized(): props = torch.cuda.get_device_properties(device) return tuple(getattr(props, name) for name in names) # Run in subprocess to avoid initializing CUDA as a side effect. mp_ctx = multiprocessing.get_context("fork") with ProcessPoolExecutor(max_workers=1, mp_context=mp_ctx) as executor: return executor.submit(cuda_get_device_properties, device, names, True).result() @cache def is_pin_memory_available() -> bool: from vllm.platforms import current_platform return current_platform.is_pin_memory_available() @cache def is_uva_available() -> bool: """Check if Unified Virtual Addressing (UVA) is available.""" # UVA requires pinned memory. # TODO: Add more requirements for UVA if needed. return is_pin_memory_available() @cache def num_compute_units(device_id: int = 0) -> int: """Get the number of compute units of the current device.""" from vllm.platforms import current_platform return current_platform.num_compute_units(device_id)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/platform_utils.py", "license": "Apache License 2.0", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/models/language/pooling/test_extract_hidden_states.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm import TokensPrompt @pytest.mark.parametrize( "model", ["Qwen/Qwen3-0.6B"], ) @torch.inference_mode def test_extract_hidden_states(hf_runner, vllm_runner, model: str): n_prompt_tokens = [55, 56, 57] token_prompts = [[1024 + i for i in range(n)] for n in n_prompt_tokens] with vllm_runner( model, max_model_len=128, enforce_eager=True, runner="pooling", enable_prefix_caching=True, ) as vllm_model: pooling_outputs = vllm_model.llm.encode( [TokensPrompt(prompt_token_ids=t) for t in token_prompts], pooling_task="token_embed", ) for n, output in zip(n_prompt_tokens, pooling_outputs): assert len(output.prompt_token_ids) == n assert len(output.outputs.data) == n assert output.num_cached_tokens == 0 # test enable_prefix_caching plus all pooling # we need to skip reading cache at this request by # request.skip_reading_prefix_cache pooling_outputs = vllm_model.llm.encode( [TokensPrompt(prompt_token_ids=t) for t in token_prompts], pooling_task="token_embed", ) for n, output in zip(n_prompt_tokens, pooling_outputs): assert len(output.prompt_token_ids) == n assert len(output.outputs.data) == n assert output.num_cached_tokens == 0 # skip_reading_prefix_cache can still write to cache # to accelerate following requests pooling_outputs = vllm_model.llm.encode( [TokensPrompt(prompt_token_ids=t) for t in token_prompts], pooling_task="embed", ) for n, output in zip(n_prompt_tokens, pooling_outputs): assert len(output.prompt_token_ids) == n assert output.num_cached_tokens > 0
{ "repo_id": "vllm-project/vllm", "file_path": "tests/models/language/pooling/test_extract_hidden_states.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/utils_/test_system_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import tempfile from pathlib import Path from vllm.utils.system_utils import unique_filepath def test_unique_filepath(): temp_dir = tempfile.mkdtemp() path_fn = lambda i: Path(temp_dir) / f"file_{i}.txt" paths = set() for i in range(10): path = unique_filepath(path_fn) path.write_text("test") paths.add(path) assert len(paths) == 10 assert len(list(Path(temp_dir).glob("*.txt"))) == 10
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_system_utils.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/system_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import contextlib import multiprocessing import os import signal import sys from collections.abc import Callable, Iterator from pathlib import Path from typing import TextIO import psutil import vllm.envs as envs from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.platforms.interface import in_wsl from vllm.ray.lazy_utils import is_in_ray_actor from .platform_utils import cuda_is_initialized, xpu_is_initialized logger = init_logger(__name__) CYAN = "\033[0;36m" RESET = "\033[0;0m" # Environment variable utilities def update_environment_variables(envs_dict: dict[str, str]): """Update multiple environment variables with logging.""" for k, v in envs_dict.items(): if k in os.environ and os.environ[k] != v: logger.warning( "Overwriting environment variable %s from '%s' to '%s'", k, os.environ[k], v, ) os.environ[k] = v @contextlib.contextmanager def set_env_var(key: str, value: str) -> Iterator[None]: """Temporarily set an environment variable.""" old = os.environ.get(key) os.environ[key] = value try: yield finally: if old is None: os.environ.pop(key, None) else: os.environ[key] = old @contextlib.contextmanager def suppress_stdout(): """ Suppress stdout from C libraries at the file descriptor level. Only suppresses stdout, not stderr, to preserve error messages. Suppression is disabled when VLLM_LOGGING_LEVEL is set to DEBUG. Example: with suppress_stdout(): # C library calls that would normally print to stdout torch.distributed.new_group(ranks, backend="gloo") """ # Don't suppress if logging level is DEBUG if envs.VLLM_LOGGING_LEVEL == "DEBUG": yield return stdout_fd = sys.stdout.fileno() stdout_dup = os.dup(stdout_fd) devnull_fd = os.open(os.devnull, os.O_WRONLY) try: sys.stdout.flush() os.dup2(devnull_fd, stdout_fd) yield finally: sys.stdout.flush() os.dup2(stdout_dup, stdout_fd) os.close(stdout_dup) os.close(devnull_fd) # File path utilities def unique_filepath(fn: Callable[[int], Path]) -> Path: """Generate a unique file path by trying incrementing integers. Note: This function has a TOCTOU race condition. Caller should use atomic operations (e.g., open with 'x' mode) when creating the file to ensure thread safety. """ i = 0 while True: p = fn(i) if not p.exists(): return p i += 1 # Process management utilities def _sync_visible_devices_env_vars(): """Sync HIP/CUDA visibility env vars before spawning (ROCm only).""" if not current_platform.is_rocm(): return from vllm.platforms.rocm import _sync_hip_cuda_env_vars _sync_hip_cuda_env_vars() def _maybe_force_spawn(): """Check if we need to force the use of the `spawn` multiprocessing start method. """ if os.environ.get("VLLM_WORKER_MULTIPROC_METHOD") == "spawn": return reasons = [] if is_in_ray_actor(): # even if we choose to spawn, we need to pass the ray address # to the subprocess so that it knows how to connect to the ray cluster. # env vars are inherited by subprocesses, even if we use spawn. import ray os.environ["RAY_ADDRESS"] = ray.get_runtime_context().gcs_address reasons.append("In a Ray actor and can only be spawned") if cuda_is_initialized(): reasons.append("CUDA is initialized") elif xpu_is_initialized(): reasons.append("XPU is initialized") if in_wsl(): reasons.append("WSL is detected and NVML is not compatible with fork") if reasons: logger.warning( "We must use the `spawn` multiprocessing start method. " "Overriding VLLM_WORKER_MULTIPROC_METHOD to 'spawn'. " "See https://docs.vllm.ai/en/latest/usage/" "troubleshooting.html#python-multiprocessing " "for more information. Reasons: %s", "; ".join(reasons), ) os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" def get_mp_context(): """Get a multiprocessing context with a particular method (spawn or fork). By default we follow the value of the VLLM_WORKER_MULTIPROC_METHOD to determine the multiprocessing method (default is fork). However, under certain conditions, we may enforce spawn and override the value of VLLM_WORKER_MULTIPROC_METHOD. """ _maybe_force_spawn() # (ROCm): Sync GPU visibility env vars so spawned children inherit # consistent values. Must run after _maybe_force_spawn and regardless # of whether spawn was already set. _sync_visible_devices_env_vars() mp_method = envs.VLLM_WORKER_MULTIPROC_METHOD return multiprocessing.get_context(mp_method) def set_process_title( name: str, suffix: str = "", prefix: str = envs.VLLM_PROCESS_NAME_PREFIX, ) -> None: """Set the current process title with optional suffix.""" try: import setproctitle except ImportError: return if suffix: name = f"{name}_{suffix}" setproctitle.setproctitle(f"{prefix}::{name}") def _add_prefix(file: TextIO, worker_name: str, pid: int) -> None: """Add colored prefix to file output for log decoration.""" is_tty = hasattr(file, "isatty") and file.isatty() if ( envs.NO_COLOR or envs.VLLM_LOGGING_COLOR == "0" or (envs.VLLM_LOGGING_COLOR != "1" and not is_tty) ): prefix = f"({worker_name} pid={pid}) " else: prefix = f"{CYAN}({worker_name} pid={pid}){RESET} " file_write = file.write def write_with_prefix(s: str): if not s: return if file.start_new_line: # type: ignore[attr-defined] file_write(prefix) idx = 0 while (next_idx := s.find("\n", idx)) != -1: next_idx += 1 file_write(s[idx:next_idx]) if next_idx == len(s): file.start_new_line = True # type: ignore[attr-defined] return file_write(prefix) idx = next_idx file_write(s[idx:]) file.start_new_line = False # type: ignore[attr-defined] file.start_new_line = True # type: ignore[attr-defined] file.write = write_with_prefix # type: ignore[method-assign] def decorate_logs(process_name: str | None = None) -> None: """Decorate stdout/stderr with process name and PID prefix.""" # Respect VLLM_CONFIGURE_LOGGING environment variable if not envs.VLLM_CONFIGURE_LOGGING: return if process_name is None: process_name = get_mp_context().current_process().name pid = os.getpid() _add_prefix(sys.stdout, process_name, pid) _add_prefix(sys.stderr, process_name, pid) def kill_process_tree(pid: int): """ Kills all descendant processes of the given pid by sending SIGKILL. Args: pid (int): Process ID of the parent process """ try: parent = psutil.Process(pid) except psutil.NoSuchProcess: return # Get all children recursively children = parent.children(recursive=True) # Send SIGKILL to all children first for child in children: with contextlib.suppress(ProcessLookupError): os.kill(child.pid, signal.SIGKILL) # Finally kill the parent with contextlib.suppress(ProcessLookupError): os.kill(pid, signal.SIGKILL) # Resource utilities # Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/srt/utils.py#L630 def set_ulimit(target_soft_limit: int = 65535): if sys.platform.startswith("win"): logger.info("Windows detected, skipping ulimit adjustment.") return import resource resource_type = resource.RLIMIT_NOFILE current_soft, current_hard = resource.getrlimit(resource_type) if current_soft < target_soft_limit: try: resource.setrlimit(resource_type, (target_soft_limit, current_hard)) except ValueError as e: logger.warning( "Found ulimit of %s and failed to automatically increase " "with error %s. This can cause fd limit errors like " "`OSError: [Errno 24] Too many open files`. Consider " "increasing with ulimit -n", current_soft, e, ) def find_loaded_library(lib_name: str) -> str | None: """ According to according to https://man7.org/linux/man-pages/man5/proc_pid_maps.5.html, the file `/proc/self/maps` contains the memory maps of the process, which includes the shared libraries loaded by the process. We can use this file to find the path of the loaded library. """ # noqa found_line = None with open("/proc/self/maps") as f: for line in f: if lib_name in line: found_line = line break if found_line is None: # the library is not loaded in the current process return None # if lib_name is libcudart, we need to match a line with: # address /path/to/libcudart-hash.so.11.0 start = found_line.index("/") path = found_line[start:].strip() filename = path.split("/")[-1] assert filename.rpartition(".so")[0].startswith(lib_name), ( f"Unexpected filename: {filename} for library {lib_name}" ) return path
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/system_utils.py", "license": "Apache License 2.0", "lines": 254, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/entrypoints/anthropic/protocol.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Pydantic models for Anthropic API protocol""" import time from typing import Any, Literal from pydantic import BaseModel, field_validator, model_validator class AnthropicError(BaseModel): """Error structure for Anthropic API""" type: str message: str class AnthropicErrorResponse(BaseModel): """Error response structure for Anthropic API""" type: Literal["error"] = "error" error: AnthropicError class AnthropicUsage(BaseModel): """Token usage information""" input_tokens: int output_tokens: int cache_creation_input_tokens: int | None = None cache_read_input_tokens: int | None = None class AnthropicContentBlock(BaseModel): """Content block in message""" type: Literal["text", "image", "tool_use", "tool_result", "thinking"] text: str | None = None # For image content source: dict[str, Any] | None = None # For tool use/result id: str | None = None tool_use_id: str | None = None name: str | None = None input: dict[str, Any] | None = None content: str | list[dict[str, Any]] | None = None is_error: bool | None = None # For thinking content thinking: str | None = None signature: str | None = None class AnthropicMessage(BaseModel): """Message structure""" role: Literal["user", "assistant"] content: str | list[AnthropicContentBlock] class AnthropicTool(BaseModel): """Tool definition""" name: str description: str | None = None input_schema: dict[str, Any] @field_validator("input_schema") @classmethod def validate_input_schema(cls, v): if not isinstance(v, dict): raise ValueError("input_schema must be a dictionary") if "type" not in v: v["type"] = "object" # Default to object type return v class AnthropicToolChoice(BaseModel): """Tool Choice definition""" type: Literal["auto", "any", "tool"] name: str | None = None @model_validator(mode="after") def validate_name_required_for_tool(self) -> "AnthropicToolChoice": if self.type == "tool" and not self.name: raise ValueError("tool_choice.name is required when type is 'tool'") return self class AnthropicMessagesRequest(BaseModel): """Anthropic Messages API request""" model: str messages: list[AnthropicMessage] max_tokens: int metadata: dict[str, Any] | None = None stop_sequences: list[str] | None = None stream: bool | None = False system: str | list[AnthropicContentBlock] | None = None temperature: float | None = None tool_choice: AnthropicToolChoice | None = None tools: list[AnthropicTool] | None = None top_k: int | None = None top_p: float | None = None @field_validator("model") @classmethod def validate_model(cls, v): if not v: raise ValueError("Model is required") return v @field_validator("max_tokens") @classmethod def validate_max_tokens(cls, v): if v <= 0: raise ValueError("max_tokens must be positive") return v class AnthropicDelta(BaseModel): """Delta for streaming responses""" type: ( Literal["text_delta", "input_json_delta", "thinking_delta", "signature_delta"] | None ) = None text: str | None = None thinking: str | None = None partial_json: str | None = None signature: str | None = None # Message delta stop_reason: ( Literal["end_turn", "max_tokens", "stop_sequence", "tool_use"] | None ) = None stop_sequence: str | None = None class AnthropicStreamEvent(BaseModel): """Streaming event""" type: Literal[ "message_start", "message_delta", "message_stop", "content_block_start", "content_block_delta", "content_block_stop", "ping", "error", ] message: "AnthropicMessagesResponse | None" = None delta: AnthropicDelta | None = None content_block: AnthropicContentBlock | None = None index: int | None = None error: AnthropicError | None = None usage: AnthropicUsage | None = None class AnthropicMessagesResponse(BaseModel): """Anthropic Messages API response""" id: str type: Literal["message"] = "message" role: Literal["assistant"] = "assistant" content: list[AnthropicContentBlock] model: str stop_reason: ( Literal["end_turn", "max_tokens", "stop_sequence", "tool_use"] | None ) = None stop_sequence: str | None = None usage: AnthropicUsage | None = None def model_post_init(self, __context): if not self.id: self.id = f"msg_{int(time.time() * 1000)}" class AnthropicContextManagement(BaseModel): """Context management information for token counting.""" original_input_tokens: int class AnthropicCountTokensRequest(BaseModel): """Anthropic messages.count_tokens request""" model: str messages: list[AnthropicMessage] system: str | list[AnthropicContentBlock] | None = None tool_choice: AnthropicToolChoice | None = None tools: list[AnthropicTool] | None = None @field_validator("model") @classmethod def validate_model(cls, v): if not v: raise ValueError("Model is required") return v class AnthropicCountTokensResponse(BaseModel): """Anthropic messages.count_tokens response""" input_tokens: int context_management: AnthropicContextManagement | None = None
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/entrypoints/anthropic/protocol.py", "license": "Apache License 2.0", "lines": 156, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/deepencoder.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # adapted from # https://github.com/deepseek-ai/DeepSeek-OCR/blob/main/DeepSeek-OCR-master/DeepSeek-OCR-vllm/deepencoder/sam_vary_sdpa.py # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math from collections.abc import Iterable from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from transformers import CLIPVisionConfig from vllm.model_executor.layers.attention import MMEncoderAttention from vllm.model_executor.layers.conv import Conv2dLayer from vllm.model_executor.layers.quantization import QuantizationConfig from vllm.model_executor.model_loader.weight_utils import default_weight_loader from .clip import CLIPEncoder, CLIPVisionEmbeddings class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = act() def forward(self, x: torch.Tensor) -> torch.Tensor: return self.lin2(self.act(self.lin1(x))) # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa class LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps def forward(self, x: torch.Tensor) -> torch.Tensor: u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa class ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: bool = True, norm_layer: type[nn.Module] = nn.LayerNorm, act_layer: type[nn.Module] = nn.GELU, use_abs_pos: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, window_size: int = 0, global_attn_indexes: tuple[int, ...] = (), last_conv_output: int = 1024, ) -> None: """ Args: img_size (int): Input image size. patch_size (int): Patch size. in_chans (int): Number of input image channels. embed_dim (int): Patch embedding dimension. depth (int): Depth of ViT. num_heads (int): Number of attention heads in each ViT block. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool): If True, add a learnable bias to query, key, value. norm_layer (nn.Module): Normalization layer. act_layer (nn.Module): Activation layer. use_abs_pos (bool): If True, use absolute positional embeddings. use_rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. window_size (int): Window size for window attention blocks. global_attn_indexes (list): Indexes for blocks using global attention. """ # noqa: E501 super().__init__() self.img_size = img_size self.patch_embed = PatchEmbed( kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), in_chans=in_chans, embed_dim=embed_dim, ) self.pos_embed: nn.Parameter | None = None if use_abs_pos: # Initialize absolute positional embedding with pretrain image size. self.pos_embed = nn.Parameter( torch.zeros( 1, img_size // patch_size, img_size // patch_size, embed_dim ) ) self.blocks = nn.ModuleList() for i in range(depth): block = Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, norm_layer=norm_layer, act_layer=act_layer, use_rel_pos=use_rel_pos, rel_pos_zero_init=rel_pos_zero_init, window_size=window_size if i not in global_attn_indexes else 0, input_size=(img_size // patch_size, img_size // patch_size), ) self.blocks.append(block) self.neck = nn.Sequential( Conv2dLayer( embed_dim, out_chans, kernel_size=1, bias=False, ), LayerNorm2d(out_chans), Conv2dLayer( out_chans, out_chans, kernel_size=3, padding=1, bias=False, ), LayerNorm2d(out_chans), ) self.net_2 = Conv2dLayer( 256, 512, kernel_size=3, stride=2, padding=1, bias=False ) self.net_3 = Conv2dLayer( 512, last_conv_output, kernel_size=3, stride=2, padding=1, bias=False ) def get_abs_pos(self, abs_pos: torch.Tensor, tgt_size: int): dtype = abs_pos.dtype src_size = abs_pos.size(1) if src_size != tgt_size: old_pos_embed = abs_pos.permute(0, 3, 1, 2) old_pos_embed = old_pos_embed.to(torch.float32) new_pos_embed = F.interpolate( old_pos_embed, size=(tgt_size, tgt_size), mode="bicubic", antialias=True, align_corners=False, ).to(dtype) new_pos_embed = new_pos_embed.permute(0, 2, 3, 1) return new_pos_embed else: return abs_pos def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.patch_embed(x) if self.pos_embed is not None: x = x + self.get_abs_pos(self.pos_embed, x.size(1)) for blk in self.blocks: x = blk(x) neck_output = self.neck(x.permute(0, 3, 1, 2)) conv2_output = self.net_2(neck_output) conv3_output = self.net_3(conv2_output) return conv3_output class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: type[nn.Module] = nn.LayerNorm, act_layer: type[nn.Module] = nn.GELU, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, window_size: int = 0, input_size: tuple[int, int] | None = None, ) -> None: """ Args: dim (int): Number of input channels. num_heads (int): Number of attention heads in each ViT block. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool): If True, add a learnable bias to query, key, value. norm_layer (nn.Module): Normalization layer. act_layer (nn.Module): Activation layer. use_rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. window_size (int): Window size for window attention blocks. If it equals 0, then use global attention. input_size (tuple(int, int) or None): Input resolution for calculating the relative positional parameter size. """ # noqa: E501 super().__init__() self.norm1 = norm_layer(dim) self.attn = RelPosAttention( dim, num_heads=num_heads, qkv_bias=qkv_bias, use_rel_pos=use_rel_pos, rel_pos_zero_init=rel_pos_zero_init, input_size=input_size if window_size == 0 else (window_size, window_size), ) self.norm2 = norm_layer(dim) self.mlp = MLPBlock( embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer ) self.window_size = window_size def forward(self, x: torch.Tensor) -> torch.Tensor: shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size) x = self.attn(x) # Reverse window partition if self.window_size > 0: x = window_unpartition(x, self.window_size, pad_hw, (H, W)) x = shortcut + x x = x + self.mlp(self.norm2(x)) return x class RelPosAttention(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: tuple[int, int] | None = None, ) -> None: """ Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. qkv_bias (bool): If True, add a learnable bias to query, key, value. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. input_size (tuple(int, int) or None): Input resolution for calculating the relative positional parameter size. """ # noqa: E501 super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim**-0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim) self.use_rel_pos = use_rel_pos if self.use_rel_pos: assert input_size is not None, ( "Input size must be provided if using relative positional encoding." ) # initialize relative positional embeddings self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) def forward(self, x: torch.Tensor) -> torch.Tensor: B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = ( self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) ) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) rel_h, rel_w = None, None if self.use_rel_pos: rel_h, rel_w = add_decomposed_rel_pos( q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W) ) q = q.view(B, self.num_heads, H * W, -1) k = k.view(B, self.num_heads, H * W, -1) v = v.view(B, self.num_heads, H * W, -1) if self.use_rel_pos: rel_h = rel_h.view( B, self.num_heads, rel_h.size(1), rel_h.size(2), rel_h.size(3) ) rel_w = rel_w.view( B, self.num_heads, rel_w.size(1), rel_w.size(2), rel_w.size(3) ) attn_bias = (rel_h + rel_w).view( B, self.num_heads, rel_h.size(2), rel_h.size(3) * rel_w.size(4) ) x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=attn_bias ) else: x = torch.nn.functional.scaled_dot_product_attention(q, k, v) x = ( x.view(B, self.num_heads, H, W, -1) .permute(0, 2, 3, 1, 4) .reshape(B, H, W, -1) ) x = self.proj(x) return x def window_partition( x: torch.Tensor, window_size: int ) -> tuple[torch.Tensor, tuple[int, int]]: """ Partition into non-overlapping windows with padding if needed. Args: x (tensor): input tokens with [B, H, W, C]. window_size (int): window size. Returns: windows: windows after partition with [B * num_windows, window_size, window_size, C]. (Hp, Wp): padded height and width before partition """ # noqa: E501 B, H, W, C = x.shape pad_h = (window_size - H % window_size) % window_size pad_w = (window_size - W % window_size) % window_size if pad_h > 0 or pad_w > 0: x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) Hp, Wp = H + pad_h, W + pad_w x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) windows = ( x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) ) return windows, (Hp, Wp) def window_unpartition( windows: torch.Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int], ) -> torch.Tensor: """ Window unpartition into original sequences and removing padding. Args: windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. window_size (int): window size. pad_hw (Tuple): padded height and width (Hp, Wp). hw (Tuple): original height and width (H, W) before padding. Returns: x: unpartitioned sequences with [B, H, W, C]. """ # noqa: E501 Hp, Wp = pad_hw H, W = hw B = windows.shape[0] // (Hp * Wp // window_size // window_size) x = windows.view( B, Hp // window_size, Wp // window_size, window_size, window_size, -1 ) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) if Hp > H or Wp > W: x = x[:, :H, :W, :].contiguous() return x def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: """ Get relative positional embeddings according to the relative positions of query and key sizes. Args: q_size (int): size of query q. k_size (int): size of key k. rel_pos (Tensor): relative position embeddings (L, C). Returns: Extracted positional embeddings according to relative positions. """ max_rel_dist = int(2 * max(q_size, k_size) - 1) # Interpolate rel pos if needed. if rel_pos.shape[0] != max_rel_dist: # Interpolate rel pos. dtype = rel_pos.dtype rel_pos = rel_pos.to(torch.float32) rel_pos_resized = F.interpolate( rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode="linear", ).to(dtype) rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) else: rel_pos_resized = rel_pos # Scale the coords with short length if shapes for q and k are different. q_coords = torch.arange(q_size, device=rel_pos.device)[:, None] * max( k_size / q_size, 1.0 ) k_coords = torch.arange(k_size, device=rel_pos.device)[None, :] * max( q_size / k_size, 1.0 ) relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) return rel_pos_resized[relative_coords.long()] def add_decomposed_rel_pos( q: torch.Tensor, rel_pos_h: torch.Tensor, rel_pos_w: torch.Tensor, q_size: tuple[int, int], k_size: tuple[int, int], ) -> torch.Tensor: """ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py Args: q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. q_size (Tuple): spatial sequence size of query q with (q_h, q_w). k_size (Tuple): spatial sequence size of key k with (k_h, k_w). Returns: attn (Tensor): attention map with added relative positional embeddings. """ # noqa: E501 q_h, q_w = q_size k_h, k_w = k_size Rh = get_rel_pos(q_h, k_h, rel_pos_h) Rw = get_rel_pos(q_w, k_w, rel_pos_w) B, _, dim = q.shape r_q = q.reshape(B, q_h, q_w, dim) rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) rel_h = rel_h.unsqueeze(-1) rel_w = rel_w.unsqueeze(-2) rel_h = rel_h.reshape(B, q_h * q_w, k_h, 1) rel_w = rel_w.reshape(B, q_h * q_w, 1, k_w) return rel_h, rel_w class PatchEmbed(nn.Module): """ Image to Patch Embedding. """ def __init__( self, kernel_size: tuple[int, int] = (16, 16), stride: tuple[int, int] = (16, 16), padding: tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: """ Args: kernel_size (Tuple): kernel size of the projection layer. stride (Tuple): stride of the projection layer. padding (Tuple): padding size of the projection layer. in_chans (int): Number of input image channels. embed_dim (int): Patch embedding dimension. """ super().__init__() self.proj = Conv2dLayer( in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.proj(x) # B C H W -> B H W C x = x.permute(0, 2, 3, 1) return x # TODO(Isotr0py): use vision_config to build sam model def build_sam_vit_b(): return _build_sam( encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=[2, 5, 8, 11], ) def _build_sam( encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, ): prompt_embed_dim = 256 image_size = 1024 vit_patch_size = 16 image_encoder = ImageEncoderViT( depth=encoder_depth, embed_dim=encoder_embed_dim, img_size=image_size, mlp_ratio=4, norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), num_heads=encoder_num_heads, patch_size=vit_patch_size, qkv_bias=True, use_rel_pos=True, global_attn_indexes=encoder_global_attn_indexes, window_size=14, out_chans=prompt_embed_dim, ) return image_encoder class DeepCLIPVisionEmbeddings(CLIPVisionEmbeddings): def get_abs_pos(self, abs_pos: torch.Tensor, tgt_size: int): # abs_pos: L, C # tgt_size: M # return: M, C dim = abs_pos.size(-1) abs_pos_new = abs_pos.squeeze(0) cls_token, old_pos_embed = abs_pos_new[:1], abs_pos_new[1:] src_size = int(math.sqrt(abs_pos_new.shape[0] - 1)) tgt_size = int(math.sqrt(tgt_size)) dtype = abs_pos.dtype if src_size != tgt_size: old_pos_embed = ( old_pos_embed.view(1, src_size, src_size, dim) .permute(0, 3, 1, 2) .contiguous() ) old_pos_embed = old_pos_embed.to(torch.float32) new_pos_embed = F.interpolate( old_pos_embed, size=(tgt_size, tgt_size), mode="bicubic", antialias=True, align_corners=False, ).to(dtype) new_pos_embed = new_pos_embed.permute(0, 2, 3, 1) new_pos_embed = new_pos_embed.view(tgt_size * tgt_size, dim) vision_pos_embed = torch.cat([cls_token, new_pos_embed], dim=0) vision_pos_embed = vision_pos_embed.view(1, tgt_size * tgt_size + 1, dim) return vision_pos_embed else: return abs_pos def forward( self, pixel_values: torch.Tensor, patch_embeds: torch.Tensor | None = None ) -> torch.Tensor: batch_size = pixel_values.shape[0] if patch_embeds is not None: patch_embeds = patch_embeds else: patch_embeds = self.patch_embedding(pixel_values) patch_embeds = patch_embeds.flatten(2).transpose(1, 2) class_embeds = self.class_embedding.expand(batch_size, 1, -1) embeddings = torch.cat([class_embeds, patch_embeds], dim=1) embeddings = embeddings + self.get_abs_pos( self.position_embedding(self.position_ids), embeddings.size(1) ) return embeddings class DeepCLIPVisionTransformer(nn.Module): def __init__( self, config: CLIPVisionConfig, quant_config: QuantizationConfig | None = None, *, num_hidden_layers_override: int | None = None, prefix: str = "", ) -> None: super().__init__() self.config = config embed_dim = config.hidden_size self.embeddings = DeepCLIPVisionEmbeddings(config) # NOTE: This typo of "layrnorm" is not fixed on purpose to match # the original transformers code and name of the model weights. self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) self.transformer = CLIPEncoder( config=config, quant_config=quant_config, num_hidden_layers_override=num_hidden_layers_override, prefix=f"{prefix}.encoder", attn_cls=MMEncoderAttention, ) num_hidden_layers = config.num_hidden_layers if len(self.transformer.layers) > config.num_hidden_layers: raise ValueError( f"The original encoder only has {num_hidden_layers} " f"layers, but you requested {len(self.transformer.layers)} layers." ) @property def dtype(self): return next(self.parameters()).dtype @property def device(self): return next(self.parameters()).device def forward( self, pixel_values: torch.Tensor, patch_embeds: torch.Tensor | None = None, *, select_layers: list[int] | None = None, ) -> torch.Tensor: hidden_states = self.embeddings(pixel_values, patch_embeds) hidden_states = self.pre_layrnorm(hidden_states) # Produces either the last layer output or all of the hidden states, # depending on if we have select_layers or not encoder_outputs = self.transformer( inputs_embeds=hidden_states, return_all_hidden_states=select_layers is not None, ) return encoder_outputs def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: params_dict = dict(self.named_parameters()) loaded_params: set[str] = set() for name, loaded_weight in weights: param = params_dict[name] weight_loader = getattr(param, "weight_loader", default_weight_loader) weight_loader(param, loaded_weight) loaded_params.add(name) return loaded_params
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/deepencoder.py", "license": "Apache License 2.0", "lines": 583, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/deepseek_ocr.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Inference-only Deepseek-OCR model compatible with HuggingFace weights.""" import math from collections.abc import Iterable, Mapping, Sequence from typing import Annotated, Literal import torch import torch.nn as nn from transformers import BatchFeature, CLIPVisionConfig from vllm.config import VllmConfig from vllm.config.multimodal import BaseDummyOptions from vllm.model_executor.models.interfaces import ( MultiModalEmbeddings, SupportsLoRA, SupportsMultiModal, SupportsPP, ) from vllm.model_executor.models.module_mapping import MultiModelKeys from vllm.model_executor.models.utils import ( AutoWeightsLoader, WeightsMapper, init_vllm_registered_model, maybe_prefix, ) from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.inputs import ( MultiModalDataDict, MultiModalFieldConfig, MultiModalKwargsItems, NestedTensors, ) from vllm.multimodal.parse import ( ImageEmbeddingItems, ImageProcessorItems, ImageSize, MultiModalDataItems, ) from vllm.multimodal.processing import ( BaseDummyInputsBuilder, BaseMultiModalProcessor, BaseProcessingInfo, PromptReplacement, PromptUpdate, ) from vllm.sampling_params import SamplingParams from vllm.sequence import IntermediateTensors from vllm.tokenizers import cached_tokenizer_from_config from vllm.transformers_utils.configs.deepseek_vl2 import DeepseekVLV2Config from vllm.transformers_utils.processors.deepseek_ocr import ( BASE_SIZE, CROP_MODE, DeepseekOCRProcessor, count_tiles, ) from vllm.utils.tensor_schema import TensorSchema, TensorShape from vllm.v1.sample.logits_processor import ( AdapterLogitsProcessor, RequestLogitsProcessor, ) from .deepencoder import DeepCLIPVisionTransformer, build_sam_vit_b from .deepseek_vl2 import MlpProjector # The image token id may be various IMAGE_SIZE = 640 _IMAGE_TOKEN = "<image>" class DeepseekOCRImagePixelInputs(TensorSchema): """ Dimensions: - b: Batch size - n: Number of images - p: Number of patches - base_size: Base size of the processor - image_size: Image size of the processor """ type: Literal["pixel_values"] data: Annotated[ torch.Tensor, TensorShape("bn", 3, "base_size", "base_size", dynamic_dims={"bnp"}), ] images_crop: Annotated[ torch.Tensor, TensorShape("bnp", 3, "image_size", "image_size", dynamic_dims={"bnp"}), ] images_spatial_crop: Annotated[torch.Tensor, TensorShape("bn", 2)] class NoRepeatNGramLogitsProcessor: def __init__( self, ngram_size: int, window_size: int, whitelist_token_ids: set[int] | None = None, ): self.ngram_size = ngram_size self.window_size = window_size self.whitelist_token_ids = whitelist_token_ids or set() def __call__( self, output_ids: list[int], logits: torch.Tensor, ) -> torch.Tensor: if len(output_ids) < self.ngram_size: return logits current_prefix = tuple(output_ids[-(self.ngram_size - 1) :]) search_start = max(0, len(output_ids) - self.window_size) search_end = len(output_ids) - self.ngram_size + 1 banned_tokens = set() for i in range(search_start, search_end): ngram = tuple(output_ids[i : i + self.ngram_size]) if ngram[:-1] == current_prefix: banned_tokens.add(ngram[-1]) banned_tokens = banned_tokens - self.whitelist_token_ids if banned_tokens: logits[list(banned_tokens)] = -float("inf") return logits class NGramPerReqLogitsProcessor(AdapterLogitsProcessor): """Example of overriding the wrapper class `__init__()` in order to utilize info about the device type""" @classmethod def validate_params(cls, params: SamplingParams): ngram_size = params.extra_args and params.extra_args.get("ngram_size") window_size = params.extra_args and params.extra_args.get("window_size", 100) whitelist_token_ids = params.extra_args and params.extra_args.get( "whitelist_token_ids", None ) # if ngram_size is not provided, skip validation because the processor # will not be used. if ngram_size is None: return None if not isinstance(ngram_size, int) or ngram_size <= 0: raise ValueError( f"`ngram_size` has to be a strictly positive integer, got {ngram_size}." ) if not isinstance(window_size, int) or window_size <= 0: raise ValueError( "`window_size` has to be a strictly positive integer, " f"got {window_size}." ) if whitelist_token_ids is not None and not isinstance( whitelist_token_ids, Iterable ): raise ValueError( "`whitelist_token_ids` has to be a sequence of integers, " f"got {whitelist_token_ids}." ) def is_argmax_invariant(self) -> bool: return False def new_req_logits_processor( self, params: SamplingParams, ) -> RequestLogitsProcessor | None: ngram_size = params.extra_args and params.extra_args.get("ngram_size") window_size = params.extra_args and params.extra_args.get("window_size", 100) whitelist_token_ids = params.extra_args and params.extra_args.get( "whitelist_token_ids", None ) if ngram_size is None: return None whitelist_token_ids = set(whitelist_token_ids) if whitelist_token_ids else None return NoRepeatNGramLogitsProcessor( ngram_size=ngram_size, window_size=window_size, whitelist_token_ids=whitelist_token_ids, ) class DeepseekOCRProcessingInfo(BaseProcessingInfo): def get_hf_config(self): return self.ctx.get_hf_config(DeepseekVLV2Config) def get_hf_processor(self, **kwargs: object): v1_processor_config = dict( image_size=IMAGE_SIZE, base_size=BASE_SIZE, crop_mode=CROP_MODE, strategy="v1", ) return self.ctx.get_hf_processor( DeepseekOCRProcessor, **{**kwargs, **v1_processor_config} ) def get_supported_mm_limits(self) -> Mapping[str, int | None]: return {"image": None} def get_num_image_tokens( self, *, image_width: int, image_height: int, cropping: bool = True ) -> int: image_size = IMAGE_SIZE base_size = BASE_SIZE patch_size = 16 downsample_ratio = 4 if CROP_MODE: if image_width <= 640 and image_height <= 640: crop_ratio = [1, 1] else: # find the closest aspect ratio to the target crop_ratio = count_tiles( image_width, image_height, image_size=IMAGE_SIZE ) num_width_tiles, num_height_tiles = crop_ratio else: num_width_tiles = num_height_tiles = 1 h = w = math.ceil((base_size // patch_size) / downsample_ratio) h2 = w2 = math.ceil((image_size // patch_size) / downsample_ratio) global_views_tokens = h * (w + 1) if num_width_tiles > 1 or num_height_tiles > 1: local_views_tokens = (num_height_tiles * h2) * (num_width_tiles * w2 + 1) else: local_views_tokens = 0 return global_views_tokens + local_views_tokens + 1 def get_image_size_with_most_features(self) -> ImageSize: if IMAGE_SIZE == 1024 and BASE_SIZE == 1280: return ImageSize(width=1024 * 2, height=1024 * 2) return ImageSize(width=640 * 2, height=640 * 2) class DeepseekOCRDummyInputsBuilder(BaseDummyInputsBuilder[DeepseekOCRProcessingInfo]): def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str: num_images = mm_counts.get("image", 0) processor = self.info.get_hf_processor() image_token = processor.image_token return image_token * num_images def get_dummy_mm_data( self, seq_len: int, mm_counts: Mapping[str, int], mm_options: Mapping[str, BaseDummyOptions], ) -> MultiModalDataDict: num_images = mm_counts.get("image", 0) max_image_size = self.info.get_image_size_with_most_features() return { "image": self._get_dummy_images( width=max_image_size.width, height=max_image_size.height, num_images=num_images, ) } class DeepseekOCRMultiModalProcessor( BaseMultiModalProcessor[DeepseekOCRProcessingInfo] ): def _call_hf_processor( self, prompt: str, mm_data: Mapping[str, object], mm_kwargs: Mapping[str, object], tok_kwargs: Mapping[str, object], ) -> BatchFeature: if mm_data: processed_outputs = self.info.ctx.call_hf_processor( self.info.get_hf_processor(**mm_kwargs), dict(prompt=prompt, **mm_data), mm_kwargs, ) else: tokenizer = self.info.get_tokenizer() processed_outputs = tokenizer( prompt, add_special_tokens=True, return_tensors="pt" ) return processed_outputs def _get_mm_fields_config( self, hf_inputs: BatchFeature, hf_processor_mm_kwargs: Mapping[str, object], ) -> Mapping[str, MultiModalFieldConfig]: images_spatial_crop = hf_inputs.get("images_spatial_crop", torch.empty((0, 2))) is_tiled = (images_spatial_crop[:, 0] > 1) | (images_spatial_crop[:, 1] > 1) patches_per_image = torch.where(is_tiled, images_spatial_crop.prod(dim=-1), 0) return dict( pixel_values=MultiModalFieldConfig.batched("image"), images_spatial_crop=MultiModalFieldConfig.batched("image"), images_crop=MultiModalFieldConfig.flat_from_sizes( "image", patches_per_image ), ) def _get_prompt_updates( self, mm_items: MultiModalDataItems, hf_processor_mm_kwargs: Mapping[str, object], out_mm_kwargs: MultiModalKwargsItems, ) -> Sequence[PromptUpdate]: hf_processor = self.info.get_hf_processor(**hf_processor_mm_kwargs) image_token_id = hf_processor.image_token_id assert isinstance(image_token_id, int) def get_replacement_deepseek_vl2(item_idx: int): images = mm_items.get_items( "image", (ImageEmbeddingItems, ImageProcessorItems) ) if isinstance(images, ImageEmbeddingItems): num_image_tokens = images.get_feature_size(item_idx) else: size = images.get_image_size(item_idx) num_image_tokens = self.info.get_num_image_tokens( image_width=size.width, image_height=size.height, cropping=CROP_MODE, ) return [image_token_id] * num_image_tokens return [ PromptReplacement( modality="image", target=[image_token_id], replacement=get_replacement_deepseek_vl2, ) ] @MULTIMODAL_REGISTRY.register_processor( DeepseekOCRMultiModalProcessor, info=DeepseekOCRProcessingInfo, dummy_inputs=DeepseekOCRDummyInputsBuilder, ) class DeepseekOCRForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsLoRA): hf_to_vllm_mapper = WeightsMapper( orig_to_new_prefix={ # map prefix for language backbone "model.embed_tokens.": "language_model.model.embed_tokens.", "model.layers.": "language_model.model.layers.", "model.norm.": "language_model.model.norm.", "lm_head.": "language_model.lm_head.", # remove "model." prefix for other components "model.": "", } ) @classmethod def get_placeholder_str(cls, modality: str, i: int) -> str | None: if modality.startswith("image"): return "<image>" raise ValueError("Only image modality is supported") def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() config: DeepseekVLV2Config = vllm_config.model_config.hf_config quant_config = vllm_config.quant_config multimodal_config = vllm_config.model_config.multimodal_config self.config = config self.multimodal_config = multimodal_config self.vision_config = config.vision_config self.projector_config = config.projector_config self.text_config = config.text_config model_config = vllm_config.model_config tokenizer = cached_tokenizer_from_config(model_config) self.image_token_id = tokenizer.vocab[_IMAGE_TOKEN] with self._mark_tower_model(vllm_config, "image"): self.sam_model = build_sam_vit_b() clip_vision_config = CLIPVisionConfig( hidden_size=1024, intermediate_size=4096, num_attention_heads=16, num_hidden_layers=24, image_size=224, patch_size=14, projection_dim=512, layer_norm_eps=1e-5, ) self.vision_model = DeepCLIPVisionTransformer( config=clip_vision_config, quant_config=quant_config, prefix=maybe_prefix(prefix, "vision_model"), ) self.projector = MlpProjector(self.projector_config) self.tile_tag = config.tile_tag self.global_view_pos = config.global_view_pos # special token for image token sequence format n_embed = self.projector_config.n_embed embed_std = 1 / torch.sqrt(torch.tensor(n_embed, dtype=torch.float32)) if self.tile_tag == "2D": # <|view_separator|>, <|\n|> self.image_newline = nn.Parameter(torch.randn(n_embed) * embed_std) # This is a typo in original implementation self.view_seperator = nn.Parameter(torch.randn(n_embed) * embed_std) else: raise ValueError( f"Only 2D tile_tag is supported currently, got: {self.tile_tag}" ) with self._mark_language_model(vllm_config): self.language_model = init_vllm_registered_model( vllm_config=vllm_config, hf_config=self.text_config, prefix=maybe_prefix(prefix, "language_model"), ) self.make_empty_intermediate_tensors = ( self.language_model.make_empty_intermediate_tensors ) def _parse_and_validate_image_input( self, **kwargs: object ) -> DeepseekOCRImagePixelInputs | None: pixel_values = kwargs.pop("pixel_values", None) images_spatial_crop = kwargs.pop("images_spatial_crop", None) images_crop = kwargs.pop("images_crop", None) if pixel_values is None or torch.sum(pixel_values).item() == 0: return None # Use actual tensor spatial dim instead of hardcoded # vision_config.image_size (1024). The vision encoders (SAM & CLIP) # support arbitrary resolutions via pos-encoding interpolation, # so Tiny/Small/Base/Large variants all work with the same weights. base_size = pixel_values.shape[-1] if images_crop is not None and images_crop.numel() > 0: image_size = images_crop.shape[-1] else: image_size = base_size return DeepseekOCRImagePixelInputs( type="pixel_values", data=pixel_values, images_crop=images_crop, images_spatial_crop=images_spatial_crop, resolve_bindings={ "base_size": base_size, "image_size": image_size, }, ) def _encode_global_features(self, image_tensor: torch.Tensor) -> torch.Tensor: global_features_1 = self.sam_model(image_tensor) global_features_2 = self.vision_model(image_tensor, global_features_1) features = torch.cat( ( global_features_2[:, 1:], global_features_1.flatten(2).permute(0, 2, 1), ), dim=-1, ) features = self.projector(features) _, hw, dim = features.shape side = int(hw**0.5) features = features.view(side, side, dim) newline = self.image_newline[None, None, :].expand(side, 1, dim) features = torch.cat([features, newline], dim=1) return features.view(-1, dim) def _encode_local_features( self, patches: torch.Tensor, crop_shape: torch.Tensor ) -> torch.Tensor | None: if torch.sum(patches).item() == 0: return None local_features_1 = self.sam_model(patches) local_features_2 = self.vision_model(patches, local_features_1) features = torch.cat( ( local_features_2[:, 1:], local_features_1.flatten(2).permute(0, 2, 1), ), dim=-1, ) features = self.projector(features) _, hw, dim = features.shape patch_side = int(hw**0.5) width_tiles = int(crop_shape[0].item()) height_tiles = int(crop_shape[1].item()) features = ( features.view(height_tiles, width_tiles, patch_side, patch_side, dim) .permute(0, 2, 1, 3, 4) .reshape(height_tiles * patch_side, width_tiles * patch_side, dim) ) newline = self.image_newline[None, None, :].expand( height_tiles * patch_side, 1, dim ) features = torch.cat([features, newline], dim=1) return features.view(-1, dim) def _pixel_values_to_embedding( self, pixel_values: torch.Tensor, images_crop: torch.Tensor, images_spatial_crop: torch.Tensor, ) -> NestedTensors: images_in_this_batch = [] is_tiled = (images_spatial_crop[:, 0] > 1) | (images_spatial_crop[:, 1] > 1) patches_per_image = torch.where(is_tiled, images_spatial_crop.prod(dim=-1), 0) images_crop = images_crop.split(patches_per_image.tolist()) for jdx in range(images_spatial_crop.size(0)): patches = images_crop[jdx] image_ori = pixel_values[[jdx]] crop_shape = images_spatial_crop[jdx] global_features = self._encode_global_features(image_ori) local_features = self._encode_local_features(patches, crop_shape) if local_features is not None: combined = torch.cat( [local_features, global_features, self.view_seperator[None, :]], dim=0, ) else: combined = torch.cat( [global_features, self.view_seperator[None, :]], dim=0 ) images_in_this_batch.append(combined) return images_in_this_batch def _process_image_input( self, image_input: DeepseekOCRImagePixelInputs ) -> torch.Tensor: pixel_values = image_input.data images_crop = image_input.images_crop images_spatial_crop = image_input.images_spatial_crop.to(dtype=torch.long) vision_features = self._pixel_values_to_embedding( pixel_values=pixel_values, images_crop=images_crop, images_spatial_crop=images_spatial_crop, ) return vision_features def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings | None: image_input = self._parse_and_validate_image_input(**kwargs) if image_input is None: return None vision_embeddings = self._process_image_input(image_input) return vision_embeddings def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, **kwargs: object, ): if intermediate_tensors is not None: inputs_embeds = None hidden_states = self.language_model( input_ids, positions, intermediate_tensors, inputs_embeds=inputs_embeds ) return hidden_states def compute_logits( self, hidden_states: torch.Tensor, ) -> torch.Tensor | None: return self.language_model.compute_logits(hidden_states) def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: loader = AutoWeightsLoader(self) autoloaded_weights = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) return autoloaded_weights def get_mm_mapping(self) -> MultiModelKeys: """ Get the module prefix in multimodal models """ return MultiModelKeys.from_string_field( language_model="language_model", connector="projector", tower_model=["sam_model", "vision_model"], )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/deepseek_ocr.py", "license": "Apache License 2.0", "lines": 520, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/transformers_utils/processors/deepseek_ocr.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # adapted from https://github.com/deepseek-ai/DeepSeek-OCR/blob/main/DeepSeek-OCR-master/DeepSeek-OCR-vllm/process/image_process.py # and https://github.com/deepseek-ai/DeepSeek-OCR-2/blob/main/DeepSeek-OCR2-master/DeepSeek-OCR2-vllm/process/image_process.py import math from typing import Literal import torch import torchvision.transforms as T from PIL import Image, ImageOps from transformers import AutoProcessor, BatchFeature, LlamaTokenizerFast from transformers.processing_utils import ProcessorMixin # TODO(Isotr0py): change modes for variants # see: https://github.com/deepseek-ai/DeepSeek-OCR/blob/8cf003d38821fa1b19c73da3bd1b0dc262ea8136/DeepSeek-OCR-master/DeepSeek-OCR-vllm/config.py#L1-L6 # Tiny: base_size = 512, image_size = 512, crop_mode = False # Small: base_size = 640, image_size = 640, crop_mode = False # Base: base_size = 1024, image_size = 1024, crop_mode = False # Large: base_size = 1280, image_size = 1280, crop_mode = False # Gundam: base_size = 1024, image_size = 640, crop_mode = True BASE_SIZE = 1024 IMAGE_SIZE = 640 CROP_MODE = True # TODO(Isotr0py): Expose as mm_kwargs MIN_CROPS = 2 MAX_CROPS = 6 # max:9; If your GPU memory is small, it is recommended to set it to 6. def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): best_ratio_diff = float("inf") best_ratio = (1, 1) area = width * height for ratio in target_ratios: target_aspect_ratio = ratio[0] / ratio[1] ratio_diff = abs(aspect_ratio - target_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_ratio = ratio elif ratio_diff == best_ratio_diff: if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: best_ratio = ratio return best_ratio def calculate_aspect_ratios( min_num: int = MIN_CROPS, max_num: int = MAX_CROPS ) -> list[tuple[int, int]]: target_ratios: set[tuple[int, int]] = set( (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if i * j <= max_num and i * j >= min_num ) sorted_target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) return sorted_target_ratios def count_tiles( orig_width, orig_height, min_num=MIN_CROPS, max_num=MAX_CROPS, image_size=640, use_thumbnail=False, ): aspect_ratio = orig_width / orig_height # calculate the existing image aspect ratio target_ratios = calculate_aspect_ratios(min_num, max_num) # find the closest aspect ratio to the target target_aspect_ratio = find_closest_aspect_ratio( aspect_ratio, target_ratios, orig_width, orig_height, image_size ) return target_aspect_ratio def dynamic_preprocess( image, min_num=MIN_CROPS, max_num=MAX_CROPS, image_size=640, use_thumbnail=False ): orig_width, orig_height = image.size aspect_ratio = orig_width / orig_height # calculate the existing image aspect ratio target_ratios = calculate_aspect_ratios(min_num, max_num) # find the closest aspect ratio to the target target_aspect_ratio = find_closest_aspect_ratio( aspect_ratio, target_ratios, orig_width, orig_height, image_size ) # calculate the target width and height target_width = image_size * target_aspect_ratio[0] target_height = image_size * target_aspect_ratio[1] blocks = target_aspect_ratio[0] * target_aspect_ratio[1] # resize the image resized_img = image.resize((target_width, target_height)) processed_images = [] for i in range(blocks): box = ( (i % (target_width // image_size)) * image_size, (i // (target_width // image_size)) * image_size, ((i % (target_width // image_size)) + 1) * image_size, ((i // (target_width // image_size)) + 1) * image_size, ) # split the image split_img = resized_img.crop(box) processed_images.append(split_img) assert len(processed_images) == blocks if use_thumbnail and len(processed_images) != 1: thumbnail_img = image.resize((image_size, image_size)) processed_images.append(thumbnail_img) return processed_images, target_aspect_ratio class ImageTransform: def __init__( self, mean: tuple[float, float, float] = (0.5, 0.5, 0.5), std: tuple[float, float, float] = (0.5, 0.5, 0.5), normalize: bool = True, ): self.mean = mean self.std = std self.normalize = normalize transform_pipelines = [T.ToTensor()] if normalize: transform_pipelines.append(T.Normalize(mean, std)) self.transform = T.Compose(transform_pipelines) def __call__(self, pil_img: Image.Image): x = self.transform(pil_img) return x class DeepseekOCRProcessor(ProcessorMixin): tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast") attributes = ["tokenizer"] def __init__( self, tokenizer: LlamaTokenizerFast, patch_size: int = 16, downsample_ratio: int = 4, image_mean: tuple[float, float, float] = (0.5, 0.5, 0.5), image_std: tuple[float, float, float] = (0.5, 0.5, 0.5), normalize: bool = True, image_token: str = "<image>", pad_token: str = "<|▁pad▁|>", add_special_token: bool = False, sft_format: str = "deepseek", mask_prompt: bool = True, ignore_id: int = -100, image_size: int = IMAGE_SIZE, base_size: int = BASE_SIZE, strategy: Literal["v1", "v2"] = "v1", **kwargs, ): self.image_size = image_size self.base_size = base_size # image token calculation strategy for # Deepseek-OCR and Deepseek-OCR-2 self.strategy = strategy assert strategy in ["v1", "v2"], "Only 'v1' and 'v2' strategies are supported." self.patch_size = 16 self.image_mean = image_mean self.image_std = image_std self.normalize = normalize self.downsample_ratio = 4 self.image_transform = ImageTransform( mean=image_mean, std=image_std, normalize=normalize ) self.tokenizer = tokenizer self.tokenizer.padding_side = "left" # must set this,padding side with make a difference in batch inference # noqa: E501 # add the pad_token as special token to use 'tokenizer.pad_token' # and 'tokenizer.pad_token_id' if self.tokenizer.pad_token is None: self.tokenizer.add_special_tokens({"pad_token": pad_token}) # add image token self.image_token_id = self.tokenizer.vocab.get(image_token) self.image_token = image_token self.pad_token = pad_token self.add_special_token = add_special_token self.sft_format = sft_format self.mask_prompt = mask_prompt self.ignore_id = ignore_id super().__init__( tokenizer, **kwargs, ) @property def bos_id(self): return self.tokenizer.bos_token_id @property def eos_id(self): return self.tokenizer.eos_token_id @property def pad_id(self): return self.tokenizer.pad_token_id def encode(self, text: str, bos: bool = True, eos: bool = False): t = self.tokenizer.encode(text, add_special_tokens=False) if bos: t = [self.bos_id] + t if eos: t = t + [self.eos_id] return t def decode(self, t: list[int], **kwargs) -> str: return self.tokenizer.decode(t, **kwargs) def process_one( self, prompt: str, images: list[Image.Image], crop_mode: bool = CROP_MODE, ): """ Args: prompt (str): the formatted prompt; images (List[ImageType]): the list of images; crop_mode (bool): if True, then crop the image; Returns: outputs (BaseProcessorOutput): the output of the processor, - input_ids (torch.LongTensor): [N + image tokens] - target_ids (torch.LongTensor): [N + image tokens] - pixel_values (torch.FloatTensor): [n_patches, 3, H, W] - image_id (int): the id of the image token - num_image_tokens (List[int]): the number of image tokens """ assert prompt is not None and images is not None, ( "prompt and images must be used at the same time." ) sft_format = prompt ( input_ids, pixel_values, images_crop, images_seq_mask, images_spatial_crop, num_image_tokens, _, ) = self.tokenize_with_images( conversation=sft_format, images=images, bos=True, eos=True, cropping=crop_mode, ) prepare = BatchFeature( data=dict( input_ids=input_ids, pixel_values=pixel_values, images_crop=images_crop, images_seq_mask=images_seq_mask, images_spatial_crop=images_spatial_crop, num_image_tokens=num_image_tokens, ), tensor_type="pt", ) return prepare def __call__( self, *, prompt: str, images: list[Image.Image], crop_mode: bool = CROP_MODE, **kwargs, ): prepare = self.process_one( prompt=prompt, images=images, crop_mode=crop_mode, ) return prepare def tokenize_with_images( self, conversation: str, images: list[Image.Image], bos: bool = True, eos: bool = True, cropping: bool = True, ): """Tokenize text with <image> tags.""" assert conversation.count(self.image_token) == len(images) text_splits = conversation.split(self.image_token) images_list, images_crop_list, images_seq_mask, images_spatial_crop = ( [], [], [], [], ) image_shapes = [] num_image_tokens = [] tokenized_str = [] for text_sep, image in zip(text_splits, images): tokenized_sep = self.encode(text_sep, bos=False, eos=False) tokenized_str += tokenized_sep images_seq_mask += [False] * len(tokenized_sep) image_shapes.append(image.size) images_crop_raw = [] if image.size[0] <= self.image_size and image.size[1] <= self.image_size: crop_ratio = [1, 1] elif cropping: images_crop_raw, crop_ratio = dynamic_preprocess( image, image_size=self.image_size ) else: crop_ratio = [1, 1] if not cropping: image = image.resize((self.image_size, self.image_size)) global_view = ImageOps.pad( image, (self.base_size, self.base_size), color=tuple(int(x * 255) for x in self.image_transform.mean), ) images_list.append(self.image_transform(global_view)) num_width_tiles, num_height_tiles = crop_ratio images_spatial_crop.append([num_width_tiles, num_height_tiles]) if num_width_tiles > 1 or num_height_tiles > 1: for cropped_image in images_crop_raw: images_crop_list.append(self.image_transform(cropped_image)) num_queries = math.ceil( (self.image_size // self.patch_size) / self.downsample_ratio ) num_queries_base = math.ceil( (self.base_size // self.patch_size) / self.downsample_ratio ) num_tokens_base = ( (num_queries_base * (num_queries_base + 1)) if self.strategy == "v1" else num_queries_base * num_queries_base ) tokenized_image = [self.image_token_id] * num_tokens_base tokenized_image += [self.image_token_id] if num_width_tiles > 1 or num_height_tiles > 1: num_tokens_per_row = ( num_queries * num_width_tiles + 1 if self.strategy == "v1" else num_queries * num_width_tiles ) local_row = [self.image_token_id] * num_tokens_per_row tokenized_image += local_row * (num_queries * num_height_tiles) tokenized_str += tokenized_image images_seq_mask += [True] * len(tokenized_image) num_image_tokens.append(len(tokenized_image)) """process the last text split""" tokenized_sep = self.encode(text_splits[-1], bos=False, eos=False) tokenized_str += tokenized_sep images_seq_mask += [False] * len(tokenized_sep) """add the bos and eos tokens""" if bos: tokenized_str = [self.bos_id] + tokenized_str images_seq_mask = [False] + images_seq_mask if eos: tokenized_str = tokenized_str + [self.eos_id] images_seq_mask = images_seq_mask + [False] assert len(tokenized_str) == len(images_seq_mask), ( f"tokenize_with_images func: tokenized_str's length {len(tokenized_str)} " f"is not equal to images_seq_mask's length {len(images_seq_mask)}." ) masked_tokenized_str = [] for token_index in tokenized_str: if token_index != self.image_token_id: masked_tokenized_str.append(token_index) else: masked_tokenized_str.append(self.ignore_id) assert ( len(tokenized_str) == len(images_seq_mask) == len(masked_tokenized_str) ), ( f"tokenized_str's length {len(tokenized_str)}, " f"input_ids' length {len(masked_tokenized_str)}, " f"images_seq_mask's length {len(images_seq_mask)}, are not equal." ) input_ids = torch.LongTensor(tokenized_str) target_ids = torch.LongTensor(masked_tokenized_str) images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool) # set input_ids < 0 | input_ids == self.image_token_id as ignore_id target_ids[(input_ids < 0) | (input_ids == self.image_token_id)] = ( self.ignore_id ) input_ids[input_ids < 0] = self.pad_id # Remove the ending eos token assert input_ids[-1] == self.eos_id input_ids = input_ids[:-1] target_ids = target_ids[:-1] images_seq_mask = images_seq_mask[:-1] if len(images_list) == 0: pixel_values = torch.zeros((0, 3, self.base_size, self.base_size)) images_spatial_crop = torch.zeros((0, 2), dtype=torch.long) images_crop = torch.zeros((0, 3, self.image_size, self.image_size)) else: pixel_values = torch.stack(images_list, dim=0) images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long) if images_crop_list: images_crop = torch.stack(images_crop_list, dim=0) else: images_crop = torch.zeros((0, 3, self.image_size, self.image_size)) input_ids = input_ids.unsqueeze(0) return ( input_ids, pixel_values, images_crop, images_seq_mask, images_spatial_crop, num_image_tokens, image_shapes, ) AutoProcessor.register("DeepseekOCRProcessor", DeepseekOCRProcessor)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/transformers_utils/processors/deepseek_ocr.py", "license": "Apache License 2.0", "lines": 386, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/utils_/test_serial_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from tests.models.utils import check_embeddings_close from vllm.utils.serial_utils import ( EMBED_DTYPES, ENDIANNESS, EmbedDType, Endianness, binary2tensor, tensor2binary, ) @pytest.mark.parametrize("endianness", ENDIANNESS) @pytest.mark.parametrize("embed_dtype", EMBED_DTYPES.keys()) @torch.inference_mode() def test_encode_and_decode(embed_dtype: EmbedDType, endianness: Endianness): for i in range(10): tensor = torch.rand(2, 3, 5, 7, 11, 13, device="cpu", dtype=torch.float32) shape = tensor.shape binary = tensor2binary(tensor, embed_dtype, endianness) new_tensor = binary2tensor(binary, shape, embed_dtype, endianness).to( torch.float32 ) if embed_dtype in ["float32", "float16"]: torch.testing.assert_close(tensor, new_tensor, atol=0.001, rtol=0.001) elif embed_dtype == "bfloat16": torch.testing.assert_close(tensor, new_tensor, atol=0.01, rtol=0.01) else: # for fp8 torch.testing.assert_close(tensor, new_tensor, atol=0.1, rtol=0.1) check_embeddings_close( embeddings_0_lst=tensor.view(1, -1), embeddings_1_lst=new_tensor.view(1, -1), name_0="gt", name_1="new", tol=1e-2, )
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_serial_utils.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/serial_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import io import sys from collections.abc import Mapping from dataclasses import dataclass from typing import Literal, get_args import numpy as np import numpy.typing as npt import pybase64 import torch sys_byteorder = sys.byteorder @dataclass(frozen=True) class DTypeInfo: torch_dtype: torch.dtype torch_view_dtype: torch.dtype numpy_view_dtype: npt.DTypeLike @property def nbytes(self) -> int: return self.torch_dtype.itemsize EmbedDType = Literal["float32", "float16", "bfloat16", "fp8_e4m3", "fp8_e5m2"] Endianness = Literal["native", "big", "little"] EncodingFormat = Literal["float", "base64", "bytes", "bytes_only"] # I'm not sure if other platforms' CPUs support the fp8 data format. # EMBED_DTYPE only uses the fp8 data representation, # does not use fp8 computation, and only occurs on the CPU. # Apologize for any possible break. # NOTE: numpy does not support bfloat16 and fp8 EMBED_DTYPES: Mapping[EmbedDType, DTypeInfo] = { "float32": DTypeInfo(torch.float32, torch.float32, np.float32), "float16": DTypeInfo(torch.float16, torch.float16, np.float16), "bfloat16": DTypeInfo(torch.bfloat16, torch.float16, np.float16), "fp8_e4m3": DTypeInfo(torch.float8_e4m3fn, torch.uint8, np.uint8), "fp8_e5m2": DTypeInfo(torch.float8_e5m2, torch.uint8, np.uint8), } ENDIANNESS: tuple[Endianness, ...] = get_args(Endianness) def tensor2base64(x: torch.Tensor) -> str: with io.BytesIO() as buf: torch.save(x, buf) buf.seek(0) binary_data = buf.read() return pybase64.b64encode(binary_data).decode("utf-8") def tensor2binary( tensor: torch.Tensor, embed_dtype: EmbedDType, endianness: Endianness, ) -> bytes: assert isinstance(tensor, torch.Tensor) assert embed_dtype in EMBED_DTYPES assert endianness in ENDIANNESS dtype_info = EMBED_DTYPES[embed_dtype] np_array = ( tensor.to(dtype_info.torch_dtype) .flatten() .contiguous() .view(dtype_info.torch_view_dtype) .numpy() ) if endianness != "native" and endianness != sys_byteorder: np_array = np_array.byteswap() return np_array.tobytes() def binary2tensor( binary: bytes, shape: tuple[int, ...], embed_dtype: EmbedDType, endianness: Endianness, ) -> torch.Tensor: assert embed_dtype in EMBED_DTYPES assert endianness in ENDIANNESS dtype_info = EMBED_DTYPES[embed_dtype] np_array = np.frombuffer(binary, dtype=dtype_info.numpy_view_dtype).reshape(shape) if endianness != "native" and endianness != sys_byteorder: np_array = np_array.byteswap() return torch.from_numpy(np_array).view(dtype_info.torch_dtype)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/serial_utils.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/benchmarks/sweep/param_sweep.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import json import os from typing import Any class ParameterSweep(list["ParameterSweepItem"]): @classmethod def read_json(cls, filepath: os.PathLike): with open(filepath, "rb") as f: data = json.load(f) # Support both list and dict formats if isinstance(data, dict): return cls.read_from_dict(data) return cls.from_records(data) @classmethod def read_from_dict(cls, data: dict[str, dict[str, object]]): """ Read parameter sweep from a dict format where keys are names. Example: { "experiment1": {"max_tokens": 100, "temperature": 0.7}, "experiment2": {"max_tokens": 200, "temperature": 0.9} } """ records = [{"_benchmark_name": name, **params} for name, params in data.items()] return cls.from_records(records) @classmethod def from_records(cls, records: list[dict[str, object]]): if not isinstance(records, list): raise TypeError( f"The parameter sweep should be a list of dictionaries, " f"but found type: {type(records)}" ) # Validate that all _benchmark_name values are unique if provided names = [r["_benchmark_name"] for r in records if "_benchmark_name" in r] if names and len(names) != len(set(names)): duplicates = [name for name in names if names.count(name) > 1] raise ValueError( f"Duplicate _benchmark_name values found: {set(duplicates)}. " f"All _benchmark_name values must be unique." ) return cls(ParameterSweepItem.from_record(record) for record in records) class ParameterSweepItem(dict[str, object]): @classmethod def from_record(cls, record: dict[str, object]): if not isinstance(record, dict): raise TypeError( f"Each item in the parameter sweep should be a dictionary, " f"but found type: {type(record)}" ) return cls(record) def __or__(self, other: dict[str, Any]): return type(self)(super().__or__(other)) @property def name(self) -> str: """ Get the name for this parameter sweep item. Returns the '_benchmark_name' field if present, otherwise returns a text representation of all parameters. """ if "_benchmark_name" in self: return str(self["_benchmark_name"]) return self.as_text(sep="-") # In JSON, we prefer "_" def _iter_param_key_candidates(self, param_key: str): # Inner config arguments are not converted by the CLI if "." in param_key: prefix, rest = param_key.split(".", 1) for prefix_candidate in self._iter_param_key_candidates(prefix): yield prefix_candidate + "." + rest return yield param_key yield param_key.replace("-", "_") yield param_key.replace("_", "-") # In CLI, we prefer "-" def _iter_cmd_key_candidates(self, param_key: str): for k in reversed(tuple(self._iter_param_key_candidates(param_key))): yield "--" + k def _normalize_cmd_key(self, param_key: str): return next(self._iter_cmd_key_candidates(param_key)) def has_param(self, param_key: str) -> bool: return any(k in self for k in self._iter_param_key_candidates(param_key)) def _normalize_cmd_kv_pair(self, k: str, v: object) -> list[str]: """ Normalize a key-value pair into command-line arguments. Returns a list containing either: - A single element for boolean flags (e.g., ['--flag'] or ['--flag=true']) - Two elements for key-value pairs (e.g., ['--key', 'value']) """ if isinstance(v, bool): # For nested params (containing "."), use =true/false syntax if "." in k: return [f"{self._normalize_cmd_key(k)}={'true' if v else 'false'}"] else: return [self._normalize_cmd_key(k if v else "no-" + k)] else: return [self._normalize_cmd_key(k), str(v)] def apply_to_cmd(self, cmd: list[str]) -> list[str]: cmd = list(cmd) for k, v in self.items(): # Skip the '_benchmark_name' field, not a parameter if k == "_benchmark_name": continue # Serialize dict values as JSON if isinstance(v, dict): v = json.dumps(v) for k_candidate in self._iter_cmd_key_candidates(k): try: k_idx = cmd.index(k_candidate) # Replace existing parameter normalized = self._normalize_cmd_kv_pair(k, v) if len(normalized) == 1: # Boolean flag cmd[k_idx] = normalized[0] else: # Key-value pair cmd[k_idx] = normalized[0] cmd[k_idx + 1] = normalized[1] break except ValueError: continue else: # Add new parameter cmd.extend(self._normalize_cmd_kv_pair(k, v)) return cmd def as_text(self, sep: str = ", ") -> str: return sep.join(f"{k}={v}" for k, v in self.items() if k != "_benchmark_name")
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/benchmarks/sweep/param_sweep.py", "license": "Apache License 2.0", "lines": 127, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/benchmarks/sweep/plot.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import argparse import json from abc import ABC, abstractmethod from concurrent.futures import ProcessPoolExecutor from dataclasses import dataclass from functools import partial from pathlib import Path from types import TracebackType from typing import ClassVar from typing_extensions import Self, override from vllm.utils.collection_utils import full_groupby from vllm.utils.import_utils import PlaceholderModule from .utils import sanitize_filename try: import matplotlib.pyplot as plt except ImportError: plt = PlaceholderModule("matplotlib").placeholder_attr("pyplot") try: import pandas as pd except ImportError: pd = PlaceholderModule("pandas") try: import seaborn as sns except ImportError: seaborn = PlaceholderModule("seaborn") @dataclass class PlotFilterBase(ABC): var: str target: str @classmethod def parse_str(cls, s: str): for op_key in PLOT_FILTERS: if op_key in s: key, value = s.split(op_key) return PLOT_FILTERS[op_key]( key, value.removeprefix(op_key).strip("'").strip('"'), ) else: raise ValueError( f"Invalid operator for plot filter '{s}'. " f"Valid operators are: {sorted(PLOT_FILTERS)}", ) @abstractmethod def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": """Applies this filter to a DataFrame.""" raise NotImplementedError @dataclass class PlotEqualTo(PlotFilterBase): @override def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": try: target = float(self.target) except ValueError: target = self.target return df[df[self.var] == target] @dataclass class PlotNotEqualTo(PlotFilterBase): @override def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": try: target = float(self.target) except ValueError: target = self.target return df[df[self.var] != target] @dataclass class PlotLessThan(PlotFilterBase): @override def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": return df[df[self.var] < float(self.target)] @dataclass class PlotLessThanOrEqualTo(PlotFilterBase): @override def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": return df[df[self.var] <= float(self.target)] @dataclass class PlotGreaterThan(PlotFilterBase): @override def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": return df[df[self.var] > float(self.target)] @dataclass class PlotGreaterThanOrEqualTo(PlotFilterBase): @override def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": return df[df[self.var] >= float(self.target)] # NOTE: The ordering is important! Match longer op_keys first PLOT_FILTERS: dict[str, type[PlotFilterBase]] = { "==": PlotEqualTo, "!=": PlotNotEqualTo, "<=": PlotLessThanOrEqualTo, ">=": PlotGreaterThanOrEqualTo, "<": PlotLessThan, ">": PlotGreaterThan, } class PlotFilters(list[PlotFilterBase]): @classmethod def parse_str(cls, s: str): if not s: return cls() return cls(PlotFilterBase.parse_str(e) for e in s.split(",")) def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": for item in self: df = item.apply(df) return df @dataclass class PlotBinner: var: str bin_size: float @classmethod def parse_str(cls, s: str): for op_key in PLOT_BINNERS: if op_key in s: key, value = s.split(op_key) return PLOT_BINNERS[op_key](key, float(value.removeprefix(op_key))) else: raise ValueError( f"Invalid operator for plot binner '{s}'. " f"Valid operators are: {sorted(PLOT_BINNERS)}", ) def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": """Applies this binner to a DataFrame.""" df = df.copy() df[self.var] = df[self.var] // self.bin_size * self.bin_size return df PLOT_BINNERS: dict[str, type[PlotBinner]] = { "%": PlotBinner, } class PlotBinners(list[PlotBinner]): @classmethod def parse_str(cls, s: str): if not s: return cls() return cls(PlotBinner.parse_str(e) for e in s.split(",")) def apply(self, df: "pd.DataFrame") -> "pd.DataFrame": for item in self: df = item.apply(df) return df def _json_load_bytes(path: Path) -> list[dict[str, object]]: with path.open("rb") as f: return json.load(f) def _convert_inf_nan_strings(data: list[dict[str, object]]) -> list[dict[str, object]]: """ Convert string values "inf", "-inf", and "nan" to their float equivalents. This handles the case where JSON serialization represents inf/nan as strings. """ converted_data = [] for record in data: converted_record = {} for key, value in record.items(): if isinstance(value, str): if value in ["inf", "-inf", "nan"]: converted_record[key] = float(value) else: converted_record[key] = value else: converted_record[key] = value converted_data.append(converted_record) return converted_data def _get_metric(run_data: dict[str, object], metric_key: str): try: return run_data[metric_key] except KeyError as exc: raise ValueError(f"Cannot find metric {metric_key!r} in {run_data=}") from exc def _get_group(run_data: dict[str, object], group_keys: list[str]): return tuple((k, str(_get_metric(run_data, k))) for k in group_keys) def _get_fig_path(fig_dir: Path, group: tuple[tuple[str, str], ...], fig_name: str): parts = list[str]() # Start with figure name (always provided, defaults to "FIGURE") parts.append(fig_name) # Always append group data if present if group: parts.extend(f"{k}={v}" for k, v in group) return fig_dir / sanitize_filename("-".join(parts) + ".png") class DummyExecutor: map = map def __enter__(self) -> Self: return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_traceback: TracebackType | None, ) -> None: return None def _plot_fig( fig_dir: Path, fig_group_data: tuple[tuple[tuple[str, str], ...], list[dict[str, object]]], row_by: list[str], col_by: list[str], curve_by: list[str], *, var_x: str, var_y: str, filter_by: PlotFilters, bin_by: PlotBinners, scale_x: str | None, scale_y: str | None, dry_run: bool, fig_name: str, error_bars: bool, fig_height: float, fig_dpi: int, ): fig_group, fig_data = fig_group_data row_groups = full_groupby( fig_data, key=lambda item: _get_group(item, row_by), ) num_rows = len(row_groups) num_cols = max( len(full_groupby(row_data, key=lambda item: _get_group(item, col_by))) for _, row_data in row_groups ) fig_path = _get_fig_path(fig_dir, fig_group, fig_name) print("[BEGIN FIGURE]") print(f"Group: {dict(fig_group)}") print(f"Grid: {num_rows} rows x {num_cols} cols") print(f"Output file: {fig_path}") if dry_run: print("[END FIGURE]") return # Convert string "inf", "-inf", and "nan" to their float equivalents fig_data = _convert_inf_nan_strings(fig_data) df = pd.DataFrame.from_records(fig_data) if var_x not in df.columns: raise ValueError( f"Cannot find {var_x=!r} in parameter sweep results. " f"Available variables: {df.columns.tolist()}" ) if var_y not in df.columns: raise ValueError( f"Cannot find {var_y=!r} in parameter sweep results. " f"Available variables: {df.columns.tolist()}" ) for k in row_by: if k not in df.columns: raise ValueError( f"Cannot find row_by={k!r} in parameter sweep results. " f"Available variables: {df.columns.tolist()}" ) for k in col_by: if k not in df.columns: raise ValueError( f"Cannot find col_by={k!r} in parameter sweep results. " f"Available variables: {df.columns.tolist()}" ) for k in curve_by: if k not in df.columns: raise ValueError( f"Cannot find curve_by={k!r} in parameter sweep results. " f"Available variables: {df.columns.tolist()}" ) df = filter_by.apply(df) df = bin_by.apply(df) if len(df) == 0: print(f"No data to plot. Filters: {filter_by}") print("[END FIGURE]") return # Sort by curve_by columns alphabetically for consistent legend ordering if curve_by: df = df.sort_values(by=curve_by) df["row_group"] = ( pd.concat( [k + "=" + df[k].astype(str) for k in row_by], axis=1, ).agg("\n".join, axis=1) if row_by else "(All)" ) df["col_group"] = ( pd.concat( [k + "=" + df[k].astype(str) for k in col_by], axis=1, ).agg("\n".join, axis=1) if col_by else "(All)" ) if len(curve_by) <= 3: hue, style, size, *_ = (*curve_by, None, None, None) g = sns.relplot( df, x=var_x, y=var_y, hue=hue, style=style, size=size, markers=True, errorbar="sd" if error_bars else None, kind="line", row="row_group", col="col_group", height=fig_height, ) else: df["curve_group"] = ( pd.concat( [k + "=" + df[k].astype(str) for k in curve_by], axis=1, ).agg("\n".join, axis=1) if curve_by else "(All)" ) g = sns.relplot( df, x=var_x, y=var_y, hue="curve_group", markers=True, errorbar="sd" if error_bars else None, kind="line", row="row_group", col="col_group", height=fig_height, ) if row_by and col_by: g.set_titles("{row_name}\n{col_name}") elif row_by: g.set_titles("{row_name}") elif col_by: g.set_titles("{col_name}") else: g.set_titles("") if scale_x: g.set(xscale=scale_x) if scale_y: g.set(yscale=scale_y) g.savefig(fig_path, dpi=fig_dpi) plt.close(g.figure) print("[END FIGURE]") def plot( output_dir: Path, fig_dir: Path, fig_by: list[str], row_by: list[str], col_by: list[str], curve_by: list[str], *, var_x: str, var_y: str, filter_by: PlotFilters, bin_by: PlotBinners, scale_x: str | None, scale_y: str | None, dry_run: bool, fig_name: str = "FIGURE", error_bars: bool = True, fig_height: float = 6.4, fig_dpi: int = 300, ): all_data = [ run_data for path in output_dir.rglob("**/summary.json") for run_data in _json_load_bytes(path) ] if not all_data: raise ValueError(f"Did not find any parameter sweep results under {output_dir}") fig_dir.mkdir(parents=True, exist_ok=True) fig_groups = full_groupby( all_data, key=lambda item: _get_group(item, fig_by), ) with DummyExecutor() if len(fig_groups) <= 1 else ProcessPoolExecutor() as executor: # Resolve the iterable to ensure that the workers are run all( executor.map( partial( _plot_fig, fig_dir, row_by=row_by, col_by=col_by, curve_by=curve_by, var_x=var_x, var_y=var_y, filter_by=filter_by, bin_by=bin_by, scale_x=scale_x, scale_y=scale_y, dry_run=dry_run, fig_name=fig_name, error_bars=error_bars, fig_height=fig_height, fig_dpi=fig_dpi, ), fig_groups, ) ) @dataclass class SweepPlotArgs: output_dir: Path fig_dir: Path fig_by: list[str] row_by: list[str] col_by: list[str] curve_by: list[str] var_x: str var_y: str filter_by: PlotFilters bin_by: PlotBinners scale_x: str | None scale_y: str | None dry_run: bool fig_name: str = "FIGURE" error_bars: bool = True fig_height: float = 6.4 fig_dpi: int = 300 parser_name: ClassVar[str] = "plot" parser_help: ClassVar[str] = "Plot performance curves from parameter sweep results." @classmethod def from_cli_args(cls, args: argparse.Namespace): output_dir = Path(args.EXPERIMENT_DIR) if not output_dir.exists(): raise ValueError(f"No parameter sweep results under {output_dir}") curve_by = [] if not args.curve_by else args.curve_by.split(",") row_by = [] if not args.row_by else args.row_by.split(",") col_by = [] if not args.col_by else args.col_by.split(",") fig_by = [] if not args.fig_by else args.fig_by.split(",") return cls( output_dir=output_dir, fig_dir=output_dir / args.fig_dir, fig_by=fig_by, row_by=row_by, col_by=col_by, curve_by=curve_by, var_x=args.var_x, var_y=args.var_y, filter_by=PlotFilters.parse_str(args.filter_by), bin_by=PlotBinners.parse_str(args.bin_by), scale_x=args.scale_x, scale_y=args.scale_y, dry_run=args.dry_run, fig_name=args.fig_name, error_bars=not args.no_error_bars, fig_height=args.fig_height, fig_dpi=args.fig_dpi, ) @classmethod def add_cli_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser: parser.add_argument( "EXPERIMENT_DIR", type=str, help="The directory containing the sweep results to plot.", ) parser.add_argument( "--fig-dir", type=str, default="", help="The directory to save the figures, relative to `OUTPUT_DIR`. " "By default, the same directory is used.", ) parser.add_argument( "--fig-by", type=str, default="", help="A comma-separated list of variables, such that a separate figure " "is created for each combination of these variables.", ) parser.add_argument( "--row-by", type=str, default="", help="A comma-separated list of variables, such that a separate row " "is created for each combination of these variables.", ) parser.add_argument( "--col-by", type=str, default="", help="A comma-separated list of variables, such that a separate column " "is created for each combination of these variables.", ) parser.add_argument( "--curve-by", type=str, default=None, help="A comma-separated list of variables, such that a separate curve " "is created for each combination of these variables.", ) parser.add_argument( "--var-x", type=str, default="total_token_throughput", help="The variable for the x-axis.", ) parser.add_argument( "--var-y", type=str, default="median_ttft_ms", help="The variable for the y-axis", ) parser.add_argument( "--filter-by", type=str, default="", help="A comma-separated list of statements indicating values to filter by. " "This is useful to remove outliers. " "Example: `max_concurrency<1000,max_num_batched_tokens<=4096` means " "plot only the points where `max_concurrency` is less than 1000 and " "`max_num_batched_tokens` is no greater than 4096.", ) parser.add_argument( "--bin-by", type=str, default="", help="A comma-separated list of statements indicating values to bin by. " "This is useful to avoid plotting points that are too close together. " "Example: `request_throughput%%1` means " "use a bin size of 1 for the `request_throughput` variable.", ) parser.add_argument( "--scale-x", type=str, default=None, help="The scale to use for the x-axis. " "Currently only accepts string values such as 'log' and 'sqrt'. " "See also: https://seaborn.pydata.org/generated/seaborn.objects.Plot.scale.html", ) parser.add_argument( "--scale-y", type=str, default=None, help="The scale to use for the y-axis. " "Currently only accepts string values such as 'log' and 'sqrt'. " "See also: https://seaborn.pydata.org/generated/seaborn.objects.Plot.scale.html", ) parser.add_argument( "--fig-name", type=str, default="FIGURE", help="Name prefix for the output figure file. " "Group data is always appended when present. " "Default: 'FIGURE'. Example: --fig-name my_performance_plot", ) parser.add_argument( "--no-error-bars", action="store_true", help="If set, disables error bars on the plot. " "By default, error bars are shown.", ) parser.add_argument( "--fig-height", type=float, default=6.4, help="Height of each subplot in inches. Default: 6.4", ) parser.add_argument( "--fig-dpi", type=int, default=300, help="Resolution of the output figure in dots per inch. Default: 300", ) parser.add_argument( "--dry-run", action="store_true", help="If set, prints the information about each figure to plot, " "then exits without drawing them.", ) return parser def run_main(args: SweepPlotArgs): return plot( output_dir=args.output_dir, fig_dir=args.fig_dir, fig_by=args.fig_by, row_by=args.row_by, col_by=args.col_by, curve_by=args.curve_by, var_x=args.var_x, var_y=args.var_y, filter_by=args.filter_by, bin_by=args.bin_by, scale_x=args.scale_x, scale_y=args.scale_y, dry_run=args.dry_run, fig_name=args.fig_name, error_bars=args.error_bars, fig_height=args.fig_height, fig_dpi=args.fig_dpi, ) def main(args: argparse.Namespace): run_main(SweepPlotArgs.from_cli_args(args)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=SweepPlotArgs.parser_help) SweepPlotArgs.add_cli_args(parser) main(parser.parse_args())
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/benchmarks/sweep/plot.py", "license": "Apache License 2.0", "lines": 585, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/benchmarks/sweep/serve.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import argparse import contextlib import json import shlex from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import ClassVar from vllm.utils.import_utils import PlaceholderModule from .param_sweep import ParameterSweep, ParameterSweepItem from .server import ServerProcess from .utils import sanitize_filename try: import pandas as pd except ImportError: pd = PlaceholderModule("pandas") @contextlib.contextmanager def run_server( serve_cmd: list[str], after_bench_cmd: list[str], *, show_stdout: bool, serve_overrides: ParameterSweepItem, dry_run: bool, server_ready_timeout: int = 300, ): server_cmd = serve_overrides.apply_to_cmd(serve_cmd) print("[BEGIN SERVER]") print(f"Server overrides: {serve_overrides}") print(f"Server command: {server_cmd}") if dry_run: yield None print("[END SERVER]") return with ServerProcess(server_cmd, after_bench_cmd, show_stdout=show_stdout) as server: server.wait_until_ready(timeout=server_ready_timeout) yield server print("[END SERVER]") def _update_run_data( run_data: dict[str, object], serve_overrides: ParameterSweepItem, bench_overrides: ParameterSweepItem, run_number: int, ): run_data["run_number"] = run_number run_data.update(serve_overrides) run_data.update(bench_overrides) return run_data def run_benchmark( server: ServerProcess | None, bench_cmd: list[str], *, serve_overrides: ParameterSweepItem, bench_overrides: ParameterSweepItem, run_number: int, output_path: Path, dry_run: bool, ): benchmark_cmd = [ *bench_overrides.apply_to_cmd(bench_cmd), "--percentile-metrics", "ttft,tpot,itl,e2el", "--save-result", "--result-dir", str(output_path.parent), "--result-filename", output_path.name, ] print("[BEGIN BENCHMARK]") print(f"Benchmark overrides: {bench_overrides}") print(f"Run Number: {run_number}") print(f"Benchmark command: {benchmark_cmd}") print(f"Output file: {output_path}") run_data: dict[str, object] if output_path.exists(): print("Found existing results.") print("[SKIPPED BENCHMARK]") with output_path.open("rb") as f: run_data = json.load(f) return _update_run_data( run_data, serve_overrides, bench_overrides, run_number, ) if server is None: if not dry_run: raise ValueError(f"Cannot find results at {output_path}") print("[END BENCHMARK]") return None output_path.parent.mkdir(parents=True, exist_ok=True) server.run_subcommand(benchmark_cmd) server.after_bench() with output_path.open("rb") as f: run_data = json.load(f) run_data = _update_run_data( run_data, serve_overrides, bench_overrides, run_number, ) with output_path.open("w") as f: json.dump(run_data, f, indent=4) print("[END BENCHMARK]") return run_data def _get_comb_base_path( experiment_dir: Path, serve_comb: ParameterSweepItem, bench_comb: ParameterSweepItem, *, extra_parts: tuple[str, ...] = (), ): parts = list[str]() if serve_comb: parts.extend(("SERVE-", serve_comb.name)) if bench_comb: parts.extend(("BENCH-", bench_comb.name)) if extra_parts: parts.extend(extra_parts) return experiment_dir / sanitize_filename("-".join(parts)) def _get_comb_run_path(base_path: Path, run_number: int | None): if run_number is None: return base_path / "summary.json" return base_path / f"run={run_number}.json" def _comb_needs_server( serve_comb: ParameterSweepItem, bench_combs: ParameterSweep, experiment_dir: Path, ): for bench_comb in bench_combs: base_path = _get_comb_base_path(experiment_dir, serve_comb, bench_comb) if not _get_comb_run_path(base_path, run_number=None).exists(): return True return False def server_ctx( serve_cmd: list[str], after_bench_cmd: list[str], *, show_stdout: bool, serve_comb: ParameterSweepItem, bench_params: ParameterSweep, experiment_dir: Path, dry_run: bool, server_ready_timeout: int = 300, ): if not _comb_needs_server(serve_comb, bench_params, experiment_dir): return contextlib.nullcontext() return run_server( serve_cmd, after_bench_cmd, show_stdout=show_stdout, serve_overrides=serve_comb, dry_run=dry_run, server_ready_timeout=server_ready_timeout, ) def _comb_is_valid( serve_comb: ParameterSweepItem, bench_comb: ParameterSweepItem, link_vars: list[tuple[str, str]], ) -> bool: return all( serve_key in serve_comb and bench_key in bench_comb and serve_comb[serve_key] == bench_comb[bench_key] for serve_key, bench_key in link_vars ) def run_comb( server: ServerProcess | None, bench_cmd: list[str], *, serve_comb: ParameterSweepItem, bench_comb: ParameterSweepItem, link_vars: list[tuple[str, str]], base_path: Path, num_runs: int, dry_run: bool, ): if not _comb_is_valid(serve_comb, bench_comb, link_vars): return None comb_data = list[dict[str, object]]() for run_number in range(num_runs): run_data = run_benchmark( server, bench_cmd, serve_overrides=serve_comb, bench_overrides=bench_comb, run_number=run_number, output_path=_get_comb_run_path(base_path, run_number), dry_run=dry_run, ) if run_data is not None: comb_data.append(run_data) if dry_run: return None with _get_comb_run_path(base_path, run_number=None).open("w") as f: json.dump(comb_data, f, indent=4) return comb_data def run_combs( serve_cmd: list[str], bench_cmd: list[str], after_bench_cmd: list[str], *, show_stdout: bool, server_ready_timeout: int, serve_params: ParameterSweep, bench_params: ParameterSweep, link_vars: list[tuple[str, str]], experiment_dir: Path, num_runs: int, dry_run: bool, ): all_data = list[dict[str, object]]() for serve_comb in serve_params: with server_ctx( serve_cmd, after_bench_cmd, show_stdout=show_stdout, serve_comb=serve_comb, bench_params=bench_params, experiment_dir=experiment_dir, dry_run=dry_run, server_ready_timeout=server_ready_timeout, ) as server: for bench_comb in bench_params: base_path = _get_comb_base_path(experiment_dir, serve_comb, bench_comb) comb_data = run_comb( server, bench_cmd, serve_comb=serve_comb, bench_comb=bench_comb, link_vars=link_vars, base_path=base_path, num_runs=num_runs, dry_run=dry_run, ) if comb_data is not None: all_data.extend(comb_data) if dry_run: return None combined_df = pd.DataFrame.from_records(all_data) combined_df.to_csv(experiment_dir / "summary.csv") return combined_df @dataclass class SweepServeArgs: serve_cmd: list[str] bench_cmd: list[str] after_bench_cmd: list[str] show_stdout: bool server_ready_timeout: int serve_params: ParameterSweep bench_params: ParameterSweep link_vars: list[tuple[str, str]] output_dir: Path experiment_name: str num_runs: int dry_run: bool resume: bool parser_name: ClassVar[str] = "serve" parser_help: ClassVar[str] = "Run vLLM server benchmark under multiple settings." @classmethod def from_cli_args(cls, args: argparse.Namespace): serve_cmd = shlex.split(args.serve_cmd) bench_cmd = shlex.split(args.bench_cmd) after_bench_cmd = ( [] if args.after_bench_cmd is None else shlex.split(args.after_bench_cmd) ) if args.serve_params: serve_params = ParameterSweep.read_json(args.serve_params) else: # i.e.: run serve_cmd without any modification serve_params = ParameterSweep.from_records([{}]) if args.bench_params: bench_params = ParameterSweep.read_json(args.bench_params) else: # i.e.: run bench_cmd without any modification bench_params = ParameterSweep.from_records([{}]) link_vars = cls.parse_link_vars(args.link_vars) if args.experiment_name: experiment_name = args.experiment_name else: experiment_name = datetime.now().strftime("%Y%m%d_%H%M%S") num_runs = args.num_runs if num_runs < 1: raise ValueError("`num_runs` should be at least 1.") return cls( serve_cmd=serve_cmd, bench_cmd=bench_cmd, after_bench_cmd=after_bench_cmd, show_stdout=args.show_stdout, serve_params=serve_params, bench_params=bench_params, link_vars=link_vars, output_dir=Path(args.output_dir), experiment_name=experiment_name, num_runs=num_runs, dry_run=args.dry_run, resume=args.resume, server_ready_timeout=args.server_ready_timeout, ) @classmethod def add_cli_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser: parser.add_argument( "--serve-cmd", type=str, required=True, help="The command used to run the server: `vllm serve ...`", ) parser.add_argument( "--bench-cmd", type=str, required=True, help="The command used to run the benchmark: `vllm bench serve ...`", ) parser.add_argument( "--after-bench-cmd", type=str, default=None, help="After a benchmark run is complete, invoke this command instead of " "the default `ServerWrapper.clear_cache()`.", ) parser.add_argument( "--show-stdout", action="store_true", help="If set, logs the standard output of subcommands. " "Useful for debugging but can be quite spammy.", ) parser.add_argument( "--server-ready-timeout", type=int, default=300, help="Timeout in seconds to wait for the server to become ready.", ) parser.add_argument( "--serve-params", type=str, default=None, help="Path to JSON file containing parameter combinations " "for the `vllm serve` command. Can be either a list of dicts or a dict " "where keys are benchmark names. " "If both `serve_params` and `bench_params` are given, " "this script will iterate over their Cartesian product.", ) parser.add_argument( "--link-vars", type=str, default="", help=( "Comma-separated list of linked variables between serve and bench, " "e.g. max_num_seqs=max_concurrency,max_model_len=random_input_len" ), ) parser.add_argument( "--bench-params", type=str, default=None, help="Path to JSON file containing parameter combinations " "for the `vllm bench serve` command. Can be either a list of dicts or " "a dict where keys are benchmark names. " "If both `serve_params` and `bench_params` are given, " "this script will iterate over their Cartesian product.", ) parser.add_argument( "-o", "--output-dir", type=str, default="results", help="The main directory to which results are written.", ) parser.add_argument( "-e", "--experiment-name", type=str, default=None, help="The name of this experiment (defaults to current timestamp). " "Results will be stored under `output_dir/experiment_name`.", ) parser.add_argument( "--num-runs", type=int, default=3, help="Number of runs per parameter combination.", ) parser.add_argument( "--dry-run", action="store_true", help="If set, prints the commands to run, " "then exits without executing them.", ) parser.add_argument( "--resume", action="store_true", help="Resume a previous execution of this script, i.e., only run " "parameter combinations for which there are still no output files " "under `output_dir/experiment_name`.", ) return parser @staticmethod def parse_link_vars(s: str) -> list[tuple[str, str]]: if not s: return [] pairs = [] for item in s.split(","): a, b = item.split("=") pairs.append((a.strip(), b.strip())) return pairs def resolve_experiment_dir(self) -> Path: experiment_dir = self.output_dir / self.experiment_name if self.resume: if not experiment_dir.exists(): raise ValueError(f"Cannot resume from non-existent {experiment_dir=}") else: if experiment_dir.exists(): raise ValueError(f"Cannot overwrite existing {experiment_dir=}") return experiment_dir @contextmanager def run_ctx(self, experiment_dir: Path): if self.dry_run: yield print(f"Experiment will be saved at: {experiment_dir}") return try: yield print(f"Experiment has been saved at: {experiment_dir}") except BaseException as exc: raise RuntimeError( "The script was terminated early. Use `--resume` " "to continue the script from its last checkpoint." ) from exc def run_main(args: SweepServeArgs): experiment_dir = args.resolve_experiment_dir() with args.run_ctx(experiment_dir): return run_combs( serve_cmd=args.serve_cmd, bench_cmd=args.bench_cmd, link_vars=args.link_vars, after_bench_cmd=args.after_bench_cmd, show_stdout=args.show_stdout, server_ready_timeout=args.server_ready_timeout, serve_params=args.serve_params, bench_params=args.bench_params, experiment_dir=experiment_dir, num_runs=args.num_runs, dry_run=args.dry_run, ) def main(args: argparse.Namespace): run_main(SweepServeArgs.from_cli_args(args)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=SweepServeArgs.parser_help) SweepServeArgs.add_cli_args(parser) main(parser.parse_args())
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/benchmarks/sweep/serve.py", "license": "Apache License 2.0", "lines": 453, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/benchmarks/sweep/server.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import os import signal import subprocess import time from types import TracebackType import requests from typing_extensions import Self class ServerProcess: VLLM_RESET_CACHE_ENDPOINTS = [ "/reset_prefix_cache", "/reset_mm_cache", "/reset_encoder_cache", ] def __init__( self, server_cmd: list[str], after_bench_cmd: list[str], *, show_stdout: bool, ) -> None: super().__init__() self.server_cmd = server_cmd self.after_bench_cmd = after_bench_cmd self.show_stdout = show_stdout def __enter__(self) -> Self: self.start() return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_traceback: TracebackType | None, ) -> None: self.stop() def start(self): # Create new process for clean termination self._server_process = subprocess.Popen( self.server_cmd, start_new_session=True, stdout=None if self.show_stdout else subprocess.DEVNULL, # Need `VLLM_SERVER_DEV_MODE=1` for `_reset_caches` env=os.environ | {"VLLM_SERVER_DEV_MODE": "1"}, ) def stop(self): server_process = self._server_process if server_process.poll() is None: # In case only some processes have been terminated with contextlib.suppress(ProcessLookupError): # We need to kill both API Server and Engine processes os.killpg(os.getpgid(server_process.pid), signal.SIGKILL) def run_subcommand(self, cmd: list[str]): return subprocess.run( cmd, stdout=None if self.show_stdout else subprocess.DEVNULL, check=True, ) def after_bench(self) -> None: if not self.after_bench_cmd: self.reset_caches() return self.run_subcommand(self.after_bench_cmd) def _get_vllm_server_address(self) -> str: server_cmd = self.server_cmd for host_key in ("--host",): if host_key in server_cmd: host = server_cmd[server_cmd.index(host_key) + 1] break else: host = "localhost" for port_key in ("-p", "--port"): if port_key in server_cmd: port = int(server_cmd[server_cmd.index(port_key) + 1]) break else: port = 8000 # The default value in vllm serve return f"http://{host}:{port}" def is_server_ready(self) -> bool: server_address = self._get_vllm_server_address() try: response = requests.get(f"{server_address}/health") return response.status_code == 200 except requests.RequestException: return False def wait_until_ready(self, timeout: int) -> None: start_time = time.monotonic() while not self.is_server_ready(): # Check if server process has crashed if self._server_process.poll() is not None: returncode = self._server_process.returncode raise RuntimeError( f"Server process crashed with return code {returncode}" ) if time.monotonic() - start_time > timeout: raise TimeoutError( f"Server failed to become ready within {timeout} seconds." ) time.sleep(1) def reset_caches(self) -> None: server_cmd = self.server_cmd # Use `.endswith()` to match `/bin/...` if server_cmd[0].endswith("vllm"): server_address = self._get_vllm_server_address() print(f"Resetting caches at {server_address}") for endpoint in self.VLLM_RESET_CACHE_ENDPOINTS: res = requests.post(server_address + endpoint) res.raise_for_status() elif server_cmd[0].endswith("infinity_emb"): if "--vector-disk-cache" in server_cmd: raise NotImplementedError( "Infinity server uses caching but does not expose a method " "to reset the cache" ) else: raise NotImplementedError( f"No implementation of `reset_caches` for `{server_cmd[0]}` server. " "Please specify a custom command via `--after-bench-cmd`." )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/benchmarks/sweep/server.py", "license": "Apache License 2.0", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/v1/kv_connector/unit/test_decode_bench_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Unit tests for DecodeBenchConnector. Tests the functionality of the DecodeBenchConnector which fills KV cache with dummy values for decode performance benchmarking. """ import pytest import torch from vllm import SamplingParams from vllm.config import KVTransferConfig from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorRole # ruff: noqa: E501 from vllm.distributed.kv_transfer.kv_connector.v1.decode_bench_connector import ( DecodeBenchConnector, DecodeBenchConnectorMetadata, ) from vllm.forward_context import ForwardContext from vllm.utils.hashing import sha256 from vllm.v1.core.kv_cache_utils import get_request_block_hasher, init_none_hash from vllm.v1.core.sched.scheduler import Scheduler from vllm.v1.request import Request from .utils import ( EOS_TOKEN_ID, create_model_runner_output, create_scheduler, create_vllm_config, ) class DecodeBenchTestRunner: """Test runner for DecodeBenchConnector.""" def __init__(self, block_size: int, num_gpu_blocks: int): self.block_size = block_size self.num_gpu_blocks = num_gpu_blocks self.req_id = -1 # Create vllm config with DecodeBenchConnector vllm_config = create_vllm_config( block_size=block_size, max_num_batched_tokens=1000 ) vllm_config.kv_transfer_config = KVTransferConfig( kv_connector="DecodeBenchConnector", kv_role="kv_both", ) self.vllm_config = vllm_config self.scheduler: Scheduler = create_scheduler( vllm_config, num_blocks=num_gpu_blocks ) # Create worker-side connector self.worker_connector = DecodeBenchConnector( vllm_config, KVConnectorRole.WORKER ) # Create dummy KV caches for testing # Shape: [num_blocks, 2, num_heads, block_size, head_dim] # Using simplified shape for testing num_heads = 4 head_dim = 64 self.kv_caches = { f"layer_{i}": torch.zeros( num_gpu_blocks, 2, num_heads, block_size, head_dim ) for i in range(2) # 2 layers for testing } # Register KV caches with worker connector self.worker_connector.register_kv_caches(self.kv_caches) # Extract scheduler-side connector scheduler_connector = self.scheduler.connector assert scheduler_connector is not None assert isinstance(scheduler_connector, DecodeBenchConnector) self.scheduler_connector: DecodeBenchConnector = scheduler_connector init_none_hash(sha256) self._block_hasher = get_request_block_hasher(block_size, sha256) self._dummy_ctx: ForwardContext = ForwardContext( no_compile_layers={}, attn_metadata={}, virtual_engine=0, slot_mapping={} ) def new_request(self, token_ids: list[int]) -> Request: """Create a new request with given token IDs.""" self.req_id += 1 sampling_params = SamplingParams(max_tokens=100) sampling_params.update_from_generation_config({}, EOS_TOKEN_ID) req = Request( request_id=str(self.req_id), prompt_token_ids=token_ids, sampling_params=sampling_params, pooling_params=None, block_hasher=self._block_hasher, ) self.scheduler.add_request(req) return req def run_single_step(self, token_id: int = 0): """Run a single scheduler + worker step.""" scheduler_output = self.scheduler.schedule() # Get connector metadata kv_connector_metadata = scheduler_output.kv_connector_metadata assert kv_connector_metadata is not None assert isinstance(kv_connector_metadata, DecodeBenchConnectorMetadata) # Bind metadata and load KV self.worker_connector.bind_connector_metadata(kv_connector_metadata) self.worker_connector.start_load_kv(self._dummy_ctx) if scheduler_output.total_num_scheduled_tokens > 0: self.worker_connector.wait_for_save() self.worker_connector.clear_connector_metadata() # Create model runner output model_runner_output = create_model_runner_output( reqs=self.scheduler.running, token_id=token_id, ) self.scheduler.update_from_output(scheduler_output, model_runner_output) return scheduler_output, kv_connector_metadata def test_decode_bench_connector_basic(): """Test basic functionality of DecodeBenchConnector.""" block_size = 16 num_gpu_blocks = 100 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create a request with multiple blocks worth of tokens num_tokens = block_size * 3 # 3 blocks token_ids = [1] * num_tokens req = runner.new_request(token_ids) # Run first step - should fill KV cache with dummy values scheduler_output, metadata = runner.run_single_step() # Check that get_num_new_matched_tokens returned correct value # Should be num_tokens - 1 (all except the last token for decode) expected_fill_tokens = num_tokens - 1 # Check metadata has the request to fill assert len(metadata.reqs_to_fill) == 1 assert req.request_id in metadata.reqs_to_fill block_ids_per_group, num_tokens_to_fill = metadata.reqs_to_fill[req.request_id] assert num_tokens_to_fill == expected_fill_tokens # For standard attention, there's only one group assert len(block_ids_per_group) == 1 block_ids = block_ids_per_group[0] # Calculate expected number of blocks expected_num_blocks = (expected_fill_tokens + block_size - 1) // block_size assert len(block_ids) == expected_num_blocks # Verify KV caches were filled with constant value for layer_name, kv_cache in runner.kv_caches.items(): for block_id in block_ids: # Check that the block was filled block_data = kv_cache[block_id] # Should be filled with constant value 0.015 assert torch.allclose(block_data, torch.tensor(0.015)) def test_decode_bench_connector_no_refill(): """Test that DecodeBenchConnector only fills once per request.""" block_size = 16 num_gpu_blocks = 100 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create a request num_tokens = block_size * 2 token_ids = [1] * num_tokens runner.new_request(token_ids) # Run first step - should fill KV cache _, metadata1 = runner.run_single_step() assert len(metadata1.reqs_to_fill) == 1 # Run second step - should NOT fill again (already filled) _, metadata2 = runner.run_single_step() assert len(metadata2.reqs_to_fill) == 0 def test_decode_bench_connector_single_token(): """Test DecodeBenchConnector with single token request.""" block_size = 16 num_gpu_blocks = 100 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create a request with just 1 token # Should not fill anything (need at least 2 tokens: 1 to fill, 1 to decode) token_ids = [1] runner.new_request(token_ids) # Run step - should NOT fill KV cache _, metadata = runner.run_single_step() assert len(metadata.reqs_to_fill) == 0 def test_decode_bench_connector_two_tokens(): """Test DecodeBenchConnector with two token request.""" block_size = 16 num_gpu_blocks = 100 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create a request with 2 tokens # Should fill 1 token (first token), decode the second token_ids = [1, 2] req = runner.new_request(token_ids) # Run step _, metadata = runner.run_single_step() assert len(metadata.reqs_to_fill) == 1 assert req.request_id in metadata.reqs_to_fill block_ids_per_group, num_tokens_to_fill = metadata.reqs_to_fill[req.request_id] assert num_tokens_to_fill == 1 # For standard attention, there's only one group assert len(block_ids_per_group) == 1 assert len(block_ids_per_group[0]) == 1 # 1 token needs 1 block def test_decode_bench_connector_large_context(): """Test DecodeBenchConnector with large context size.""" block_size = 16 num_gpu_blocks = 1000 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create a request with many blocks num_blocks = 20 num_tokens = block_size * num_blocks token_ids = list(range(num_tokens)) req = runner.new_request(token_ids) # Run step _, metadata = runner.run_single_step() assert len(metadata.reqs_to_fill) == 1 assert req.request_id in metadata.reqs_to_fill block_ids_per_group, num_tokens_to_fill = metadata.reqs_to_fill[req.request_id] # Should fill all tokens except the last one expected_fill_tokens = num_tokens - 1 assert num_tokens_to_fill == expected_fill_tokens # For standard attention, there's only one group assert len(block_ids_per_group) == 1 block_ids = block_ids_per_group[0] # Calculate expected number of blocks expected_num_blocks = (expected_fill_tokens + block_size - 1) // block_size assert len(block_ids) == expected_num_blocks # Verify blocks were filled for layer_name, kv_cache in runner.kv_caches.items(): for block_id in block_ids: block_data = kv_cache[block_id] assert torch.allclose(block_data, torch.tensor(0.015)) def test_decode_bench_connector_multiple_requests(): """Test DecodeBenchConnector with multiple sequential requests.""" block_size = 16 num_gpu_blocks = 100 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # First request req1 = runner.new_request([1] * (block_size * 2)) _, metadata1 = runner.run_single_step() assert len(metadata1.reqs_to_fill) == 1 assert req1.request_id in metadata1.reqs_to_fill # Complete first request while runner.scheduler.running: runner.run_single_step() # Add EOS to finish scheduler_output = runner.scheduler.schedule() model_runner_output = create_model_runner_output( reqs=runner.scheduler.running, token_id=EOS_TOKEN_ID, use_eos=True, ) runner.scheduler.update_from_output(scheduler_output, model_runner_output) # Second request - should also get filled req2 = runner.new_request([2] * (block_size * 3)) _, metadata2 = runner.run_single_step() assert len(metadata2.reqs_to_fill) == 1 assert req2.request_id in metadata2.reqs_to_fill # Different request should have different metadata _, num_tokens1 = metadata1.reqs_to_fill[req1.request_id] _, num_tokens2 = metadata2.reqs_to_fill[req2.request_id] assert num_tokens1 == block_size * 2 - 1 assert num_tokens2 == block_size * 3 - 1 def test_decode_bench_connector_partial_block(): """Test DecodeBenchConnector with partial block filling.""" block_size = 16 num_gpu_blocks = 100 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create a request that doesn't align to block boundaries # e.g., 2.5 blocks worth of tokens num_tokens = block_size * 2 + block_size // 2 token_ids = [1] * num_tokens req = runner.new_request(token_ids) # Run step _, metadata = runner.run_single_step() assert len(metadata.reqs_to_fill) == 1 assert req.request_id in metadata.reqs_to_fill block_ids_per_group, num_tokens_to_fill = metadata.reqs_to_fill[req.request_id] # Should fill all tokens except the last one expected_fill_tokens = num_tokens - 1 assert num_tokens_to_fill == expected_fill_tokens # For standard attention, there's only one group assert len(block_ids_per_group) == 1 block_ids = block_ids_per_group[0] # Should allocate 3 blocks to hold the partial data expected_num_blocks = 3 assert len(block_ids) == expected_num_blocks def test_decode_bench_connector_concurrent_requests(): """Test DecodeBenchConnector with multiple concurrent requests in the same batch.""" block_size = 16 num_gpu_blocks = 1000 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create multiple requests that will be batched together req1 = runner.new_request([1] * (block_size * 2)) req2 = runner.new_request([2] * (block_size * 3)) req3 = runner.new_request([3] * (block_size * 1)) # Run first step - all requests should be filled concurrently _, metadata = runner.run_single_step() # All three requests should be in the metadata assert len(metadata.reqs_to_fill) == 3 assert req1.request_id in metadata.reqs_to_fill assert req2.request_id in metadata.reqs_to_fill assert req3.request_id in metadata.reqs_to_fill # Verify each request has correct fill info block_ids_per_group1, num_tokens1 = metadata.reqs_to_fill[req1.request_id] block_ids_per_group2, num_tokens2 = metadata.reqs_to_fill[req2.request_id] block_ids_per_group3, num_tokens3 = metadata.reqs_to_fill[req3.request_id] # Verify token counts (all tokens except last one) assert num_tokens1 == block_size * 2 - 1 assert num_tokens2 == block_size * 3 - 1 assert num_tokens3 == block_size * 1 - 1 # Verify block counts for each request assert len(block_ids_per_group1[0]) == 2 # 2 blocks assert len(block_ids_per_group2[0]) == 3 # 3 blocks assert len(block_ids_per_group3[0]) == 1 # 1 block # Verify all blocks are filled in KV cache for req_id, (block_ids_per_group, _) in metadata.reqs_to_fill.items(): block_ids = block_ids_per_group[0] for layer_name, kv_cache in runner.kv_caches.items(): for block_id in block_ids: block_data = kv_cache[block_id] assert torch.allclose(block_data, torch.tensor(0.015)) # Run second step - should NOT fill again (already filled) _, metadata2 = runner.run_single_step() assert len(metadata2.reqs_to_fill) == 0 if __name__ == "__main__": pytest.main([__file__, "-v"])
{ "repo_id": "vllm-project/vllm", "file_path": "tests/v1/kv_connector/unit/test_decode_bench_connector.py", "license": "Apache License 2.0", "lines": 308, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ DecodeBenchConnector: A KV Connector for decode instance performance testing. This connector emulates a prefill-decode disaggregated setting by filling the KV cache with dummy values, allowing measurement of decoder performance under larger input sequence lengths (ISL) in resource-limited environments. Usage: To use this connector for benchmarking, configure it in the kv_transfer_config: Example: vllm serve <model> --kv-transfer-config '{ "kv_connector": "DecodeBenchConnector", "kv_role": "kv_both", "kv_connector_extra_config": { "fill_mean": 0.015, "fill_std": 0.0 } }' Then run your benchmark with desired input/output lengths: vllm bench serve --base-url http://127.0.0.1:8000 --model <model> \\ --dataset-name random --random-input-len 40000 \\ --random-output-len 100 --max-concurrency 10 Configuration options (via kv_connector_extra_config): - fill_mean (float): Mean value for random normal fill (default: 0.015) - fill_std (float): Standard deviation for random fill (default: 0.0) Set to 0 for constant values, >0 for random sampling """ from dataclasses import dataclass from typing import TYPE_CHECKING, Any import torch from vllm.distributed.kv_transfer.kv_connector.v1 import ( KVConnectorBase_V1, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorMetadata from vllm.logger import init_logger from vllm.utils.math_utils import cdiv from vllm.v1.attention.backend import AttentionMetadata if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request logger = init_logger(__name__) @dataclass class DecodeBenchConnectorMetadata(KVConnectorMetadata): """Metadata for DecodeBenchConnector. Contains information about which requests need their KV cache filled with dummy values for benchmarking purposes. """ # request_id -> (block_ids_per_group, num_tokens_to_fill) # block_ids_per_group is a tuple of lists, one per KV cache group # For standard attention: single group, e.g., ([1, 2, 3],) # For MLA: multiple groups, e.g., ([1, 2], [1, 2]) reqs_to_fill: dict[str, tuple[tuple[list[int], ...], int]] class DecodeBenchConnector(KVConnectorBase_V1): """ A KV Connector for decode instance performance testing. This connector fills the KV cache with dummy (non-zero) values to emulate a prefill-decode disaggregated setting, enabling performance testing of the decoder with larger input sequence lengths. """ def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: "KVCacheConfig | None" = None, ): super().__init__(vllm_config, role, kv_cache_config) self.connector_scheduler: DecodeBenchConnectorScheduler | None = None self.connector_worker: DecodeBenchConnectorWorker | None = None if role == KVConnectorRole.SCHEDULER: self.connector_scheduler = DecodeBenchConnectorScheduler(vllm_config) elif role == KVConnectorRole.WORKER: self.connector_worker = DecodeBenchConnectorWorker(vllm_config) # ============================== # Worker-side methods # ============================== def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): assert self.connector_worker is not None self.connector_worker.register_kv_caches(kv_caches) def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: assert self.connector_worker is not None assert isinstance(self._connector_metadata, DecodeBenchConnectorMetadata) self.connector_worker.start_fill_kv(self._connector_metadata) def wait_for_layer_load(self, layer_name: str) -> None: # All operations are synchronous, so nothing to wait for pass def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs: Any, ) -> None: # This connector doesn't save KV cache (benchmarking only) pass def wait_for_save(self): # This connector doesn't save KV cache (benchmarking only) pass # ============================== # Scheduler-side methods # ============================== def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int | None, bool]: assert self.connector_scheduler is not None return self.connector_scheduler.get_num_new_matched_tokens( request, num_computed_tokens ) def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): assert self.connector_scheduler is not None return self.connector_scheduler.update_state_after_alloc( request, blocks, num_external_tokens ) def build_connector_meta( self, scheduler_output: "SchedulerOutput" ) -> KVConnectorMetadata: assert self.connector_scheduler is not None return self.connector_scheduler.build_connector_meta(scheduler_output) def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: assert self.connector_scheduler is not None self.connector_scheduler.request_finished(request) return False, None class DecodeBenchConnectorScheduler: """Scheduler-side implementation for DecodeBenchConnector.""" def __init__(self, vllm_config: "VllmConfig"): self.vllm_config = vllm_config self.block_size = vllm_config.cache_config.block_size # Track which requests have already been filled self._filled_requests: set[str] = set() # Track pending fills for the current scheduler step # request_id -> (block_ids_per_group, num_tokens_to_fill) # Note: _pending_fills doesn't need explicit cleanup - it's cleared # after build_connector_meta() is called in the same scheduler step self._pending_fills: dict[str, tuple[tuple[list[int], ...], int]] = {} def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int, bool]: """ For new requests, return the number of tokens that should be filled with dummy KV cache values. Returns: (num_tokens_to_fill, is_async) - num_tokens_to_fill: number of uncomputed tokens minus 1 (we fill everything except the last token for decode) - is_async: False (synchronous filling) """ req_id = request.request_id # Only fill once per request on first scheduling if req_id in self._filled_requests: return 0, False # Calculate how many tokens we need to fill # Fill all uncomputed tokens except the last one (which will be decoded) # This simulates having processed a long prefill num_uncomputed_tokens = request.num_tokens - num_computed_tokens num_tokens_to_fill = max(0, num_uncomputed_tokens - 1) if num_tokens_to_fill == 0: return 0, False # Return False for synchronous operation - the fill is fast enough # that async overhead isn't worth it return num_tokens_to_fill, False def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): """ Called after blocks are allocated. Store the block IDs so we can fill them with dummy values. Supports both standard attention (single KV cache group) and MLA (multiple KV cache groups). """ req_id = request.request_id if num_external_tokens == 0: return # Get the block IDs that were allocated # block_groups is a tuple of lists, one per KV cache group # For standard attention: 1 group # For MLA: multiple groups (one per attention type) block_groups = blocks.get_block_ids() # Calculate how many blocks we need to fill # num_external_tokens are the tokens we said we'd provide num_blocks_to_fill = cdiv(num_external_tokens, self.block_size) # Extract the first num_blocks_to_fill blocks from each group # All groups should have the same block IDs for the same request block_ids_per_group = tuple( group_blocks[:num_blocks_to_fill] for group_blocks in block_groups ) # Store the blocks to fill for all group. _pending_fills doesn't need cleanup # as it's cleared after build_connector_meta self._pending_fills[req_id] = ( block_ids_per_group, num_external_tokens, ) self._filled_requests.add(req_id) logger.debug( "DecodeBenchConnector: Allocated %d blocks across %d KV cache groups " "for request %s", num_blocks_to_fill, len(block_groups), req_id, ) def build_connector_meta( self, scheduler_output: "SchedulerOutput" ) -> KVConnectorMetadata: """ Build metadata containing information about which blocks to fill with dummy KV values. """ meta = DecodeBenchConnectorMetadata(reqs_to_fill=self._pending_fills.copy()) # Clear pending fills after building metadata self._pending_fills.clear() return meta def request_finished(self, request: "Request"): """ Called when a request has finished. Clean up any state. """ self._filled_requests.discard(request.request_id) class DecodeBenchConnectorWorker: """Worker-side implementation for DecodeBenchConnector.""" def __init__(self, vllm_config: "VllmConfig"): self.vllm_config = vllm_config self.block_size = vllm_config.cache_config.block_size # Get fill parameters from extra config kv_transfer_config = vllm_config.kv_transfer_config assert kv_transfer_config is not None self.fill_mean = kv_transfer_config.get_from_extra_config("fill_mean", 0.015) self.fill_std = kv_transfer_config.get_from_extra_config("fill_std", 0.0) # Will be populated via register_kv_caches self.kv_caches: dict[str, torch.Tensor] | None = None # Mapping from KV cache group index to list of layer names in that group self.group_to_layers: dict[int, list[str]] | None = None def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): """Store references to the KV cache tensors and build group mapping.""" self.kv_caches = kv_caches # For simplicity, assume all layers belong to group 0 (standard attention) # For MLA models with multiple groups, the metadata will handle the mapping # We just need to fill the blocks specified in the metadata self.group_to_layers = {0: list(kv_caches.keys())} logger.debug( "DecodeBenchConnector: Registered %d KV cache layers", len(kv_caches), ) def start_fill_kv(self, metadata: DecodeBenchConnectorMetadata): """ Fill the allocated KV cache blocks with dummy (non-zero) values. This simulates having a populated KV cache from a prefill phase, allowing decode performance testing with larger context sizes. Supports both standard attention (single group) and MLA (multiple groups). """ if not metadata.reqs_to_fill: return assert self.kv_caches is not None, "KV caches must be registered before filling" assert self.group_to_layers is not None, "Group mapping must be initialized" for req_id, (block_ids_per_group, num_tokens) in metadata.reqs_to_fill.items(): # Fill blocks for each KV cache group for group_idx, block_ids in enumerate(block_ids_per_group): self._fill_blocks(group_idx, block_ids, num_tokens) logger.debug( "DecodeBenchConnector: Filled %d blocks (%d tokens) across %d groups " "for request %s", len(block_ids_per_group[0]) if block_ids_per_group else 0, num_tokens, len(block_ids_per_group), req_id, ) def _fill_blocks(self, group_idx: int, block_ids: list[int], num_tokens: int): """ Fill specified blocks with dummy non-zero values for a specific KV cache group. Args: group_idx: The KV cache group index to fill block_ids: List of block IDs to fill in this group num_tokens: Total number of tokens to fill across these blocks """ if not block_ids: return assert self.kv_caches is not None assert self.group_to_layers is not None # Get the layers that belong to this group layer_names = self.group_to_layers.get(group_idx, []) # Fill only the layers in this group for layer_name in layer_names: if layer_name not in self.kv_caches: logger.warning( "DecodeBenchConnector: Layer %s not found in KV caches", layer_name ) continue kv_cache = self.kv_caches[layer_name] # Convert block_ids to tensor on device block_ids_tensor = torch.tensor( block_ids, dtype=torch.long, device=kv_cache.device ) # Filter invalid block IDs valid_mask = block_ids_tensor < kv_cache.shape[0] valid_block_ids = block_ids_tensor[valid_mask] if len(valid_block_ids) == 0: continue # Create fill values - either constant or random block_shape = kv_cache.shape[1:] if self.fill_std > 0: # Random normal sampling fill_values = torch.normal( mean=self.fill_mean, std=self.fill_std, size=(len(valid_block_ids),) + block_shape, dtype=kv_cache.dtype, device=kv_cache.device, ) else: # Constant fill value fill_values = torch.full( (len(valid_block_ids),) + block_shape, self.fill_mean, dtype=kv_cache.dtype, device=kv_cache.device, ) # Batch fill operation kv_cache[valid_block_ids] = fill_values logger.debug( "DecodeBenchConnector: Filled %d blocks in group %d with %s values " "(mean=%.3f, std=%.3f)", len(block_ids), group_idx, "random" if self.fill_std > 0 else "constant", self.fill_mean, self.fill_std, )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py", "license": "Apache License 2.0", "lines": 338, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/utils/nccl.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import importlib.util import os import torch import vllm.envs as envs from vllm.logger import init_logger logger = init_logger(__name__) def find_nccl_library() -> str: """Return NCCL/RCCL shared library name to load. Uses `VLLM_NCCL_SO_PATH` if set; otherwise chooses by torch backend. """ so_file = envs.VLLM_NCCL_SO_PATH if so_file: logger.info( "Found nccl from environment variable VLLM_NCCL_SO_PATH=%s", so_file ) else: if torch.version.cuda is not None: so_file = "libnccl.so.2" elif torch.version.hip is not None: so_file = "librccl.so.1" else: raise ValueError("NCCL only supports CUDA and ROCm backends.") logger.debug_once("Found nccl from library %s", so_file) return so_file def find_nccl_include_paths() -> list[str] | None: """Return possible include paths containing `nccl.h`. Considers `VLLM_NCCL_INCLUDE_PATH` and the `nvidia-nccl-cuXX` package. """ paths: list[str] = [] inc = envs.VLLM_NCCL_INCLUDE_PATH if inc and os.path.isdir(inc): paths.append(inc) try: spec = importlib.util.find_spec("nvidia.nccl") if spec and (locs := getattr(spec, "submodule_search_locations", None)): for loc in locs: inc_dir = os.path.join(loc, "include") if os.path.exists(os.path.join(inc_dir, "nccl.h")): paths.append(inc_dir) except Exception as e: logger.debug("Failed to find nccl include path from nvidia.nccl package: %s", e) seen: set[str] = set() out: list[str] = [] for p in paths: if p and p not in seen: out.append(p) seen.add(p) return out or None
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/nccl.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/config/test_multimodal_config.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.config.model import ModelConfig from vllm.config.multimodal import MultiModalConfig from vllm.v1.attention.backends.registry import AttentionBackendEnum 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 def test_language_model_only_does_not_affect_mm_hash(): """language_model_only does not affect the ViT computation graph, so it should not change the multimodal config hash.""" base_hash = MultiModalConfig().compute_hash() lm_only_hash = MultiModalConfig(language_model_only=True).compute_hash() assert base_hash == lm_only_hash def test_language_model_only_affects_model_hash(): """language_model_only affects the LM computation graph, so it should change the model config hash.""" model = "llava-hf/llava-1.5-7b-hf" base_hash = ModelConfig(model).compute_hash() lm_only_hash = ModelConfig(model, language_model_only=True).compute_hash() assert base_hash != lm_only_hash
{ "repo_id": "vllm-project/vllm", "file_path": "tests/config/test_multimodal_config.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm: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)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/lora/test_deepseekv2_tp.py", "license": "Apache License 2.0", "lines": 86, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm: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) if topk_ids.numel() < num_experts: max_num_tokens_padded = topk_ids.numel() * 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__])
{ "repo_id": "vllm-project/vllm", "file_path": "tests/lora/test_moe_lora_align_sum.py", "license": "Apache License 2.0", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/lora/test_olmoe_tp.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import shutil import pytest import torch from safetensors.torch import load_file, save_file 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]) def test_olmoe_lora_mixed_random(olmoe_lora_files, tmp_path): # Create a dummy LoRA with random weights based on the real one random_lora_path = tmp_path / "random_lora" shutil.copytree(olmoe_lora_files, random_lora_path) weights_path = random_lora_path / "adapter_model.safetensors" weights = load_file(str(weights_path)) random_weights = {k: torch.randn_like(v) for k, v in weights.items()} save_file(random_weights, str(weights_path)) 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, ) prompts = [ PROMPT_TEMPLATE.format(context="How many candidates are there?"), PROMPT_TEMPLATE.format(context="Count the number of candidates."), ] lora_requests = [ LoRARequest("real", 1, olmoe_lora_files), LoRARequest("random", 2, str(random_lora_path)), ] sampling_params = vllm.SamplingParams(temperature=0, max_tokens=64) outputs = llm.generate(prompts, sampling_params, lora_request=lora_requests) assert outputs[0].outputs[0].text.strip().startswith(EXPECTED_LORA_OUTPUT[0]) @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 )
{ "repo_id": "vllm-project/vllm", "file_path": "tests/lora/test_olmoe_tp.py", "license": "Apache License 2.0", "lines": 165, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm: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)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/lora/test_qwen3moe_tp.py", "license": "Apache License 2.0", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/lora/layers/fused_moe.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import functools import torch import torch.nn as nn from transformers import PretrainedConfig from vllm import envs from vllm.config.lora import LoRAConfig from vllm.distributed.parallel_state import ( get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size, ) from vllm.distributed.utils import divide from vllm.lora.layers.base import BaseLayerWithLoRA from vllm.lora.ops.triton_ops.utils import get_lora_op_configs from vllm.model_executor.layers.fused_moe import FusedMoE from vllm.model_executor.layers.fused_moe.config import ( _get_config_dtype_str, ) from vllm.model_executor.layers.fused_moe.fused_marlin_moe import ( MarlinExperts, ) from vllm.model_executor.layers.fused_moe.fused_moe import ( TritonExperts, ) from vllm.model_executor.layers.fused_moe.fused_moe_modular_method import ( FusedMoEModularMethod, ) from vllm.model_executor.layers.fused_moe.gpt_oss_triton_kernels_moe import ( UnfusedOAITritonExperts, ) from vllm.model_executor.layers.fused_moe.modular_kernel import ( FusedMoEModularKernel, ) from vllm.model_executor.layers.fused_moe.prepare_finalize import ( MoEPrepareAndFinalizeNoEP, ) from .utils import _get_lora_device, try_get_optimal_moe_lora_config class FusedMoEWithLoRA(BaseLayerWithLoRA): def __init__(self, base_layer: FusedMoE) -> None: super().__init__() self.base_layer = base_layer assert not self.base_layer.use_ep, ( "EP support for Fused MoE LoRA is not implemented yet." ) self.tp_size = get_tensor_model_parallel_world_size() self.tp_rank = get_tensor_model_parallel_rank() self.device = _get_lora_device(base_layer) # For non-gated MoE (is_act_and_mul=False), only 1 slice is needed # since there's only up_proj (w1), not gate_proj + up_proj (w1 + w3) self._w13_slices = 2 if base_layer.moe_config.is_act_and_mul else 1 self._inject_lora_into_fused_moe() def _normalize_keys(self, config: dict[str, int | None]) -> dict[str, int | None]: normalized_config = {} for key, value in config.items(): if key.islower(): if key.startswith("block_"): normalized_key = "BLOCK_SIZE_" + key.split("_")[-1].upper() else: normalized_key = key.upper() else: normalized_key = key normalized_config[normalized_key] = value return normalized_config def _get_lora_moe_configs( self, op_prefix: str, num_loras: int, rank: int, num_slices: int, M: int, layer: FusedMoE, top_k: int, config_dtype: str, ): if envs.VLLM_TUNED_CONFIG_FOLDER: hidden_size = layer.hidden_size intermediate_size = ( self.w2_lora_a_stacked[0].shape[-1] if op_prefix == "w2" else self.w13_lora_b_stacked[0].shape[-2] ) shrink_config = get_lora_op_configs( op_type=f"fused_moe_lora_{op_prefix}_shrink", max_loras=num_loras, batch=M, hidden_size=hidden_size, rank=rank, num_slices=num_slices, moe_intermediate_size=intermediate_size, ) expand_config = get_lora_op_configs( op_type=f"fused_moe_lora_{op_prefix}_expand", max_loras=num_loras, batch=M, hidden_size=hidden_size, # lora_a_stacked.shape[-1], rank=rank, num_slices=num_slices, moe_intermediate_size=intermediate_size, # lora_b_stacked.shape[-2], ) else: # fall back to the default config get_config_func = functools.partial( try_get_optimal_moe_lora_config, w1_shape=layer.w13_weight.size(), w2_shape=layer.w2_weight.size(), rank=rank, top_k=top_k, dtype=config_dtype, M=M, block_shape=layer.quant_method.moe_quant_config.block_shape, ) shrink_config = get_config_func( op_type=f"fused_moe_lora_{op_prefix}_shrink" ) expand_config = get_config_func( op_type=f"fused_moe_lora_{op_prefix}_expand" ) shrink_config = self._normalize_keys(shrink_config) expand_config = self._normalize_keys(expand_config) return shrink_config, expand_config def _inject_lora_into_fused_moe(self): moe_state_dict = {} top_k = self.base_layer.top_k self.base_layer.ensure_moe_quant_config_init() quant_config = self.base_layer.quant_method.moe_quant_config if getattr(self.base_layer.quant_method, "supports_internal_mk", False): # Use the existing modular kernel from the quant method m_fused_moe_fn = self.base_layer.quant_method.moe_mk # Don't let the kernel own shared experts so the runner can # overlap them with routed experts via a separate CUDA stream. m_fused_moe_fn.shared_experts = None else: # Create a new modular kernel via select_gemm_impl. # Don't pass shared_experts to the kernel so the runner can # overlap them with routed experts via a separate CUDA stream. prepare_finalize = MoEPrepareAndFinalizeNoEP() m_fused_moe_fn = FusedMoEModularKernel( prepare_finalize, self.base_layer.quant_method.select_gemm_impl( prepare_finalize, self.base_layer ), ) if quant_config.use_mxfp4_w4a16: assert isinstance( m_fused_moe_fn.fused_experts, (MarlinExperts, UnfusedOAITritonExperts) ) else: assert isinstance(m_fused_moe_fn.fused_experts, TritonExperts) def fwd_decorator(layer, func): def wrapper(*args, **kwargs): moe_state_dict["hidden_states"] = kwargs["hidden_states"] moe_state_dict["topk_ids"] = kwargs["topk_ids"] moe_state_dict["topk_weights"] = kwargs["topk_weights"] moe_state_dict["expert_map"] = kwargs["expert_map"] moe_state_dict["apply_router_weight_on_input"] = kwargs[ "apply_router_weight_on_input" ] result = func(*args, **kwargs) return result return wrapper def act_decorator(layer, func): def wrapper(*args, **kwargs): _, output, input = args hidden_states = moe_state_dict["hidden_states"] topk_weights = moe_state_dict["topk_weights"] curr_topk_ids = moe_state_dict["topk_ids"] expert_map = moe_state_dict["expert_map"] config_dtype = _get_config_dtype_str( dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False, ) CHUNK_SIZE = envs.VLLM_FUSED_MOE_CHUNK_SIZE num_tokens = hidden_states.size(0) M = min(num_tokens, CHUNK_SIZE) max_lora_rank = self.w13_lora_a_stacked[0].shape[-2] shrink_config, expand_config = self._get_lora_moe_configs( op_prefix="w13", num_loras=self.max_loras, rank=max_lora_rank, num_slices=self._w13_slices, M=M, layer=layer, top_k=top_k, config_dtype=config_dtype, ) # SPARSITY_FACTOR is a heuristic margin ensuring tokens * top_k # activates only a small fraction of total experts * loras. SPARSITY_FACTOR = 8 naive_block_assignment = ( expert_map is None and num_tokens * top_k * SPARSITY_FACTOR <= self.base_layer.local_num_experts * self.max_loras ) # get the block size of m from customized config or default config ( token_lora_mapping, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora, ) = self.punica_wrapper.moe_lora_align_block_size( curr_topk_ids, num_tokens, shrink_config["BLOCK_SIZE_M"], self.base_layer.local_num_experts, self.max_loras, self.adapter_enabled, expert_map, naive_block_assignment=naive_block_assignment, ) moe_state_dict["sorted_token_ids_lora"] = sorted_token_ids_lora moe_state_dict["expert_ids_lora"] = expert_ids_lora moe_state_dict["num_tokens_post_padded_lora"] = ( num_tokens_post_padded_lora ) moe_state_dict["token_lora_mapping"] = token_lora_mapping if sorted_token_ids_lora is not None: expert_ids_lora = expert_ids_lora.view(self.max_loras, -1) sorted_token_ids_lora = sorted_token_ids_lora.view( self.max_loras, -1 ) # self.punica_wrapper.add_lora_fused_moe( input.view(-1, top_k, input.shape[-1]), hidden_states, self.w13_lora_a_stacked, self.w13_lora_b_stacked, topk_weights, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora, max_lora_rank, top_k, shrink_config, ## pass the shrink config expand_config, ## pass the expand config self.adapter_enabled, fully_sharded=self.fully_sharded, token_lora_mapping=token_lora_mapping, ) result = func(*args, **kwargs) moe_state_dict["intermediate_cache2"] = output return result return wrapper def moe_sum_decorator(layer, func): def wrapper(*args, **kwargs): hidden_states = moe_state_dict["hidden_states"] topk_weights = moe_state_dict["topk_weights"] config_dtype = _get_config_dtype_str( dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False, ) CHUNK_SIZE = envs.VLLM_FUSED_MOE_CHUNK_SIZE num_tokens = hidden_states.size(0) M = min(num_tokens, CHUNK_SIZE) max_lora_rank = self.w2_lora_a_stacked[0].shape[-2] shrink_config, expand_config = self._get_lora_moe_configs( op_prefix="w2", num_loras=self.max_loras, rank=max_lora_rank, num_slices=1, M=M, layer=layer, top_k=top_k, config_dtype=config_dtype, ) sorted_token_ids_lora = moe_state_dict["sorted_token_ids_lora"] expert_ids_lora = moe_state_dict["expert_ids_lora"] num_tokens_post_padded_lora = moe_state_dict[ "num_tokens_post_padded_lora" ] token_lora_mapping = moe_state_dict.get("token_lora_mapping") if sorted_token_ids_lora is not None: expert_ids_lora = expert_ids_lora.view(self.max_loras, -1) sorted_token_ids_lora = sorted_token_ids_lora.view( self.max_loras, -1 ) intermediate_cache2 = moe_state_dict["intermediate_cache2"] intermediate_cache3 = args[0] shard_size_w2 = divide(self.base_layer.hidden_size, self.tp_size) self.punica_wrapper.add_lora_fused_moe( intermediate_cache3, intermediate_cache2, self.w2_lora_a_stacked, self.w2_lora_b_stacked, topk_weights, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora, max_lora_rank, top_k, shrink_config, ## pass the shrink config expand_config, ## pass the expand config self.adapter_enabled, True, fully_sharded=self.fully_sharded, offset=shard_size_w2 * self.tp_rank if self.fully_sharded else 0, token_lora_mapping=token_lora_mapping, ) result = func(*args, **kwargs) return result return wrapper fused_experts = m_fused_moe_fn.fused_experts m_fused_moe_fn.forward = fwd_decorator(self.base_layer, m_fused_moe_fn.forward) fused_experts.activation = act_decorator( self.base_layer, fused_experts.activation ) fused_experts.moe_sum = moe_sum_decorator( self.base_layer, fused_experts.moe_sum ) # TODO(bnell): find a less intrusive way to handle this. self.base_layer._replace_quant_method( FusedMoEModularMethod(self.base_layer.quant_method, m_fused_moe_fn) ) def _create_lora_a_weights( self, max_loras: int, lora_config: LoRAConfig, ): self.w13_lora_a_stacked: tuple[torch.Tensor, ...] = tuple( torch.zeros( ( max_loras, self.base_layer.local_num_experts, lora_config.max_lora_rank if not self.fully_sharded else divide(lora_config.max_lora_rank, self.tp_size), self.base_layer.hidden_size, ), dtype=lora_config.lora_dtype, device=self.device, ) for _ in range(self._w13_slices) ) self.w2_lora_a_stacked: tuple[torch.Tensor, ...] = ( torch.zeros( ( max_loras, self.base_layer.local_num_experts, lora_config.max_lora_rank, self.base_layer.intermediate_size_per_partition, ), dtype=lora_config.lora_dtype, device=self.device, ), ) def _create_lora_b_weights(self, max_loras: int, lora_config: LoRAConfig): self.w13_lora_b_stacked: tuple[torch.Tensor, ...] = tuple( torch.zeros( ( max_loras, self.base_layer.local_num_experts, self.base_layer.intermediate_size_per_partition, lora_config.max_lora_rank, ), dtype=lora_config.lora_dtype, device=self.device, ) for _ in range(self._w13_slices) ) self.w2_lora_b_stacked: tuple[torch.Tensor, ...] = ( torch.zeros( ( max_loras, self.base_layer.local_num_experts, self.base_layer.hidden_size if not self.fully_sharded else divide(self.base_layer.hidden_size, self.tp_size), lora_config.max_lora_rank, ), dtype=lora_config.lora_dtype, device=self.device, ), ) def create_lora_weights( self, max_loras: int, lora_config: LoRAConfig, model_config: PretrainedConfig | None = None, ) -> None: """Initializes lora matrices.""" self.max_loras = lora_config.max_loras self.fully_sharded = lora_config.fully_sharded_loras self.adapter_enabled = torch.tensor( [0] * (max_loras + 1), dtype=torch.int, device=self.device ) self._create_lora_a_weights(max_loras, lora_config) self._create_lora_b_weights(max_loras, lora_config) # They will be used by 'LoRALayerWeights.create_dummy_lora_weights' # to create a dummy LoRA weights. # TODO Optimize this section self.lora_a_stacked = [] self.lora_b_stacked = [] for lora_id in range(max_loras): for experts_id in range(self.base_layer.local_num_experts): # For gated MoE: gate_proj (w1), down_proj (w2), up_proj (w3) # For non-gated MoE: up_proj (w1), down_proj (w2) self.lora_a_stacked.append( self.w13_lora_a_stacked[0][lora_id][experts_id] ) self.lora_a_stacked.append( self.w2_lora_a_stacked[0][lora_id][experts_id] ) self.lora_b_stacked.append( self.w13_lora_b_stacked[0][lora_id][experts_id] ) self.lora_b_stacked.append( self.w2_lora_b_stacked[0][lora_id][experts_id] ) # Only add w3 (up_proj) for gated MoE (_w13_slices == 2) if self._w13_slices == 2: self.lora_a_stacked.append( self.w13_lora_a_stacked[1][lora_id][experts_id] ) self.lora_b_stacked.append( self.w13_lora_b_stacked[1][lora_id][experts_id] ) def _slice_w13_a(self, w13_lora_a: torch.Tensor) -> torch.Tensor: """ Applies to FusedMoEWithLoRA and FusedMoE3DWithLoRA """ if self.tp_size == 1 or not self.fully_sharded: return w13_lora_a # w13_lora_a shape (num_experts,rank,input_size) current_lora_rank = w13_lora_a.shape[1] assert current_lora_rank % self.tp_size == 0 # Based on S-LoRA, we slice W13/W1/W3 A along the rank dim. shard_size = self.w13_lora_a_stacked[0].shape[2] start_idx = self.tp_rank * shard_size end_idx = (self.tp_rank + 1) * shard_size return w13_lora_a[:, start_idx:end_idx, :] def _slice_w13_b(self, w13_lora_b: torch.Tensor): if self.tp_size == 1: return w13_lora_b # w13_lora_b shape (num_experts,output_size,rank) shard_size = self.base_layer.intermediate_size_per_partition start_idx = self.tp_rank * shard_size end_idx = (self.tp_rank + 1) * shard_size return w13_lora_b[:, start_idx:end_idx, :] def _slice_w2_a(self, w2_lora_a: torch.Tensor) -> torch.Tensor: """ Applies to FusedMoEWithLoRA and FusedMoE3DWithLoRA """ if self.tp_size == 1: return w2_lora_a # w2_lora_a shape (num_experts,rank,input_size) shard_size = self.base_layer.intermediate_size_per_partition start_idx = self.tp_rank * shard_size end_idx = (self.tp_rank + 1) * shard_size return w2_lora_a[:, :, start_idx:end_idx] def _slice_w2_b(self, w2_lora_b: torch.Tensor) -> torch.Tensor: """ Applies to FusedMoEWithLoRA and FusedMoE3DWithLoRA """ if self.tp_size == 1 or not self.fully_sharded: return w2_lora_b # Based on S-LoRA, we slice W2 B along the hidden_size dim. # w2_lora_b shape (num_experts,output_size,rank) shard_size = self.w2_lora_b_stacked[0].shape[2] start_idx = self.tp_rank * shard_size end_idx = (self.tp_rank + 1) * shard_size return w2_lora_b[:, start_idx:end_idx, :] def reset_lora(self, index: int): """Resets the lora weights at index back to 0.""" for pos in range(self._w13_slices): self.w13_lora_a_stacked[pos][index] = 0 self.w13_lora_b_stacked[pos][index] = 0 self.w2_lora_a_stacked[0][index] = 0 self.w2_lora_b_stacked[0][index] = 0 self.adapter_enabled[index] = 0 # def set_lora( self, index: int, lora_a: torch.Tensor | list[torch.Tensor], lora_b: torch.Tensor | list[torch.Tensor], ): """Overwrites lora tensors at index.""" # Make mypy happy assert isinstance(lora_a, list) assert isinstance(lora_b, list) self.reset_lora(index) self.adapter_enabled[index] = 1 num_experts = self.w13_lora_a_stacked[0].shape[1] w1_lora_a, w2_lora_a, w3_lora_a = lora_a w1_lora_b, w2_lora_b, w3_lora_b = lora_b assert ( num_experts == w1_lora_a.shape[0] == w2_lora_a.shape[0] == w3_lora_a.shape[0] ) slliced_w1_lora_a = self._slice_w13_a(w1_lora_a) slliced_w1_lora_b = self._slice_w13_b(w1_lora_b) sliced_w2_lora_a = self._slice_w2_a(w2_lora_a) sliced_w2_lora_b = self._slice_w2_b(w2_lora_b) self.w13_lora_a_stacked[0][ index, :, : slliced_w1_lora_a.shape[1], : slliced_w1_lora_a.shape[2] ].copy_(slliced_w1_lora_a, non_blocking=True) self.w13_lora_b_stacked[0][ index, :, : slliced_w1_lora_b.shape[1], : slliced_w1_lora_b.shape[2] ].copy_(slliced_w1_lora_b, non_blocking=True) # Only copy w3 (up_proj) for gated MoE (_w13_slices == 2) if self._w13_slices == 2: slliced_w3_lora_a = self._slice_w13_a(w3_lora_a) slliced_w3_lora_b = self._slice_w13_b(w3_lora_b) self.w13_lora_a_stacked[1][ index, :, : slliced_w3_lora_a.shape[1], : slliced_w3_lora_a.shape[2] ].copy_(slliced_w3_lora_a, non_blocking=True) self.w13_lora_b_stacked[1][ index, :, : slliced_w3_lora_b.shape[1], : slliced_w3_lora_b.shape[2] ].copy_(slliced_w3_lora_b, non_blocking=True) self.w2_lora_a_stacked[0][ index, :, : sliced_w2_lora_a.shape[1], : sliced_w2_lora_a.shape[2] ].copy_(sliced_w2_lora_a, non_blocking=True) self.w2_lora_b_stacked[0][ index, :, : sliced_w2_lora_b.shape[1], : sliced_w2_lora_b.shape[2] ].copy_(sliced_w2_lora_b, non_blocking=True) def forward(self, *args, **kwargs): return self.base_layer.forward(*args, **kwargs) def maybe_all_reduce_tensor_model_parallel(self, *args, **kwargs): return self.base_layer.maybe_all_reduce_tensor_model_parallel(*args, **kwargs) @property def _shared_experts(self): return self.base_layer._shared_experts @property def quant_method(self): return self.base_layer.quant_method @property def is_internal_router(self) -> bool: return self.base_layer.is_internal_router @classmethod def can_replace_layer( cls, source_layer: nn.Module, lora_config: LoRAConfig, packed_modules_list: list, model_config: PretrainedConfig | None = None, ) -> bool: """Returns True if the layer can be replaced by this LoRA layer.""" # source_layer is FusedMoE or SharedFusedMoE return isinstance(source_layer, FusedMoE) and len(packed_modules_list) == 2 class FusedMoE3DWithLoRA(FusedMoEWithLoRA): def __init__(self, base_layer): super().__init__(base_layer) self._w13_slices = 1 def _create_lora_b_weights(self, max_loras, lora_config): self.w13_lora_b_stacked: tuple[torch.Tensor] = tuple( torch.zeros( ( max_loras, self.base_layer.local_num_experts, self.base_layer.intermediate_size_per_partition * 2, lora_config.max_lora_rank, ), dtype=lora_config.lora_dtype, device=self.device, ) for _ in range(self._w13_slices) ) self.w2_lora_b_stacked: tuple[torch.Tensor] = ( torch.zeros( ( max_loras, self.base_layer.local_num_experts, self.base_layer.hidden_size if not self.fully_sharded else divide(self.base_layer.hidden_size, self.tp_size), lora_config.max_lora_rank, ), dtype=lora_config.lora_dtype, device=self.device, ), ) def create_lora_weights( self, max_loras: int, lora_config: LoRAConfig, model_config: PretrainedConfig | None = None, ) -> None: """Initializes lora matrices.""" assert isinstance(model_config, PretrainedConfig) self._base_model = model_config.architectures[0] self.max_loras = lora_config.max_loras self.fully_sharded = lora_config.fully_sharded_loras self.adapter_enabled = torch.tensor( [0] * (max_loras + 1), dtype=torch.int, device=self.device ) self._create_lora_a_weights(max_loras, lora_config) self._create_lora_b_weights(max_loras, lora_config) def _slice_w13_b(self, w13_lora_b: torch.Tensor): if self.tp_size == 1: return w13_lora_b # w13_lora_b shape (num_experts,output_size,rank) shard_size = self.base_layer.intermediate_size_per_partition start_idx = self.tp_rank * shard_size end_idx = (self.tp_rank + 1) * shard_size # HACK: Currently, only GPT-OSS is in interleaved order if self._base_model == "GptOssForCausalLM": # For models like GPT-OSS, the weights of w1 (gate_proj) and w3 (up_proj) # in the interleaved order, and corresponding LoRA need to be processed. w1_lora_b = w13_lora_b[:, ::2, :] w3_lora_b = w13_lora_b[:, 1::2, :] sliced_w1_lora_b = w1_lora_b[:, start_idx:end_idx, :] sliced_w3_lora_b = w3_lora_b[:, start_idx:end_idx, :] return torch.stack([sliced_w1_lora_b, sliced_w3_lora_b], dim=2).flatten( 1, 2 ) else: slice_size = w13_lora_b.shape[1] // 2 w1_lora_b = w13_lora_b[:, :slice_size, :] w3_lora_b = w13_lora_b[:, slice_size:, :] sliced_w1_lora_b = w1_lora_b[:, start_idx:end_idx, :] sliced_w3_lora_b = w3_lora_b[:, start_idx:end_idx, :] return torch.cat([sliced_w1_lora_b, sliced_w3_lora_b], dim=1) def set_lora( self, index: int, lora_a: torch.Tensor | list[torch.Tensor], lora_b: torch.Tensor | list[torch.Tensor], ): """Overwrites lora tensors at index.""" # Make mypy happy assert isinstance(lora_a, list) assert isinstance(lora_b, list) assert len(lora_a) == len(lora_b) == 2 self.reset_lora(index) self.adapter_enabled[index] = 1 w13_lora_a, w2_lora_a = lora_a w13_lora_b, w2_lora_b = lora_b sliced_w13_lora_a = self._slice_w13_a(w13_lora_a) sliced_w13_lora_b = self._slice_w13_b(w13_lora_b) sliced_w2_lora_a = self._slice_w2_a(w2_lora_a) sliced_w2_lora_b = self._slice_w2_b(w2_lora_b) self.w13_lora_a_stacked[0][ index, :, : sliced_w13_lora_a.shape[1], : sliced_w13_lora_a.shape[2] ].copy_(sliced_w13_lora_a, non_blocking=True) self.w2_lora_a_stacked[0][ index, :, : sliced_w2_lora_a.shape[1], : sliced_w2_lora_a.shape[2] ].copy_(sliced_w2_lora_a, non_blocking=True) self.w13_lora_b_stacked[0][ index, :, : sliced_w13_lora_b.shape[1], : sliced_w13_lora_b.shape[2] ].copy_(sliced_w13_lora_b, non_blocking=True) self.w2_lora_b_stacked[0][ index, :, : sliced_w2_lora_b.shape[1], : sliced_w2_lora_b.shape[2] ].copy_(sliced_w2_lora_b, non_blocking=True) @property def w13_input_size(self): """ Full size """ return self.w13_lora_a_stacked[0].shape[-1] @property def w13_output_size(self): """ Full size """ return self.w13_lora_b_stacked[0].shape[-2] * self.tp_size @property def w2_input_size(self): """ Full size """ return self.w2_lora_a_stacked[0].shape[-1] * self.tp_size @property def w2_output_size(self): """ Full size """ return self.base_layer.hidden_size @classmethod def can_replace_layer( cls, source_layer: nn.Module, lora_config: LoRAConfig, packed_modules_list: list, model_config: PretrainedConfig | None = None, ) -> bool: """Returns True if the layer can be replaced by this LoRA layer.""" # source_layer is FusedMoE or SharedFusedMoE return isinstance(source_layer, FusedMoE) and len(packed_modules_list) == 1
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/lora/layers/fused_moe.py", "license": "Apache License 2.0", "lines": 683, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/lora/ops/triton_ops/fused_moe_lora_op.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm.distributed import ( tensor_model_parallel_all_gather, tensor_model_parallel_all_reduce, ) from vllm.triton_utils import tl, triton from vllm.triton_utils.allocation import set_triton_allocator from vllm.utils.torch_utils import direct_register_custom_op from .utils import supports_pdl, supports_tma @triton.jit def _get_lora_id( lora_ids, token_lora_mapping_ptr, lora_idx, pid_m, top_k_num, naive_block_assignment: tl.constexpr, ): """Returns lora_id""" if naive_block_assignment: token_idx = pid_m // top_k_num return tl.load(token_lora_mapping_ptr + token_idx) else: return tl.load(lora_ids + lora_idx) @triton.jit def _get_expert_id( expert_ids_ptr, lora_id, pid_m, stride_el, max_loras, naive_block_assignment: tl.constexpr, ): """Returns expert_id""" if naive_block_assignment: return tl.load(expert_ids_ptr + pid_m) else: ind = lora_id * stride_el + pid_m return tl.load(expert_ids_ptr + ind, ind < max_loras * stride_el, -1) @triton.jit def _get_token_offs( sorted_token_ids_ptr, lora_id, pid_m, offs, stride_tl, max_loras, num_valid_tokens, naive_block_assignment: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, ): """Returns token offsets""" if naive_block_assignment: return tl.where(offs == 0, pid_m, num_valid_tokens) else: offs_token_id = pid_m * BLOCK_SIZE_M + offs token_ind = stride_tl * lora_id + offs_token_id return tl.load( sorted_token_ids_ptr + token_ind, token_ind < max_loras * stride_tl, 0 ) @triton.jit def _get_c_ptrs( cur_c_ptr, lora_id, pid_m, offs, offs_token, offs_cn, stride_cm, stride_cn, EM: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, sort_c: tl.constexpr, ): # When sort_c is true, store the output in c_ptr using token order defined # in sorted_token_ids_ptr; otherwise, use the original token order from the prompt if sort_c: offs_token_id = pid_m * BLOCK_SIZE_M + offs c_ptrs = ( cur_c_ptr + lora_id * EM * stride_cm + stride_cm * offs_token_id[:, None] + stride_cn * offs_cn[None, :] ) else: c_ptrs = ( cur_c_ptr + stride_cm * offs_token[:, None] + stride_cn * offs_cn[None, :] ) return c_ptrs _LORA_PTR_DICT: dict[tuple[int, ...], torch.tensor] = {} def _get_ptr(lora_weights: list[torch.Tensor], device: torch.device): """ `_LORA_PTR_DICT` collects the required information during `profile_run`, After this, it remains constant and subsequent usage is through LUT. Refer to: https://github.com/triton-lang/triton/blob/release/3.1.x/python/tutorials/08-grouped-gemm.py """ key = tuple(lora_weight.data_ptr() for lora_weight in lora_weights) if (ptr_tensor := _LORA_PTR_DICT.get(key)) is not None: return ptr_tensor tensor_ptrs = [] for lora_weight in lora_weights: tensor_ptrs.append(lora_weight.data_ptr()) ptr_tensor = torch.tensor(tensor_ptrs, device=device, dtype=torch.uint64) _LORA_PTR_DICT[key] = ptr_tensor return _LORA_PTR_DICT.get(key) def _adjust_kernel_inputs( num_active_loras: int, sorted_token_ids: torch.Tensor | None, expert_ids: torch.Tensor, ): """ helper function to adjust kernel inputs when sorted_token_ids is None """ if sorted_token_ids is None: stride_tl = 0 stride_el = 0 grid_lora_dim = 1 else: stride_tl = sorted_token_ids.stride(0) stride_el = expert_ids.stride(0) grid_lora_dim = num_active_loras return grid_lora_dim, stride_tl, stride_el @triton.jit( do_not_specialize=[ "num_valid_tokens", "EM", "stride_tl", "stride_el", "slice_a_size", "slice_c_size", ] ) def _fused_moe_lora_kernel( a_ptr, a_desc, b_ptr, b_desc, c_ptr, topk_weights_ptr, sorted_token_ids_ptr, expert_ids_ptr, num_tokens_post_padded_ptr, token_lora_mapping_ptr, # Matrix dimensions N, K, EM, num_valid_tokens, num_experts, top_k_num, lora_ids, adapter_enabled, max_loras, # <<< PR2: rename, used for masks when grid axis-2 != max_loras # The stride variables represent how much to increase the ptr by when # moving by 1 element in a particular dimension. E.g. `stride_am` is # how much to increase `a_ptr` by to get the element one row down # (A has M rows). stride_am, stride_ak, stride_bl, stride_be, stride_bk, stride_bn, stride_cm, stride_cn, stride_tl, stride_el, slice_a_size, slice_c_size, # Meta-parameters num_slice_a: tl.constexpr, num_slice_c: tl.constexpr, # top_k_num or 1 depending on input token # is expanded by top_k or not token_mapping_factor: tl.constexpr, # whether use naive block assignment naive_block_assignment: tl.constexpr, MUL_ROUTED_WEIGHT: tl.constexpr, ADD_INPUTS: tl.constexpr, USE_B_L2_CACHE: tl.constexpr, # new, enable .ca load for B BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, SPLIT_K: tl.constexpr, USE_GDC: tl.constexpr, launch_pdl: tl.constexpr, IS_PRIMARY: tl.constexpr, USE_TMA: tl.constexpr, # sort_c determines whether tokens are stored in C in the order determined # by sorted_token_ids to enable later TMA loads from this tensor. # # When USE_TMA is enabled, the parameter combinations are: # a_desc | b_desc | sort_c | Use Case # --------|---------|--------|----------------------------- # yes | yes | False | expand kernel (num_slices=1) # no | yes | True | shrink kernel (num_slices=1) # yes | no | False | expand kernel (num_slices>1) # no | no | True | shrink kernel (num_slices>1) sort_c: tl.constexpr, ): pid = tl.program_id(axis=0) slice_id = tl.program_id(axis=1) grid_k = tl.cdiv(K, BLOCK_SIZE_K * SPLIT_K) # calculate pid_m,pid_n lora_idx = tl.program_id(axis=2) pid_sk = pid % SPLIT_K pid_m_n = pid // SPLIT_K num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M) num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) num_pid_in_group = GROUP_SIZE_M * num_pid_n group_id = pid_m_n // num_pid_in_group first_pid_m = group_id * GROUP_SIZE_M group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) pid_m = first_pid_m + ((pid_m_n % num_pid_in_group) % group_size_m) pid_n = (pid_m_n % num_pid_in_group) // group_size_m offs = tl.arange(0, BLOCK_SIZE_M).to(tl.int64) # Get lora_id lora_id = _get_lora_id( lora_ids, token_lora_mapping_ptr, lora_idx, pid_m, top_k_num, naive_block_assignment, ) if lora_id == -1: return moe_enabled = tl.load(adapter_enabled + lora_id) if moe_enabled == 0: return if lora_id >= max_loras: return # Non-naive only: check num_tokens_post_padded if not naive_block_assignment: num_tokens_post_padded = tl.load(num_tokens_post_padded_ptr + lora_id) if pid_m * BLOCK_SIZE_M >= num_tokens_post_padded: return # Get expert_id expert_id = _get_expert_id( expert_ids_ptr, lora_id, pid_m, stride_el, max_loras, naive_block_assignment, ) if expert_id == -1: return # Get token offsets offs_token = _get_token_offs( sorted_token_ids_ptr, lora_id, pid_m, offs, stride_tl, max_loras, num_valid_tokens, naive_block_assignment, BLOCK_SIZE_M, ) # get a_ptr,b_ptr,c_ptr cur_a_ptr = a_ptr + (slice_id % num_slice_a) * slice_a_size cur_b_ptr = tl.load(b_ptr + slice_id).to(tl.pointer_type(c_ptr.dtype.element_ty)) cur_c_ptr = c_ptr + (slice_id % num_slice_c) * slice_c_size offs_k = pid_sk * BLOCK_SIZE_K + tl.arange(0, BLOCK_SIZE_K) token_mask = offs_token < num_valid_tokens if USE_TMA and a_desc is not None: # Expand path - with TMA enabled, load from A using TMA descriptor offs_am = ( slice_id * max_loras * EM + lora_id * EM + pid_m * BLOCK_SIZE_M // token_mapping_factor ) offs_ak = pid_sk * BLOCK_SIZE_K else: # Shrink path - load hidden states based on order defined in # 'sorted_token_ids_ptr' then store them in c_ptr in this same sorted order tl.static_assert(a_desc is None, "a_desc must be none") a_ptrs = cur_a_ptr + ( offs_token[:, None] // token_mapping_factor * stride_am + offs_k[None, :] * stride_ak ) if USE_TMA: offs_bn = pid_n * BLOCK_SIZE_N offs_bk = pid_sk * BLOCK_SIZE_K if b_desc is None: # Note(@gnovack) - Allocation of TMA descriptors on-device # can cause conflicts when running in parallel via PDL if USE_GDC and not IS_PRIMARY: tl.extra.cuda.gdc_wait() b_desc = tl.make_tensor_descriptor( cur_b_ptr, shape=[max_loras, num_experts, N, K], strides=[stride_bl, stride_be, stride_bn, stride_bk], block_shape=[1, 1, BLOCK_SIZE_N, BLOCK_SIZE_K], ) else: offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int32) b_ptrs = ( cur_b_ptr + lora_id * stride_bl + expert_id * stride_be + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn ) if USE_GDC and IS_PRIMARY: # GDC launch dependents hints the runtime system to launch dependent kernels. tl.extra.cuda.gdc_launch_dependents() accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) if USE_GDC and not IS_PRIMARY: tl.extra.cuda.gdc_wait() for k in range(0, grid_k): cur_k_offset = k * (BLOCK_SIZE_K * SPLIT_K) k_remaining = K - cur_k_offset # pre-fetch lora weight if b_desc is not None: b = ( b_desc.load([lora_id, expert_id, offs_bn, offs_bk + cur_k_offset]) .reshape(BLOCK_SIZE_N, BLOCK_SIZE_K) .T ) else: # add (offs_bn < N) mask; optional .ca for B b_mask = (offs_k[:, None] < k_remaining) & (offs_bn[None, :] < N) if USE_B_L2_CACHE: b = tl.load(b_ptrs, mask=b_mask, other=0.0, cache_modifier=".ca") else: b = tl.load(b_ptrs, mask=b_mask, other=0.0) b_ptrs += BLOCK_SIZE_K * SPLIT_K * stride_bk if a_desc is not None: a = a_desc.load([offs_am, offs_ak + cur_k_offset]) else: a = tl.load( a_ptrs, mask=token_mask[:, None] & (offs_k[None, :] < k_remaining), other=0.0, ) a_ptrs += BLOCK_SIZE_K * SPLIT_K * stride_ak accumulator += tl.dot(a, b) if MUL_ROUTED_WEIGHT: moe_weight = tl.load(topk_weights_ptr + offs_token, mask=token_mask, other=0.0) accumulator = accumulator * moe_weight[:, None] accumulator = accumulator.to(c_ptr.dtype.element_ty) # Write back the block of the output offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) c_ptrs = _get_c_ptrs( cur_c_ptr, lora_id, pid_m, offs, offs_token, offs_cn, stride_cm, stride_cn, EM, BLOCK_SIZE_M, sort_c, ) c_mask = token_mask[:, None] & (offs_cn[None, :] < N) if SPLIT_K == 1: if ADD_INPUTS: prev = tl.load(c_ptrs, mask=c_mask, other=0.0) tl.store(c_ptrs, prev + accumulator, mask=c_mask) else: tl.store(c_ptrs, accumulator, mask=c_mask) else: tl.atomic_add(c_ptrs, accumulator, mask=c_mask, sem="relaxed") @torch.inference_mode() def _fused_moe_lora_shrink( a_intermediate_cache1: torch.Tensor, # (num_slices, num_tokens, top_k_num, max_lora_rank) qcurr_hidden_states: torch.Tensor, # (num_tokens, K,) lora_a_stacked: list[ torch.Tensor ], # [(max_loras, num_experts, max_lora_rank, K,),...] topk_weights: torch.Tensor, # (num_tokens, top_k_num) sorted_token_ids: torch.Tensor | None, # (max_loras, _) expert_ids: torch.Tensor, # (max_loras, _ ,) or (num_tokens * top_k,) num_tokens_post_padded: torch.Tensor | None, # (max_loras, ) token_lora_mapping: torch.Tensor, top_k_num: int, lora_ids: torch.Tensor, adapter_enabled: torch.Tensor, ## adding for kernel device: torch.device, N: int, M: int, EM: int, K: int, num_tokens: int, num_experts: int, num_slices: int, block_size_m: int, block_size_n: int, block_size_k: int, group_size_m: int, num_warps: int, num_stages: int, split_k: int, num_active_loras: int, mul_routed_weight: bool = False, use_gdc: bool = False, use_tma: bool = False, ) -> None: w1_lora_a_stacked = lora_a_stacked[0] shrink_config = { "BLOCK_SIZE_M": block_size_m, "BLOCK_SIZE_N": block_size_n, "BLOCK_SIZE_K": block_size_k, "GROUP_SIZE_M": group_size_m, "num_warps": num_warps, "num_stages": num_stages, "SPLIT_K": split_k, "USE_GDC": use_gdc, "launch_pdl": use_gdc, # triton kernel metadata "USE_TMA": use_tma, } b_ptr = _get_ptr(lora_a_stacked, device) grid_lora_dim, stride_tl, stride_el = _adjust_kernel_inputs( num_active_loras, sorted_token_ids, expert_ids ) grid = lambda META: ( split_k * triton.cdiv(EM, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]), len(lora_a_stacked), grid_lora_dim, ) a_desc = None b_desc = None if use_tma and num_slices == 1: b_desc = triton.tools.tensor_descriptor.TensorDescriptor.from_tensor( lora_a_stacked[0], [1, 1, shrink_config["BLOCK_SIZE_N"], shrink_config["BLOCK_SIZE_K"]], ) _fused_moe_lora_kernel[grid]( qcurr_hidden_states, a_desc, b_ptr, b_desc, a_intermediate_cache1, topk_weights, sorted_token_ids, expert_ids, num_tokens_post_padded, token_lora_mapping, N, K, EM, num_tokens, num_experts, top_k_num, lora_ids, adapter_enabled, lora_a_stacked[0].shape[0], qcurr_hidden_states.stride(0), qcurr_hidden_states.stride(1), w1_lora_a_stacked.stride(0), w1_lora_a_stacked.stride(1), w1_lora_a_stacked.stride(3), w1_lora_a_stacked.stride(2), a_intermediate_cache1.stride(-2), a_intermediate_cache1.stride(-1), stride_tl, stride_el, slice_a_size=qcurr_hidden_states.numel(), slice_c_size=a_intermediate_cache1.numel() // num_slices, num_slice_a=1, num_slice_c=num_slices, token_mapping_factor=1 if mul_routed_weight else top_k_num, naive_block_assignment=sorted_token_ids is None, MUL_ROUTED_WEIGHT=False, ADD_INPUTS=False, USE_B_L2_CACHE=True, sort_c=use_tma and sorted_token_ids is not None, IS_PRIMARY=True, **shrink_config, ) @torch.inference_mode() def _fused_moe_lora_expand( output: torch.Tensor, # (num_tokens, top_k_num, N*len(lora_a_stacked),) a_intermediate_cache1: torch.Tensor, # (num_slices, M, top_k_num, max_lora_rank) lora_b_stacked: list[ torch.Tensor ], # [(max_loras, num_experts, max_lora_rank, K,),...] topk_weights: torch.Tensor, # (num_tokens, top_k_num) sorted_token_ids: torch.Tensor | None, # (max_loras, _) expert_ids: torch.Tensor, # (max_loras, _ ,) or (num_tokens * top_k,) num_tokens_post_padded: torch.Tensor | None, # (max_loras, ) token_lora_mapping: torch.Tensor, top_k_num: int, lora_ids: torch.Tensor, adapter_enabled: torch.Tensor, ## adding for kernel device: torch.device, N: int, M: int, EM: int, K: int, num_tokens: int, num_experts: int, num_slices: int, max_lora_rank: int, w1_output_dim_size: int, block_size_m: int, block_size_n: int, block_size_k: int, group_size_m: int, num_warps: int, num_stages: int, split_k: int, num_active_loras: int, mul_routed_weight: bool = False, offset: int = 0, use_gdc: bool = False, use_tma: bool = False, ) -> None: b_ptr = _get_ptr(lora_b_stacked, device) K = max_lora_rank N = w1_output_dim_size w1_lora_b_stacked = lora_b_stacked[0] a_intermediate_cache1 = a_intermediate_cache1.view( -1, a_intermediate_cache1.shape[-1] ) expand_config = { "BLOCK_SIZE_M": block_size_m, "BLOCK_SIZE_N": block_size_n, "BLOCK_SIZE_K": block_size_k, "GROUP_SIZE_M": group_size_m, "num_warps": num_warps, "num_stages": num_stages, "SPLIT_K": 1, # Set split_k = 1 for expand calls "USE_GDC": use_gdc, "launch_pdl": use_gdc, # triton kernel metadata "USE_TMA": use_tma, } grid_lora_dim, stride_tl, stride_el = _adjust_kernel_inputs( num_active_loras, sorted_token_ids, expert_ids ) grid = lambda META: ( triton.cdiv(EM, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]), len(lora_b_stacked), grid_lora_dim, ) # Fast path: directly accumulate into the corresponding slice interval of output. out_view = output[:, :, offset : offset + num_slices * N] slice_c_size = N * out_view.stride(2) a_desc = None b_desc = None if use_tma: if sorted_token_ids is not None: a_desc = triton.tools.tensor_descriptor.TensorDescriptor.from_tensor( a_intermediate_cache1, [expand_config["BLOCK_SIZE_M"], expand_config["BLOCK_SIZE_K"]], ) if num_slices == 1: b_desc = triton.tools.tensor_descriptor.TensorDescriptor.from_tensor( lora_b_stacked[0], [1, 1, expand_config["BLOCK_SIZE_N"], expand_config["BLOCK_SIZE_K"]], ) else: b_desc = None _fused_moe_lora_kernel[grid]( a_intermediate_cache1, a_desc, b_ptr, b_desc, out_view, topk_weights, sorted_token_ids, expert_ids, num_tokens_post_padded, token_lora_mapping, N, K, EM, num_tokens, num_experts, top_k_num, lora_ids, adapter_enabled, lora_b_stacked[0].shape[0], a_intermediate_cache1.stride(0), a_intermediate_cache1.stride(1), w1_lora_b_stacked.stride(0), w1_lora_b_stacked.stride(1), w1_lora_b_stacked.stride(3), w1_lora_b_stacked.stride(2), out_view.stride(1), out_view.stride(2), stride_tl, stride_el, slice_a_size=a_intermediate_cache1.numel() // num_slices, slice_c_size=slice_c_size, num_slice_a=num_slices, num_slice_c=num_slices, token_mapping_factor=1, naive_block_assignment=sorted_token_ids is None, MUL_ROUTED_WEIGHT=mul_routed_weight, ADD_INPUTS=True, USE_B_L2_CACHE=True, sort_c=False, IS_PRIMARY=False, **expand_config, ) @torch.inference_mode() def _fused_moe_lora( output: torch.Tensor, # (num_tokens, top_k_num, N*len(lora_a_stacked),) qcurr_hidden_states: torch.Tensor, # (num_tokens, K,) lora_a_stacked: list[ torch.Tensor ], # [(max_loras, num_experts, max_lora_rank, K,),...] lora_b_stacked: list[ torch.Tensor ], # [(max_loras, num_experts, N, max_lora_rank,),...] topk_weights: torch.Tensor, # (num_tokens, top_k_num) sorted_token_ids: torch.Tensor | None, # (max_loras, _) expert_ids: torch.Tensor, # (max_loras, _ ,) or (num_tokens * top_k,) num_tokens_post_padded: torch.Tensor | None, # (max_loras, ) token_lora_mapping: torch.Tensor, max_lora_rank: int, top_k_num: int, lora_ids: torch.Tensor, num_active_loras: int, adapter_enabled: torch.Tensor, shrink_block_size_m: int, shrink_block_size_n: int, shrink_block_size_k: int, shrink_group_size_m: int, shrink_num_warps: int, shrink_num_stages: int, shrink_split_k: int, expand_block_size_m: int, expand_block_size_n: int, expand_block_size_k: int, expand_group_size_m: int, expand_num_warps: int, expand_num_stages: int, expand_split_k: int, mul_routed_weight: bool = False, fully_sharded: bool = False, offset: int = 0, ) -> None: assert len(lora_a_stacked) == len(lora_b_stacked) > 0 assert topk_weights.dim() == qcurr_hidden_states.dim() == 2 if sorted_token_ids is None: assert expert_ids.dim() == 1 else: assert sorted_token_ids is not None assert num_tokens_post_padded is not None assert ( sorted_token_ids.dim() == expert_ids.dim() == topk_weights.dim() == qcurr_hidden_states.dim() == 2 ) assert ( sorted_token_ids.shape[0] == expert_ids.shape[0] == num_tokens_post_padded.shape[0] ) assert output.shape[0] == topk_weights.shape[0] assert top_k_num == topk_weights.shape[1] device = qcurr_hidden_states.device num_slices = len(lora_a_stacked) w1_lora_b_stacked = lora_b_stacked[0] num_experts = lora_a_stacked[0].shape[1] N = max_lora_rank M = topk_weights.shape[0] K = qcurr_hidden_states.shape[1] num_tokens = M * top_k_num w1_output_dim_size = w1_lora_b_stacked.shape[2] assert shrink_block_size_m == expand_block_size_m EM = ( sorted_token_ids.shape[1] if sorted_token_ids is not None else num_tokens * shrink_block_size_m ) # TMA is not currently compatiple with fully_sharded due to the non-determinism # of token id sorting across ranks. use_tma = supports_tma(device) and not fully_sharded intermediate_cache_shape = ( num_slices, M, top_k_num, max_lora_rank, ) if use_tma: if num_slices > 1: # if num_slices > 1, we construct TMA descriptors for LoRA # weights within the kernel, which requires us to first set an allocator set_triton_allocator(device) # When storing intermediate data in sorted order for TMA, we # need an extra 'num_active_loras' dim in the cache to avoid conflicts if sorted_token_ids is not None: intermediate_cache_shape = ( num_slices, sorted_token_ids.shape[0], EM, max_lora_rank, ) a_intermediate_cache1 = torch.zeros( intermediate_cache_shape, dtype=output.dtype, device=device, ) use_gdc = supports_pdl(device) and not fully_sharded _fused_moe_lora_shrink( a_intermediate_cache1, qcurr_hidden_states, lora_a_stacked, topk_weights, sorted_token_ids, expert_ids, num_tokens_post_padded, token_lora_mapping, top_k_num, lora_ids, adapter_enabled, ## adding for kernel device, N, M, EM, K, num_tokens, num_experts, num_slices, shrink_block_size_m, shrink_block_size_n, shrink_block_size_k, shrink_group_size_m, shrink_num_warps, shrink_num_stages, shrink_split_k, num_active_loras, mul_routed_weight, use_gdc=use_gdc, use_tma=use_tma, ) if fully_sharded: if max_lora_rank == w1_lora_b_stacked.shape[-1]: a_intermediate_cache1 = tensor_model_parallel_all_reduce( a_intermediate_cache1 ) else: a_intermediate_cache1 = tensor_model_parallel_all_gather( a_intermediate_cache1 ) # reset max_lora_rank to the full rank after allgather max_lora_rank = a_intermediate_cache1.shape[-1] _fused_moe_lora_expand( output, a_intermediate_cache1, lora_b_stacked, topk_weights, sorted_token_ids, expert_ids, num_tokens_post_padded, token_lora_mapping, top_k_num, lora_ids, adapter_enabled, ## adding for kernel device, N, M, EM, K, num_tokens, num_experts, num_slices, max_lora_rank, w1_output_dim_size, expand_block_size_m, expand_block_size_n, expand_block_size_k, expand_group_size_m, expand_num_warps, expand_num_stages, expand_split_k, num_active_loras, mul_routed_weight, offset, use_gdc=use_gdc, use_tma=use_tma, ) def _fused_moe_lora_fake( output: torch.Tensor, qcurr_hidden_states: torch.Tensor, lora_a_stacked: list[torch.Tensor], lora_b_stacked: list[torch.Tensor], topk_weights: torch.Tensor, sorted_token_ids: torch.Tensor | None, expert_ids: torch.Tensor, num_tokens_post_padded: torch.Tensor | None, token_lora_mapping: torch.Tensor, max_lora_rank: int, top_k_num: int, lora_ids: torch.Tensor, num_active_loras: int, adapter_enabled: torch.Tensor, shrink_block_size_m: int, shrink_block_size_n: int, shrink_block_size_k: int, shrink_group_size_m: int, shrink_num_warps: int, shrink_num_stages: int, shrink_split_k: int, expand_block_size_m: int, expand_block_size_n: int, expand_block_size_k: int, expand_group_size_m: int, expand_num_warps: int, expand_num_stages: int, expand_split_k: int, mul_routed_weight: bool = False, fully_sharded: bool = False, offset: int = 0, ) -> None: return def _fused_moe_lora_shrink_fake( a_intermediate_cache1: torch.Tensor, qcurr_hidden_states: torch.Tensor, lora_a_stacked: list[torch.Tensor], topk_weights: torch.Tensor, sorted_token_ids: torch.Tensor | None, expert_ids: torch.Tensor, num_tokens_post_padded: torch.Tensor | None, token_lora_mapping: torch.Tensor, top_k_num: int, lora_ids: torch.Tensor, adapter_enabled: torch.Tensor, device: torch.device, N: int, M: int, EM: int, K: int, num_tokens: int, num_experts: int, num_slices: int, block_size_m: int, block_size_n: int, block_size_k: int, group_size_m: int, num_warps: int, num_stages: int, split_k: int, num_active_loras: int, mul_routed_weight: bool = False, use_gdc: bool = False, use_tma: bool = False, ) -> None: return def _fused_moe_lora_expand_fake( output: torch.Tensor, a_intermediate_cache1: torch.Tensor, lora_b_stacked: list[torch.Tensor], topk_weights: torch.Tensor, sorted_token_ids: torch.Tensor | None, expert_ids: torch.Tensor, num_tokens_post_padded: torch.Tensor | None, token_lora_mapping: torch.Tensor, top_k_num: int, lora_ids: torch.Tensor, adapter_enabled: torch.Tensor, device: torch.device, N: int, M: int, EM: int, K: int, num_tokens: int, num_experts: int, num_slices: int, max_lora_rank: int, w1_output_dim_size: int, block_size_m: int, block_size_n: int, block_size_k: int, group_size_m: int, num_warps: int, num_stages: int, split_k: int, num_active_loras: int, mul_routed_weight: bool = False, offset: int = 0, use_gdc: bool = False, use_tma: bool = False, ) -> None: return try: direct_register_custom_op( op_name="fused_moe_lora", op_func=_fused_moe_lora, mutates_args=["output"], fake_impl=_fused_moe_lora_fake, ) direct_register_custom_op( op_name="fused_moe_lora_shrink", op_func=_fused_moe_lora_shrink, mutates_args=["a_intermediate_cache1"], fake_impl=_fused_moe_lora_shrink_fake, ) direct_register_custom_op( op_name="fused_moe_lora_expand", op_func=_fused_moe_lora_expand, mutates_args=["output"], fake_impl=_fused_moe_lora_expand_fake, ) fused_moe_lora = torch.ops.vllm.fused_moe_lora fused_moe_lora_shrink = torch.ops.vllm.fused_moe_lora_shrink fused_moe_lora_expand = torch.ops.vllm.fused_moe_lora_expand except AttributeError: fused_moe_lora = _fused_moe_lora fused_moe_lora_shrink = _fused_moe_lora_shrink fused_moe_lora_expand = _fused_moe_lora_expand
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/lora/ops/triton_ops/fused_moe_lora_op.py", "license": "Apache License 2.0", "lines": 921, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/bee.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Mapping import torch import torch.nn as nn from transformers.activations import GELUActivation from vllm.config import VllmConfig from vllm.config.multimodal import BaseDummyOptions from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.inputs import MultiModalDataDict from .llava_next import ( LlavaDummyInputsBuilder, LlavaNextMultiModalProcessor, LlavaNextProcessingInfo, ) from .llava_onevision import LlavaOnevisionForConditionalGeneration from .utils import WeightsMapper class BeeProcessingInfo(LlavaNextProcessingInfo): def get_hf_config(self): return self.ctx.get_hf_config() def get_hf_processor(self, **kwargs: object): return self.ctx.get_hf_processor(**kwargs) def _get_num_unpadded_features( self, *, original_height: int, original_width: int, npatches: int, num_patch_height: int, num_patch_width: int, ) -> tuple[int, int]: """Override to use correct max_num_patches from vision_aspect_ratio.""" import math current_height = npatches * num_patch_height current_width = npatches * num_patch_width aspect_ratio = original_width / original_height current_aspect_ratio = current_width / current_height if aspect_ratio > current_aspect_ratio: new_height = int( round(original_height * (current_width / original_width), 7) ) padding = (current_height - new_height) // 2 current_height = current_height - (2 * padding) else: new_width = int( round(original_width * (current_height / original_height), 7) ) padding = (current_width - new_width) // 2 current_width = current_width - (2 * padding) unpadded_features = current_height * current_width newline_features = current_height # Get max_num_patches from vision_aspect_ratio config hf_config = self.get_hf_config() vision_aspect_ratio = getattr(hf_config, "vision_aspect_ratio", "anyres_max_9") max_num_patches = int(vision_aspect_ratio.replace("anyres_max_", "")) ratio = math.sqrt( current_height * current_width / (max_num_patches * npatches**2) ) if ratio > 1.1: height_factor = int(current_height // ratio) width_factor = int(current_width // ratio) unpadded_features = height_factor * width_factor newline_features = height_factor return (unpadded_features, newline_features) class BeeDummyInputsBuilder(LlavaDummyInputsBuilder[BeeProcessingInfo]): def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str: num_images = mm_counts.get("image", 0) image_token = "<image>" return image_token * num_images def get_dummy_mm_data( self, seq_len: int, mm_counts: Mapping[str, int], mm_options: Mapping[str, BaseDummyOptions], ) -> MultiModalDataDict: num_images = mm_counts.get("image", 0) target_width, target_height = self.info.get_image_size_with_most_features() image_overrides = mm_options.get("image") return { "image": self._get_dummy_images( width=target_width, height=target_height, num_images=num_images, overrides=image_overrides, ), } class BeeMultiModalProjector(nn.Module): def __init__(self, config): super().__init__() self.pre_norm = nn.LayerNorm(config.vision_config.hidden_size, eps=1e-06) self.linear_1 = nn.Linear( config.vision_config.hidden_size, config.text_config.hidden_size * 4, bias=True, ) self.act = GELUActivation() self.linear_2 = nn.Linear( config.text_config.hidden_size * 4, config.text_config.hidden_size, bias=True, ) def forward(self, image_feature: torch.Tensor) -> torch.Tensor: image_feature = self.pre_norm(image_feature) hidden_states = self.linear_1(image_feature) hidden_states = self.act(hidden_states) hidden_states = self.linear_2(hidden_states) return hidden_states @MULTIMODAL_REGISTRY.register_processor( LlavaNextMultiModalProcessor, info=BeeProcessingInfo, dummy_inputs=BeeDummyInputsBuilder, ) class BeeForConditionalGeneration(LlavaOnevisionForConditionalGeneration): hf_to_vllm_mapper = WeightsMapper( orig_to_new_prefix={ # mapping for new names in checkpoint saved after transformers # v4.55 "model.language_model.": "language_model.model.", "model.vision_tower.": "vision_tower.", "model.multi_modal_projector.": "multi_modal_projector.", "model.image_newline": "image_newline", "lm_head.": "language_model.lm_head.", } ) def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: super().__init__(vllm_config=vllm_config, prefix=prefix) config = vllm_config.model_config.hf_config self.multi_modal_projector = BeeMultiModalProjector(config)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/bee.py", "license": "Apache License 2.0", "lines": 128, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/utils_/test_hashing.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import hashlib import pickle import pytest from vllm.utils.hashing import sha256 @pytest.mark.parametrize("input", [(), ("abc",), (None,), (None, bool, [1, 2, 3])]) def test_sha256(input: tuple): digest = sha256(input) assert digest is not None assert isinstance(digest, bytes) assert digest != b"" input_bytes = pickle.dumps(input, protocol=pickle.HIGHEST_PROTOCOL) assert digest == hashlib.sha256(input_bytes).digest() # hashing again, returns the same value assert digest == sha256(input) # hashing different input, returns different value assert digest != sha256(input + (1,))
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_hashing.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/utils_/test_mem_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm_test_utils.monitor import monitor from vllm.utils.mem_utils import MemorySnapshot, memory_profiling from ..utils import create_new_process_for_each_test @create_new_process_for_each_test() def test_memory_profiling(): # Fake out some model loading + inference memory usage to test profiling # Memory used by other processes will show up as cuda usage outside of torch from vllm.distributed.device_communicators.cuda_wrapper import CudaRTLibrary lib = CudaRTLibrary() # 512 MiB allocation outside of this instance handle1 = lib.cudaMalloc(512 * 1024 * 1024) baseline_snapshot = MemorySnapshot() # load weights weights = torch.randn(128, 1024, 1024, device="cuda", dtype=torch.float32) weights_memory = 128 * 1024 * 1024 * 4 # 512 MiB def measure_current_non_torch(): free, total = torch.cuda.mem_get_info() current_used = total - free current_torch = torch.cuda.memory_reserved() current_non_torch = current_used - current_torch return current_non_torch with ( memory_profiling( baseline_snapshot=baseline_snapshot, weights_memory=weights_memory ) as result, monitor(measure_current_non_torch) as monitored_values, ): # make a memory spike, 1 GiB spike = torch.randn(256, 1024, 1024, device="cuda", dtype=torch.float32) del spike # Add some extra non-torch memory 256 MiB (simulate NCCL) handle2 = lib.cudaMalloc(256 * 1024 * 1024) # this is an analytic value, it is exact, # we only have 256 MiB non-torch memory increase measured_diff = monitored_values.values[-1] - monitored_values.values[0] assert measured_diff == 256 * 1024 * 1024 # Check that the memory usage is within 5% of the expected values # 5% tolerance is caused by cuda runtime. # we cannot control cuda runtime in the granularity of bytes, # which causes a small error (<10 MiB in practice) non_torch_ratio = result.non_torch_increase / (256 * 1024 * 1024) # noqa assert abs(non_torch_ratio - 1) <= 0.05 assert result.torch_peak_increase == 1024 * 1024 * 1024 del weights lib.cudaFree(handle1) lib.cudaFree(handle2)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_mem_utils.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/utils_/test_torch_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from vllm.utils.torch_utils import ( common_broadcastable_dtype, current_stream, is_lossless_cast, ) @pytest.mark.parametrize( ("src_dtype", "tgt_dtype", "expected_result"), [ # Different precision_levels (torch.bool, torch.int8, True), (torch.bool, torch.float16, True), (torch.bool, torch.complex32, True), (torch.int64, torch.bool, False), (torch.int64, torch.float16, True), (torch.int64, torch.complex32, True), (torch.float64, torch.bool, False), (torch.float64, torch.int8, False), (torch.float64, torch.complex32, True), (torch.complex128, torch.bool, False), (torch.complex128, torch.int8, False), (torch.complex128, torch.float16, False), # precision_level=0 (torch.bool, torch.bool, True), # precision_level=1 (torch.int8, torch.int16, True), (torch.int16, torch.int8, False), (torch.uint8, torch.int8, False), (torch.int8, torch.uint8, False), # precision_level=2 (torch.float16, torch.float32, True), (torch.float32, torch.float16, False), (torch.bfloat16, torch.float32, True), (torch.float32, torch.bfloat16, False), # precision_level=3 (torch.complex32, torch.complex64, True), (torch.complex64, torch.complex32, False), ], ) def test_is_lossless_cast(src_dtype, tgt_dtype, expected_result): assert is_lossless_cast(src_dtype, tgt_dtype) == expected_result @pytest.mark.parametrize( ("dtypes", "expected_result"), [ ([torch.bool], torch.bool), ([torch.bool, torch.int8], torch.int8), ([torch.bool, torch.int8, torch.float16], torch.float16), ([torch.bool, torch.int8, torch.float16, torch.complex32], torch.complex32), # noqa: E501 ], ) def test_common_broadcastable_dtype(dtypes, expected_result): assert common_broadcastable_dtype(dtypes) == expected_result def _test_stream_thread(main_expected_stream: torch.cuda.Stream): import threading child_stream = torch.cuda.Stream() thread_stream_ready = threading.Event() thread_can_exit = threading.Event() def child_thread_func(): with torch.cuda.stream(child_stream): thread_stream_ready.set() thread_can_exit.wait(timeout=10) child_thread = threading.Thread(target=child_thread_func) child_thread.start() try: assert thread_stream_ready.wait(timeout=5), ( "Child thread failed to enter stream context in time" ) main_current_stream = current_stream() assert main_current_stream != child_stream, ( "Main thread's current_stream was contaminated by child thread" ) assert main_current_stream == main_expected_stream, ( f"Main thread's stream changed unexpectedly. " f"Expected {main_expected_stream}, got {main_current_stream}" ) thread_can_exit.set() finally: child_thread.join(timeout=5) if child_thread.is_alive(): pytest.fail("Child thread failed to exit properly") def test_current_stream_multithread(): if not torch.cuda.is_available(): pytest.skip("CUDA not available") main_dedicated_stream = current_stream() assert main_dedicated_stream.cuda_stream != 0, ( "ROCm/CUDA should create a dedicated stream, not use default stream (0x0)" ) main_stream_again = current_stream() assert main_stream_again == main_dedicated_stream, ( "Multiple calls to current_stream should return the same dedicated stream" ) _test_stream_thread(main_dedicated_stream)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_torch_utils.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/utils_/test_network_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import socket import pytest import zmq from vllm.utils.network_utils import ( get_open_port, get_tcp_uri, join_host_port, make_zmq_path, make_zmq_socket, split_host_port, split_zmq_path, ) def test_get_open_port(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: m.setenv("VLLM_PORT", "5678") # make sure we can get multiple ports, even if the env var is set with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s1: s1.bind(("localhost", get_open_port())) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s2: s2.bind(("localhost", get_open_port())) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s3: s3.bind(("localhost", get_open_port())) @pytest.mark.parametrize( "path,expected", [ ("ipc://some_path", ("ipc", "some_path", "")), ("tcp://127.0.0.1:5555", ("tcp", "127.0.0.1", "5555")), ("tcp://[::1]:5555", ("tcp", "::1", "5555")), # IPv6 address ("inproc://some_identifier", ("inproc", "some_identifier", "")), ], ) def test_split_zmq_path(path, expected): assert split_zmq_path(path) == expected @pytest.mark.parametrize( "invalid_path", [ "invalid_path", # Missing scheme "tcp://127.0.0.1", # Missing port "tcp://[::1]", # Missing port for IPv6 "tcp://:5555", # Missing host ], ) def test_split_zmq_path_invalid(invalid_path): with pytest.raises(ValueError): split_zmq_path(invalid_path) def test_make_zmq_socket_ipv6(): # Check if IPv6 is supported by trying to create an IPv6 socket try: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.close() except OSError: pytest.skip("IPv6 is not supported on this system") ctx = zmq.Context() ipv6_path = "tcp://[::]:5555" # IPv6 loopback address socket_type = zmq.REP # Example socket type # Create the socket zsock: zmq.Socket = make_zmq_socket(ctx, ipv6_path, socket_type) # Verify that the IPV6 option is set assert zsock.getsockopt(zmq.IPV6) == 1, ( "IPV6 option should be enabled for IPv6 addresses" ) # Clean up zsock.close() ctx.term() def test_make_zmq_path(): assert make_zmq_path("tcp", "127.0.0.1", "5555") == "tcp://127.0.0.1:5555" assert make_zmq_path("tcp", "::1", "5555") == "tcp://[::1]:5555" def test_get_tcp_uri(): assert get_tcp_uri("127.0.0.1", 5555) == "tcp://127.0.0.1:5555" assert get_tcp_uri("::1", 5555) == "tcp://[::1]:5555" def test_split_host_port(): # valid ipv4 assert split_host_port("127.0.0.1:5555") == ("127.0.0.1", 5555) # invalid ipv4 with pytest.raises(ValueError): # multi colon assert split_host_port("127.0.0.1::5555") with pytest.raises(ValueError): # tailing colon assert split_host_port("127.0.0.1:5555:") with pytest.raises(ValueError): # no colon assert split_host_port("127.0.0.15555") with pytest.raises(ValueError): # none int port assert split_host_port("127.0.0.1:5555a") # valid ipv6 assert split_host_port("[::1]:5555") == ("::1", 5555) # invalid ipv6 with pytest.raises(ValueError): # multi colon assert split_host_port("[::1]::5555") with pytest.raises(IndexError): # no colon assert split_host_port("[::1]5555") with pytest.raises(ValueError): # none int port assert split_host_port("[::1]:5555a") def test_join_host_port(): assert join_host_port("127.0.0.1", 5555) == "127.0.0.1:5555" assert join_host_port("::1", 5555) == "[::1]:5555"
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_network_utils.py", "license": "Apache License 2.0", "lines": 103, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/network_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import ipaddress import os import socket import sys import warnings from collections.abc import ( Iterator, Sequence, ) from typing import Any from uuid import uuid4 import psutil import zmq import zmq.asyncio from urllib3.util import parse_url import vllm.envs as envs from vllm.logger import init_logger logger = init_logger(__name__) def close_sockets(sockets: Sequence[zmq.Socket | zmq.asyncio.Socket]): for sock in sockets: if sock is not None: sock.close(linger=0) def get_ip() -> str: host_ip = envs.VLLM_HOST_IP if "HOST_IP" in os.environ and "VLLM_HOST_IP" not in os.environ: logger.warning( "The environment variable HOST_IP is deprecated and ignored, as" " it is often used by Docker and other software to" " interact with the container's network stack. Please " "use VLLM_HOST_IP instead to set the IP address for vLLM processes" " to communicate with each other." ) if host_ip: return host_ip # IP is not set, try to get it from the network interface # try ipv4 try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.connect(("8.8.8.8", 80)) # Doesn't need to be reachable return s.getsockname()[0] except Exception: pass # try ipv6 try: with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as s: # Google's public DNS server, see # https://developers.google.com/speed/public-dns/docs/using#addresses s.connect(("2001:4860:4860::8888", 80)) # Doesn't need to be reachable return s.getsockname()[0] except Exception: pass warnings.warn( "Failed to get the IP address, using 0.0.0.0 by default." "The value can be set by the environment variable" " VLLM_HOST_IP or HOST_IP.", stacklevel=2, ) return "0.0.0.0" def test_loopback_bind(address: str, family: int) -> bool: try: s = socket.socket(family, socket.SOCK_DGRAM) s.bind((address, 0)) # Port 0 = auto assign s.close() return True except OSError: return False def get_loopback_ip() -> str: loopback_ip = envs.VLLM_LOOPBACK_IP if loopback_ip: return loopback_ip # VLLM_LOOPBACK_IP is not set, try to get it based on network interface if test_loopback_bind("127.0.0.1", socket.AF_INET): return "127.0.0.1" elif test_loopback_bind("::1", socket.AF_INET6): return "::1" else: raise RuntimeError( "Neither 127.0.0.1 nor ::1 are bound to a local interface. " "Set the VLLM_LOOPBACK_IP environment variable explicitly." ) def is_valid_ipv6_address(address: str) -> bool: try: ipaddress.IPv6Address(address) return True except ValueError: return False def split_host_port(host_port: str) -> tuple[str, int]: # ipv6 if host_port.startswith("["): host, port = host_port.rsplit("]", 1) host = host[1:] port = port.split(":")[1] return host, int(port) else: host, port = host_port.split(":") return host, int(port) def join_host_port(host: str, port: int) -> str: if is_valid_ipv6_address(host): return f"[{host}]:{port}" else: return f"{host}:{port}" def get_distributed_init_method(ip: str, port: int) -> str: return get_tcp_uri(ip, port) def get_tcp_uri(ip: str, port: int) -> str: if is_valid_ipv6_address(ip): return f"tcp://[{ip}]:{port}" else: return f"tcp://{ip}:{port}" def get_open_zmq_ipc_path() -> str: base_rpc_path = envs.VLLM_RPC_BASE_PATH return f"ipc://{base_rpc_path}/{uuid4()}" def get_open_zmq_inproc_path() -> str: return f"inproc://{uuid4()}" def get_open_port() -> int: """ Get an open port for the vLLM process to listen on. An edge case to handle, is when we run data parallel, we need to avoid ports that are potentially used by the data parallel master process. Right now we reserve 10 ports for the data parallel master process. Currently it uses 2 ports. """ if "VLLM_DP_MASTER_PORT" in os.environ: dp_master_port = envs.VLLM_DP_MASTER_PORT reserved_port_range = range(dp_master_port, dp_master_port + 10) while True: candidate_port = _get_open_port() if candidate_port not in reserved_port_range: return candidate_port return _get_open_port() def get_open_ports_list(count: int = 5) -> list[int]: """Get a list of open ports.""" ports = set[int]() while len(ports) < count: ports.add(get_open_port()) return list(ports) def _get_open_port() -> int: port = envs.VLLM_PORT if port is not None: while True: try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("", port)) return port except OSError: port += 1 # Increment port number if already in use logger.info("Port %d is already in use, trying port %d", port - 1, port) # try ipv4 try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("", 0)) return s.getsockname()[1] except OSError: # try ipv6 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: s.bind(("", 0)) return s.getsockname()[1] def find_process_using_port(port: int) -> psutil.Process | None: # TODO: We can not check for running processes with network # port on macOS. Therefore, we can not have a full graceful shutdown # of vLLM. For now, let's not look for processes in this case. # Ref: https://www.florianreinhard.de/accessdenied-in-psutil/ if sys.platform.startswith("darwin"): return None our_pid = os.getpid() for conn in psutil.net_connections(): if conn.laddr.port == port and (conn.pid is not None and conn.pid != our_pid): try: return psutil.Process(conn.pid) except psutil.NoSuchProcess: return None return None def split_zmq_path(path: str) -> tuple[str, str, str]: """Split a zmq path into its parts.""" parsed = parse_url(path) if not parsed.scheme: raise ValueError(f"Invalid zmq path: {path}") scheme = parsed.scheme host = parsed.hostname or "" port = str(parsed.port or "") if host.startswith("[") and host.endswith("]"): host = host[1:-1] # Remove brackets for IPv6 address if scheme == "tcp" and not all((host, port)): # The host and port fields are required for tcp raise ValueError(f"Invalid zmq path: {path}") if scheme != "tcp" and port: # port only makes sense with tcp raise ValueError(f"Invalid zmq path: {path}") return scheme, host, port def make_zmq_path(scheme: str, host: str, port: int | None = None) -> str: """Make a ZMQ path from its parts. Args: scheme: The ZMQ transport scheme (e.g. tcp, ipc, inproc). host: The host - can be an IPv4 address, IPv6 address, or hostname. port: Optional port number, only used for TCP sockets. Returns: A properly formatted ZMQ path string. """ if port is None: return f"{scheme}://{host}" if is_valid_ipv6_address(host): return f"{scheme}://[{host}]:{port}" return f"{scheme}://{host}:{port}" # Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/srt/utils.py#L783 # noqa: E501 def make_zmq_socket( ctx: zmq.asyncio.Context | zmq.Context, # type: ignore[name-defined] path: str, socket_type: Any, bind: bool | None = None, identity: bytes | None = None, linger: int | None = None, ) -> zmq.Socket | zmq.asyncio.Socket: # type: ignore[name-defined] """Make a ZMQ socket with the proper bind/connect semantics.""" mem = psutil.virtual_memory() socket = ctx.socket(socket_type) # Calculate buffer size based on system memory total_mem = mem.total / 1024**3 available_mem = mem.available / 1024**3 # For systems with substantial memory (>32GB total, >16GB available): # - Set a large 0.5GB buffer to improve throughput # For systems with less memory: # - Use system default (-1) to avoid excessive memory consumption buf_size = int(0.5 * 1024**3) if total_mem > 32 and available_mem > 16 else -1 if bind is None: bind = socket_type not in (zmq.PUSH, zmq.SUB, zmq.XSUB) if socket_type in (zmq.PULL, zmq.DEALER, zmq.ROUTER): socket.setsockopt(zmq.RCVHWM, 0) socket.setsockopt(zmq.RCVBUF, buf_size) if socket_type in (zmq.PUSH, zmq.DEALER, zmq.ROUTER): socket.setsockopt(zmq.SNDHWM, 0) socket.setsockopt(zmq.SNDBUF, buf_size) if identity is not None: socket.setsockopt(zmq.IDENTITY, identity) if linger is not None: socket.setsockopt(zmq.LINGER, linger) if socket_type == zmq.XPUB: socket.setsockopt(zmq.XPUB_VERBOSE, True) # Determine if the path is a TCP socket with an IPv6 address. # Enable IPv6 on the zmq socket if so. scheme, host, _ = split_zmq_path(path) if scheme == "tcp" and is_valid_ipv6_address(host): socket.setsockopt(zmq.IPV6, 1) if bind: socket.bind(path) else: socket.connect(path) return socket @contextlib.contextmanager def zmq_socket_ctx( path: str, socket_type: Any, bind: bool | None = None, linger: int = 0, identity: bytes | None = None, ) -> Iterator[zmq.Socket]: """Context manager for a ZMQ socket""" ctx = zmq.Context() # type: ignore[attr-defined] try: yield make_zmq_socket(ctx, path, socket_type, bind=bind, identity=identity) except KeyboardInterrupt: logger.debug("Got Keyboard Interrupt.") finally: ctx.destroy(linger=linger)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/network_utils.py", "license": "Apache License 2.0", "lines": 266, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/utils/hashing.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import hashlib import pickle from _hashlib import HASH, UnsupportedDigestmodError from collections.abc import Callable from typing import Any import cbor2 try: # It is important that this remains an optional dependency. # It would not be allowed in environments with strict security controls, # so it's best not to have it installed when not in use. import xxhash as _xxhash if not hasattr(_xxhash, "xxh3_128_digest"): _xxhash = None except ImportError: # pragma: no cover _xxhash = None def sha256(input: Any) -> bytes: """Hash any picklable Python object using SHA-256. The input is serialized using pickle before hashing, which allows arbitrary Python objects to be used. Note that this function does not use a hash seed—if you need one, prepend it explicitly to the input. Args: input: Any picklable Python object. Returns: Bytes representing the SHA-256 hash of the serialized input. """ input_bytes = pickle.dumps(input, protocol=pickle.HIGHEST_PROTOCOL) return hashlib.sha256(input_bytes).digest() def sha256_cbor(input: Any) -> bytes: """Hash objects using CBOR serialization and SHA-256. This option is useful for non-Python-dependent serialization and hashing. Args: input: Object to be serialized and hashed. Supported types include basic Python types and complex structures like lists, tuples, and dictionaries. Custom classes must implement CBOR serialization methods. Returns: Bytes representing the SHA-256 hash of the CBOR serialized input. """ input_bytes = cbor2.dumps(input, canonical=True) return hashlib.sha256(input_bytes).digest() def _xxhash_digest(input_bytes: bytes) -> bytes: if _xxhash is None: raise ModuleNotFoundError( "xxhash is required for the 'xxhash' prefix caching hash algorithms. " "Install it via `pip install xxhash`." ) return _xxhash.xxh3_128_digest(input_bytes) def xxhash(input: Any) -> bytes: """Hash picklable objects using xxHash.""" input_bytes = pickle.dumps(input, protocol=pickle.HIGHEST_PROTOCOL) return _xxhash_digest(input_bytes) def xxhash_cbor(input: Any) -> bytes: """Hash objects serialized with CBOR using xxHash.""" input_bytes = cbor2.dumps(input, canonical=True) return _xxhash_digest(input_bytes) def get_hash_fn_by_name(hash_fn_name: str) -> Callable[[Any], bytes]: """Get a hash function by name, or raise an error if the function is not found. Args: hash_fn_name: Name of the hash function. Returns: A hash function. """ if hash_fn_name == "sha256": return sha256 if hash_fn_name == "sha256_cbor": return sha256_cbor if hash_fn_name == "xxhash": return xxhash if hash_fn_name == "xxhash_cbor": return xxhash_cbor raise ValueError(f"Unsupported hash function: {hash_fn_name}") def safe_hash(data: bytes, usedforsecurity: bool = True) -> HASH: """Hash for configs, defaulting to md5 but falling back to sha256 in FIPS constrained environments. Args: data: bytes usedforsecurity: Whether the hash is used for security purposes Returns: Hash object """ try: return hashlib.md5(data, usedforsecurity=usedforsecurity) except (UnsupportedDigestmodError, ValueError): return hashlib.sha256(data)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/hashing.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/plugins/vllm_add_dummy_stat_logger/dummy_stat_logger/dummy_stat_logger.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.v1.metrics.loggers import StatLoggerBase class DummyStatLogger(StatLoggerBase): """ A dummy stat logger for testing purposes. Implements the minimal interface expected by StatLoggerManager. """ def __init__(self, vllm_config, engine_idx=0): self.vllm_config = vllm_config self.engine_idx = engine_idx self.recorded = [] self.logged = False self.engine_initialized = False def record(self, scheduler_stats, iteration_stats, mm_cache_stats, engine_idx): self.recorded.append( (scheduler_stats, iteration_stats, mm_cache_stats, engine_idx) ) def log(self): self.logged = True def log_engine_initialized(self): self.engine_initialized = True
{ "repo_id": "vllm-project/vllm", "file_path": "tests/plugins/vllm_add_dummy_stat_logger/dummy_stat_logger/dummy_stat_logger.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm: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()
{ "repo_id": "vllm-project/vllm", "file_path": "tests/plugins_tests/test_stats_logger_plugins.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/profiling.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import contextlib from collections.abc import Callable from functools import wraps from typing import Any @contextlib.contextmanager def cprofile_context(save_file: str | None = None): """Run a cprofile Args: save_file: path to save the profile result. "1" or None will result in printing to stdout. """ import cProfile prof = cProfile.Profile() prof.enable() try: yield finally: prof.disable() if save_file and save_file != "1": prof.dump_stats(save_file) else: prof.print_stats(sort="cumtime") def cprofile(save_file: str | None = None, enabled: bool = True): """Decorator to profile a Python method using cProfile. Args: save_file: Path to save the profile result. If "1", None, or "", results will be printed to stdout. enabled: Set to false to turn this into a no-op """ def decorator(func: Callable): @wraps(func) def wrapper(*args: Any, **kwargs: Any): if not enabled: # If profiling is disabled, just call the function directly. return func(*args, **kwargs) with cprofile_context(save_file): return func(*args, **kwargs) return wrapper return decorator
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/profiling.py", "license": "Apache License 2.0", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/utils/torch_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import importlib.metadata import os import random import threading from collections.abc import Callable, Collection from functools import lru_cache from typing import TYPE_CHECKING, Any, TypeVar import numpy as np import numpy.typing as npt import torch from packaging import version from packaging.version import Version from torch.library import Library, infer_schema import vllm.envs as envs from vllm.logger import init_logger if TYPE_CHECKING: from vllm.config import ModelConfig from vllm.sequence import IntermediateTensors else: ModelConfig = object IntermediateTensors = object logger = init_logger(__name__) STR_DTYPE_TO_TORCH_DTYPE = { "float32": torch.float32, "half": torch.half, "float16": torch.float16, "bfloat16": torch.bfloat16, "float": torch.float, "fp8": torch.uint8, "fp8_e4m3": torch.uint8, "fp8_e5m2": torch.uint8, "int8": torch.int8, "fp8_inc": torch.float8_e4m3fn, "fp8_ds_mla": torch.uint8, } TORCH_DTYPE_TO_NUMPY_DTYPE = { torch.float16: np.float16, torch.float32: np.float32, torch.float64: np.float64, torch.uint8: np.uint8, torch.int32: np.int32, torch.int64: np.int64, } MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP = { # TODO: Add more modelopt kv cache dtype # mappings here when it supported by some attention backend # (for example supports nvfp4). "fp8": "fp8_e4m3", } T = TypeVar("T") def is_strictly_contiguous(t: torch.Tensor) -> bool: """ Check if tensor is contiguous AND has no degenerate strides. A degenerate stride occurs when a dimension has size 1 but the stride doesn't match the canonical contiguous layout. This can cause issues in some CUDA kernels that rely on stride values for memory access. For a C-contiguous tensor of shape (d0, d1, ..., dn), the expected strides are: stride[i] = product(shape[i+1:]) for all i, with stride[-1]=1. Example with torch.Size([16, 1, 8, 32]): - Canonical strides: (256, 256, 32, 1) - Degenerate strides: (256, 1, 32, 1) # dim=1 has size=1, allowing # non-canonical stride in dim=0 """ if not t.is_contiguous(): return False # Check that strides match canonical contiguous layout shape = t.shape strides = t.stride() expected_stride = 1 for i in range(len(shape) - 1, -1, -1): if strides[i] != expected_stride: return False expected_stride *= shape[i] return True @contextlib.contextmanager def set_default_torch_dtype(dtype: torch.dtype): """Sets the default torch dtype to the given dtype.""" old_dtype = torch.get_default_dtype() torch.set_default_dtype(dtype) yield torch.set_default_dtype(old_dtype) @contextlib.contextmanager def set_default_torch_num_threads(num_threads: int | None = None): """ Sets the default number of threads for PyTorch to the given value. `None` means using the value of the environment variable `OMP_NUM_THREADS` (or `1` if that is not available). """ if num_threads is None: num_threads = 1 try: num_threads = int(os.environ["OMP_NUM_THREADS"]) except KeyError: logger.debug_once( "OMP_NUM_THREADS is not set; defaulting Torch threads to %d.", num_threads, ) except ValueError: logger.warning_once( "OMP_NUM_THREADS is invalid; defaulting Torch threads to %d.", num_threads, ) old_num_threads = torch.get_num_threads() torch.set_num_threads(num_threads) try: yield finally: torch.set_num_threads(old_num_threads) @contextlib.contextmanager def guard_cuda_initialization(): """Avoid unexpected CUDA initialization.""" from vllm.platforms import current_platform if not current_platform.is_cuda(): yield return old_value = os.environ.get("CUDA_VISIBLE_DEVICES") os.environ["CUDA_VISIBLE_DEVICES"] = "" try: yield except Exception as e: if "No CUDA GPUs are available" in str(e): err_msg = "CUDA initialization is blocked." else: err_msg = str(e) raise RuntimeError(err_msg) from e finally: if old_value is None: del os.environ["CUDA_VISIBLE_DEVICES"] else: os.environ["CUDA_VISIBLE_DEVICES"] = old_value def get_dtype_size(dtype: torch.dtype) -> int: """Get the size of the data type in bytes.""" return torch.tensor([], dtype=dtype).element_size() # bool = 0, int = 1, float = 2, complex = 3 def _get_precision_level(dtype: torch.dtype) -> int: # NOTE: Complex dtypes return `is_floating_point=False` return (dtype != torch.bool) + dtype.is_floating_point + dtype.is_complex * 2 def is_lossless_cast(src_dtype: torch.dtype, tgt_dtype: torch.dtype): """ Test whether it is lossless to cast a tensor from `src_dtype` to `tgt_dtype`. """ if src_dtype == tgt_dtype: return True src_level = _get_precision_level(src_dtype) tgt_level = _get_precision_level(tgt_dtype) if src_level < tgt_level: return True if src_level > tgt_level: return False # Compare integral types if not src_dtype.is_floating_point and not src_dtype.is_complex: src_info = torch.iinfo(src_dtype) tgt_info = torch.iinfo(tgt_dtype) return src_info.min >= tgt_info.min and src_info.max <= tgt_info.max # Compare floating-point types src_info = torch.finfo(src_dtype) tgt_info = torch.finfo(tgt_dtype) return ( src_info.min >= tgt_info.min and src_info.max <= tgt_info.max and src_info.resolution >= tgt_info.resolution ) def common_broadcastable_dtype(dtypes: Collection[torch.dtype]): """ Get the common `dtype` where all of the other `dtypes` can be cast to it without losing any information. """ return max( dtypes, key=lambda dtype: sum(is_lossless_cast(dt, dtype) for dt in dtypes), ) def _generate_random_fp8( tensor: torch.Tensor, low: float, high: float, ) -> None: # NOTE(zhaoyang): Due to NaN and Inf representation for fp8 data type, # it may occur Inf or NaN if we directly use torch.randint # to generate random data for fp8 data. # For example, s.11111.00 in fp8e5m2 format represents Inf. # | E4M3 | E5M2 # -----|-------------|------------------- # Inf | N/A | s.11111.00 # NaN | s.1111.111 | s.11111.{01,10,11} from vllm import _custom_ops as ops tensor_tmp = torch.empty_like(tensor, dtype=torch.float16) tensor_tmp.uniform_(low, high) ops.convert_fp8(tensor, tensor_tmp) del tensor_tmp def get_kv_cache_torch_dtype( cache_dtype: str | torch.dtype | None, model_dtype: str | torch.dtype | None = None, ) -> torch.dtype: if isinstance(cache_dtype, str): if cache_dtype == "auto": if isinstance(model_dtype, str) and model_dtype in STR_DTYPE_TO_TORCH_DTYPE: torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[model_dtype] elif isinstance(model_dtype, torch.dtype): torch_dtype = model_dtype else: raise ValueError(f"Invalid model dtype: {model_dtype}") elif cache_dtype in STR_DTYPE_TO_TORCH_DTYPE: torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype] else: raise ValueError(f"Invalid kv cache dtype: {cache_dtype}") elif isinstance(cache_dtype, torch.dtype): torch_dtype = cache_dtype else: raise ValueError(f"Invalid kv cache dtype: {cache_dtype}") return torch_dtype def get_kv_cache_quant_algo_string(quant_cfg: dict[str, Any]) -> str | None: """Get the KV cache quantization algorithm string from the quantization config. Maps various FP8 format names to vLLM's standard cache dtype strings. Returns None if no kv_cache_quant_algo is specified. Returns "auto" if the value is not recognized/supported. """ # Mapping from model config values to vLLM cache_dtype strings quant_method = quant_cfg.get("quant_method", "") if quant_method.startswith("modelopt"): quantization_inner = quant_cfg.get("quantization", quant_cfg) # Check if quant config is specified and use kv cache quant algo kv_algo = ( quantization_inner.get("kv_cache_scheme") or quant_cfg.get("kv_cache_scheme") or quantization_inner.get("kv_cache_quant_algo") or quant_cfg.get("kv_cache_quant_algo") ) if isinstance(kv_algo, dict): if ( kv_algo.get("dynamic") is False and kv_algo.get("num_bits") == 8 and kv_algo.get("type") == "float" ): kv_algo = "fp8" else: # Unknown/unsupported format - return "auto" as safe fallback logger.warning( "WARNING: Unknown kv_cache_quant_algo '%s' in model " "config. Supported values: %s. Falling back to 'auto'.", f"{kv_algo}", list(MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP.keys()), ) return "auto" if isinstance(kv_algo, str): kv_algo_lower = kv_algo.lower() # Try to map to vLLM's standard format if kv_algo_lower in MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP: return MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP[kv_algo_lower] else: # Unknown/unsupported format - return "auto" as safe fallback logger.warning( "WARNING: Unknown kv_cache_quant_algo '%s' in model " "config. Supported values: %s. Falling back to 'auto'.", kv_algo, list(MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP.keys()), ) return "auto" return None def get_kv_cache_quant_algo_dtype(quant_cfg: dict[str, Any]) -> torch.dtype | None: """Get the KV cache quantization algorithm dtype from the quantization config.""" kv_algo_str = get_kv_cache_quant_algo_string(quant_cfg) if kv_algo_str is not None and kv_algo_str != "auto": # Only convert if we have a valid dtype string (not "auto" fallback) return STR_DTYPE_TO_TORCH_DTYPE[kv_algo_str] return None def resolve_kv_cache_dtype_string( kv_cache_dtype: str, model_config: ModelConfig ) -> str: """Resolve 'auto' kv_cache_dtype to the actual string value from model config. Returns the resolved cache_dtype string. """ if kv_cache_dtype != "auto": return kv_cache_dtype hf_cfg = getattr(model_config, "hf_config", None) if hf_cfg is not None: quant_cfg = getattr(hf_cfg, "quantization_config", None) if quant_cfg is not None: kv_algo_str = get_kv_cache_quant_algo_string(quant_cfg) if kv_algo_str is not None: return kv_algo_str # Default to auto (will be handled by downstream code) return "auto" def kv_cache_dtype_str_to_dtype( kv_cache_dtype: str, model_config: ModelConfig ) -> torch.dtype: if kv_cache_dtype == "auto": # Model config may not be specified for unit tests, default to float16 return model_config.dtype if model_config else torch.half return STR_DTYPE_TO_TORCH_DTYPE[kv_cache_dtype] def set_random_seed(seed: int | None) -> None: if seed is not None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) def create_kv_caches_with_random_flash( num_blocks: int, block_size: int, num_layers: int, num_heads: int, head_size: int, cache_dtype: str | torch.dtype | None, model_dtype: str | torch.dtype | None = None, seed: int | None = None, device: str | None = "cuda", cache_layout: str | None = "NHD", ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: set_random_seed(seed) dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype) generic_kv_cache_shape = (num_blocks, 2, block_size, num_heads, head_size) assert cache_layout in ("NHD", "HND") stride_order = (0, 1, 2, 3, 4) if cache_layout == "NHD" else (0, 1, 3, 2, 4) kv_cache_allocation_shape = tuple(generic_kv_cache_shape[i] for i in stride_order) scale = head_size**-0.5 key_caches: list[torch.Tensor] = [] value_caches: list[torch.Tensor] = [] for _ in range(num_layers): key_value_cache = torch.empty( size=kv_cache_allocation_shape, dtype=dtype, device=device ).permute(*stride_order) if cache_dtype in ["auto", "half", "bfloat16", "float"]: key_value_cache.uniform_(-scale, scale) elif cache_dtype == "fp8": _generate_random_fp8(key_value_cache, -scale, scale) else: raise ValueError(f"Does not support key cache of type {cache_dtype}") key_caches.append(key_value_cache[:, 0]) value_caches.append(key_value_cache[:, 1]) return key_caches, value_caches def create_kv_caches_with_random( num_blocks: int, block_size: int, num_layers: int, num_heads: int, head_size: int, cache_dtype: str | torch.dtype | None, model_dtype: str | torch.dtype | None = None, seed: int | None = None, device: str | None = "cuda", ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: if cache_dtype == "fp8" and head_size % 16: raise ValueError( f"Does not support key cache of type fp8 with head_size {head_size}" ) set_random_seed(seed) dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype) scale = head_size**-0.5 x = 16 // torch.tensor([], dtype=dtype).element_size() key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x) key_caches: list[torch.Tensor] = [] for _ in range(num_layers): key_cache = torch.empty(size=key_cache_shape, dtype=dtype, device=device) if cache_dtype in ["auto", "half", "bfloat16", "float"]: key_cache.uniform_(-scale, scale) elif cache_dtype == "fp8": _generate_random_fp8(key_cache, -scale, scale) else: raise ValueError(f"Does not support key cache of type {cache_dtype}") key_caches.append(key_cache) value_cache_shape = (num_blocks, num_heads, head_size, block_size) value_caches: list[torch.Tensor] = [] for _ in range(num_layers): value_cache = torch.empty(size=value_cache_shape, dtype=dtype, device=device) if cache_dtype in ["auto", "half", "bfloat16", "float"]: value_cache.uniform_(-scale, scale) elif cache_dtype == "fp8": _generate_random_fp8(value_cache, -scale, scale) else: raise ValueError(f"Does not support value cache of type {cache_dtype}") value_caches.append(value_cache) return key_caches, value_caches def async_tensor_h2d( data: list, dtype: torch.dtype, target_device: str | torch.device, pin_memory: bool, ) -> torch.Tensor: """Asynchronously create a tensor and copy it from host to device.""" t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device="cpu") return t.to(device=target_device, non_blocking=True) def make_ndarray_with_pad( x: list[list[T]], pad: T, dtype: npt.DTypeLike, *, max_len: int | None = None, ) -> npt.NDArray: """ Make a padded array from 2D inputs. The padding is applied to the end of each inner list until it reaches `max_len`. """ if max_len is None: # Unlike for most functions, map is faster than a genexpr over `len` max_len = max(map(len, x), default=0) padded_x = np.full((len(x), max_len), pad, dtype=dtype) for ind, blocktb in enumerate(x): assert len(blocktb) <= max_len padded_x[ind, : len(blocktb)] = blocktb return padded_x def make_tensor_with_pad( x: list[list[T]], pad: T, dtype: torch.dtype, *, max_len: int | None = None, device: str | torch.device | None = None, pin_memory: bool = False, ) -> torch.Tensor: """ Make a padded tensor from 2D inputs. The padding is applied to the end of each inner list until it reaches `max_len`. """ np_dtype = TORCH_DTYPE_TO_NUMPY_DTYPE[dtype] padded_x = make_ndarray_with_pad(x, pad, np_dtype, max_len=max_len) tensor = torch.from_numpy(padded_x).to(device) if pin_memory: tensor = tensor.pin_memory() return tensor prev_set_stream = torch.cuda.set_stream _current_stream_tls = threading.local() def _patched_set_stream(stream: torch.cuda.Stream) -> None: _current_stream_tls.value = stream prev_set_stream(stream) torch.cuda.set_stream = _patched_set_stream class _StreamPlaceholder: def __init__(self): self.synchronize = lambda: None def current_stream() -> torch.cuda.Stream: """ replace `torch.cuda.current_stream()` with `vllm.utils.current_stream()`. it turns out that `torch.cuda.current_stream()` is quite expensive, as it will construct a new stream object at each call. here we patch `torch.cuda.set_stream` to keep track of the current stream directly, so that we can avoid calling `torch.cuda.current_stream()`. the underlying hypothesis is that we do not call `torch._C._cuda_setStream` from C/C++ code. """ from vllm.platforms import current_platform if not hasattr(_current_stream_tls, "value") or _current_stream_tls.value is None: # when this function is called before any stream is set, # we return the default stream. # On ROCm using the default 0 stream in combination with RCCL # is hurting performance. # On CUDA, we capture and replay cudagraph on the same stream, # so we need to avoid using the default stream as well. The default # stream cannot be used for cudagraph capture, see # https://github.com/pytorch/pytorch/blob/42ad9edfb754743fdae3276ade43de000beb4f60/aten/src/ATen/cuda/CUDAGraph.cpp#L77 # for more details. Therefore, we create a dedicated stream per process. if current_platform.is_rocm() or current_platform.is_cuda(): # torch.cuda.set_stream here is the alias of _pathed_set_stream torch.cuda.set_stream(torch.cuda.Stream()) elif current_platform.is_cpu(): _current_stream_tls.value = _StreamPlaceholder() else: current_stream = current_platform.current_stream if current_stream is not None: _current_stream_tls.value = current_stream() else: raise ValueError( "Fail to set current stream, current platform " "may not support current_stream with torch API" ) return _current_stream_tls.value # Global auxiliary stream for running operations in background streams. # We have single global auxiliary stream to avoid an explosion of streams # for every layer (and make profiling look sane). # # aux_stream() is currently used for: # - MoE shared_expert overlap with router _aux_stream: torch.cuda.Stream | None = None def aux_stream() -> torch.cuda.Stream | None: """ Ensures aux_stream is initialized only once """ global _aux_stream from vllm.platforms import current_platform if _aux_stream is None and current_platform.is_cuda_alike(): _aux_stream = torch.cuda.Stream() return _aux_stream @lru_cache(maxsize=8) def _cuda_device_count_stateless(cuda_visible_devices: str | None = None) -> int: # Note: cuda_visible_devices is not used, but we keep it as an argument for # LRU Cache purposes. # Code below is based on # https://github.com/pytorch/pytorch/blob/ # c1cd946818442aca8c7f812b16d187ce1586c3bc/ # torch/cuda/__init__.py#L831C1-L831C17 import torch.cuda import torch.version from vllm.platforms import current_platform if not torch.cuda._is_compiled(): return 0 if current_platform.is_rocm(): # ROCm uses amdsmi instead of nvml for stateless device count # This requires a sufficiently modern version of Torch 2.4.0 raw_count = ( torch.cuda._device_count_amdsmi() if (hasattr(torch.cuda, "_device_count_amdsmi")) else -1 ) else: raw_count = torch.cuda._device_count_nvml() r = torch._C._cuda_getDeviceCount() if raw_count < 0 else raw_count return r def cuda_device_count_stateless() -> int: """Get number of CUDA devices, caching based on the value of CUDA_VISIBLE_DEVICES at the time of call. This should be used instead of torch.cuda.device_count() unless CUDA_VISIBLE_DEVICES has already been set to the desired value.""" # This can be removed and simply replaced with torch.cuda.get_device_count # after https://github.com/pytorch/pytorch/pull/122815 is released. return _cuda_device_count_stateless(envs.CUDA_VISIBLE_DEVICES) def weak_ref_tensor(tensor: Any) -> Any: """ Create a weak reference to a tensor. The new tensor will share the same data as the original tensor, but will not keep the original tensor alive. This ignores 0-size tensors as those don't allocate any memory. """ if isinstance(tensor, torch.Tensor) and tensor.numel() > 0: return torch.ops._C.weak_ref_tensor(tensor) else: return tensor def weak_ref_tensors( tensors: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor] | IntermediateTensors, ) -> torch.Tensor | list[Any] | tuple[Any] | Any: """ Convenience function to create weak references to tensors, for single tensor, list of tensors or tuple of tensors. """ if isinstance(tensors, torch.Tensor): return weak_ref_tensor(tensors) if isinstance(tensors, list): return [weak_ref_tensor(t) for t in tensors] if isinstance(tensors, tuple): return tuple(weak_ref_tensor(t) for t in tensors) # For IntermediateTensors used in pipeline parallelism from vllm.sequence import IntermediateTensors if isinstance(tensors, IntermediateTensors): ret = IntermediateTensors( {key: weak_ref_tensor(val) for key, val in tensors.tensors.items()} ) return ret raise ValueError("Invalid type for tensors") def get_accelerator_view_from_cpu_tensor(cpu_tensor: torch.Tensor) -> torch.Tensor: """ Get an accelerator view of a CPU tensor using Unified Virtual Addressing (UVA). """ from vllm.platforms import current_platform if current_platform.is_xpu(): assert cpu_tensor.is_pinned(), "CPU tensor must be pinned" return torch.ops._C.get_xpu_view_from_cpu_tensor(cpu_tensor) elif current_platform.is_cuda() or current_platform.is_rocm(): return torch.ops._C.get_cuda_view_from_cpu_tensor(cpu_tensor) else: raise ValueError( f"`get_accelerator_view_from_cpu_tensor` is currently " f"not supported in: {current_platform.device_name}" ) # Helper function used in testing. def _is_torch_equal_or_newer(torch_version: str, target: str) -> bool: return version.parse(torch_version) >= version.parse(target) def is_torch_equal_or_newer(target: str) -> bool: """Check if the installed torch version is >= the target version. Args: target: a version string, like "2.6.0". Returns: Whether the condition meets. """ try: return _is_torch_equal_or_newer(str(torch.__version__), target) except Exception: # Fallback to PKG-INFO to load the package info, needed by the doc gen. return Version(importlib.metadata.version("torch")) >= Version(target) def _is_torch_equal(target: str) -> bool: assert target.count(".") == 2 torch_version = str(torch.__version__) torch_version = version.parse(torch_version) # torch version is like "2.6.0.dev20240101" or "2.6.0.dev20240101+cpu" # or "2.6.0+cu128" but never "2.6.0.1" return ( torch_version >= version.parse(target) and version.parse(target + ".1") > torch_version ) def is_torch_equal(target: str) -> bool: """Check if the installed torch version is == the target version. Args: target: a version string, like "2.6.0". Returns: Whether the condition meets. """ try: return _is_torch_equal(target) except Exception: return Version(importlib.metadata.version("torch")) == Version(target) HAS_OPAQUE_TYPE = is_torch_equal_or_newer("2.11.0.dev") if HAS_OPAQUE_TYPE: from torch._opaque_base import OpaqueBase else: OpaqueBase = object # type: ignore[misc, assignment] class ModuleName(OpaqueBase): # type: ignore[misc] """Wraps a module name string for use as a torch opaque type. When torch >= 2.11, this is registered as a hoisted value-type opaque object so that torch.compile lifts it as a graph input instead of baking it as a constant. This avoids per-layer recompilation for MOE ops. """ def __init__(self, value: str): self.value = value def __eq__(self, other): return isinstance(other, ModuleName) and self.value == other.value def __hash__(self): return hash(self.value) def __fx_repr__(self): return (f"ModuleName({self.value!r})", {ModuleName}) if HAS_OPAQUE_TYPE: from torch._library.opaque_object import register_opaque_type register_opaque_type(ModuleName, typ="value", hoist=True) # Supports xccl with PyTorch versions >= 2.8.0.dev for XPU platform def supports_xccl() -> bool: return torch.distributed.is_xccl_available() # Supports XPU Graph with PyTorch versions >= 2.11.0.dev for XPU platform def supports_xpu_graph() -> bool: return is_torch_equal_or_newer("2.11.0.dev") # create a library to hold the custom op vllm_lib = Library("vllm", "FRAGMENT") # noqa def direct_register_custom_op( op_name: str, op_func: Callable, mutates_args: list[str] | None = None, fake_impl: Callable | None = None, target_lib: Library | None = None, dispatch_key: str | None = None, tags: tuple[torch.Tag, ...] = (), ): """ `torch.library.custom_op` can have significant overhead because it needs to consider complicated dispatching logic. This function directly registers a custom op and dispatches it to the CUDA backend. See https://gist.github.com/youkaichao/ecbea9ec9fc79a45d2adce1784d7a9a5 for more details. By default, the custom op is registered to the vLLM library. If you want to register it to a different library, you can pass the library object to the `target_lib` argument. IMPORTANT: the lifetime of the operator is tied to the lifetime of the library object. If you want to bind the operator to a different library, make sure the library object is alive when the operator is used. """ if mutates_args is None: mutates_args = [] if dispatch_key is None: from vllm.platforms import current_platform dispatch_key = current_platform.dispatch_key schema_str = infer_schema(op_func, mutates_args=mutates_args) my_lib = target_lib or vllm_lib my_lib.define(op_name + schema_str, tags=tags) my_lib.impl(op_name, op_func, dispatch_key=dispatch_key) if fake_impl is not None: my_lib._register_fake(op_name, fake_impl)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/torch_utils.py", "license": "Apache License 2.0", "lines": 669, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/utils/mem_constants.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project MB_bytes = 1_000_000 """The number of bytes in one megabyte (MB).""" MiB_bytes = 1 << 20 """The number of bytes in one mebibyte (MiB).""" GB_bytes = 1_000_000_000 """The number of bytes in one gigabyte (GB).""" GiB_bytes = 1 << 30 """The number of bytes in one gibibyte (GiB)."""
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/mem_constants.py", "license": "Apache License 2.0", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/utils/mem_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import gc import time from collections.abc import Generator from dataclasses import dataclass, field from functools import cache import psutil import torch import torch.types from vllm.platforms import current_platform from .mem_constants import GiB_bytes, MiB_bytes def format_mib(b: int) -> str: return f"{round(b / MiB_bytes, 2)}" def format_gib(b: int) -> str: return f"{round(b / GiB_bytes, 2)}" @cache def get_max_shared_memory_bytes(gpu: int = 0) -> int: """Returns the maximum shared memory per thread block in bytes.""" from vllm import _custom_ops as ops max_shared_mem = ops.get_max_shared_memory_per_block_device_attribute(gpu) # value 0 will cause MAX_SEQ_LEN become negative and test_attention.py # will fail assert max_shared_mem > 0, "max_shared_mem cannot be zero" return int(max_shared_mem) def get_cpu_memory() -> int: """Returns the total CPU memory of the node in bytes.""" return psutil.virtual_memory().total class DeviceMemoryProfiler: def __init__(self, device: torch.types.Device | None = None): self.device = device def current_memory_usage(self) -> float: # Return the memory usage in bytes. gc.collect() return current_platform.get_current_memory_usage(self.device) def __enter__(self): self.initial_memory = self.current_memory_usage() # This allows us to call methods of the context manager if needed return self def __exit__(self, exc_type, exc_val, exc_tb): self.final_memory = self.current_memory_usage() self.consumed_memory = self.final_memory - self.initial_memory # Force garbage collection gc.collect() @dataclass class MemorySnapshot: """Memory snapshot.""" torch_peak: int = 0 free_memory: int = 0 total_memory: int = 0 cuda_memory: int = 0 torch_memory: int = 0 non_torch_memory: int = 0 timestamp: float = 0.0 device: torch.types.Device = None auto_measure: bool = True def __post_init__(self) -> None: if self.device is None: device_fn = current_platform.current_device assert device_fn is not None self.device_ = torch.device(device_fn()) else: self.device_ = torch.device(self.device) if self.auto_measure: self.measure() def measure(self) -> None: device = self.device_ # we measure the torch peak memory usage via allocated_bytes, # rather than `torch.cuda.memory_reserved()` . # After `torch.cuda.reset_peak_memory_stats()`, # `torch.cuda.memory_reserved()` will keep growing, and only shrink # when we call `torch.cuda.empty_cache()` or OOM happens. self.torch_peak = current_platform.memory_stats(device).get( "allocated_bytes.all.peak", 0 ) self.free_memory, self.total_memory = current_platform.mem_get_info(device) shared_sysmem_device_mem_sms = ((8, 7), (11, 0), (12, 1)) # Orin, Thor, Spark if ( current_platform.is_cuda() and current_platform.get_device_capability(device.index) in shared_sysmem_device_mem_sms ): # On UMA (Orin, Thor and Spark) platform, # where both CPU and GPU rely on system memory, # the cudaMemGetInfo function shows the amount of free system memory # rather than what’s actually available. # In the case, # torch.cuda.mem_get_info() only reports "free" memory, # which can be lower than what is actually # available due to not including cache memory. # There’s also a comprehensive reference page # that explains how you can compute the proper value yourself. # https://docs.nvidia.com/cuda/cuda-for-tegra-appnote/#estimating-total-allocatable-device-memory-on-an-integrated-gpu-device self.free_memory = psutil.virtual_memory().available self.cuda_memory = self.total_memory - self.free_memory # torch.cuda.memory_reserved() is how many bytes # PyTorch gets from cuda (by calling cudaMalloc, etc.) # this is used to measure the non-torch memory usage self.torch_memory = current_platform.memory_reserved(device) self.non_torch_memory = self.cuda_memory - self.torch_memory self.timestamp = time.time() def __sub__(self, other: "MemorySnapshot") -> "MemorySnapshot": if self.device_ != other.device_: raise ValueError( "The two snapshots should be from the same device! " f"Found: {self.device_} vs. {other.device_}" ) return MemorySnapshot( torch_peak=self.torch_peak - other.torch_peak, free_memory=self.free_memory - other.free_memory, total_memory=self.total_memory - other.total_memory, cuda_memory=self.cuda_memory - other.cuda_memory, torch_memory=self.torch_memory - other.torch_memory, non_torch_memory=self.non_torch_memory - other.non_torch_memory, timestamp=self.timestamp - other.timestamp, device=self.device_, auto_measure=False, ) def __repr__(self) -> str: return ( f"torch_peak={format_gib(self.torch_peak)}GiB, " f"free_memory={format_gib(self.free_memory)}GiB, " f"total_memory={format_gib(self.total_memory)}GiB, " f"{current_platform.device_name}_memory={format_gib(self.cuda_memory)}GiB, " f"torch_memory={format_gib(self.torch_memory)}GiB, " f"non_torch_memory={format_gib(self.non_torch_memory)}GiB, " f"timestamp={self.timestamp}, " f"auto_measure={self.auto_measure}" ) @dataclass class MemoryProfilingResult: """Memory profiling result. All numbers are in bytes.""" non_kv_cache_memory: int = 0 torch_peak_increase: int = 0 non_torch_increase: int = 0 weights_memory: int = 0 before_create: MemorySnapshot = field(default_factory=MemorySnapshot) profile_time: float = 0.0 def __post_init__(self) -> None: device = self.before_create.device_ self.before_profile = MemorySnapshot(device=device, auto_measure=False) self.after_profile = MemorySnapshot(device=device, auto_measure=False) def __repr__(self) -> str: return ( f"Memory profiling takes {self.profile_time:.2f} seconds. " f"Total non KV cache memory: " f"{format_gib(self.non_kv_cache_memory)}GiB; " f"torch peak memory increase: " f"{format_gib(self.torch_peak_increase)}GiB; " f"non-torch forward increase memory: " f"{format_gib(self.non_torch_increase)}GiB; " f"weights memory: {format_gib(self.weights_memory)}GiB." ) @contextlib.contextmanager def memory_profiling( baseline_snapshot: MemorySnapshot, weights_memory: int = 0, ) -> Generator[MemoryProfilingResult, None, None]: """ Memory profiling context manager. baseline_snapshot: the memory snapshot before the current vLLM instance. weights_memory: memory used by PyTorch when loading the model weights. Note that, before loading the model weights, we also initialize the device and distributed environment, which may consume some memory. This part is not included in the weights_memory because PyTorch does not control it. The memory in one GPU can be classified into 3 categories: 1. memory used by anything other than the current vLLM instance. 2. memory used by torch in the current vLLM instance. 3. memory used in the current vLLM instance, but not by torch. A quantitive example: Before creating the current vLLM instance: category 1: 1 GiB category 2: 0 GiB category 3: 0 GiB After creating the current vLLM instance and loading the model, (i.e. before profiling): category 1: 1 GiB category 2: 2 GiB (model weights take 2 GiB) category 3: 0.5 GiB (memory used by NCCL) During profiling (peak): category 1: 1 GiB category 2: 4 GiB (peak activation tensors take 2 GiB) category 3: 1 GiB (memory used by NCCL + buffers for some attention backends) After profiling: category 1: 1 GiB category 2: 3 GiB (after garbage-collecting activation tensors) category 3: 1 GiB (memory used by NCCL + buffers for some attention backends) In this case, non-kv cache takes 5 GiB in total, including: a. 2 GiB used by the model weights (category 2) b. 2 GiB reserved for the peak activation tensors (category 2) c. 1 GiB used by non-torch components (category 3) The memory used for loading weights (a.) is directly given from the argument `weights_memory`. The increase of `torch.cuda.memory_stats()["allocated_bytes.all.peak"]` during profiling gives (b.). The increase of `non_torch_memory` from creating the current vLLM instance until after profiling to get (c.). """ gc.collect() current_platform.empty_cache() current_platform.reset_peak_memory_stats(baseline_snapshot.device_) result = MemoryProfilingResult( before_create=baseline_snapshot, # the part of memory used for holding the model weights weights_memory=weights_memory, ) result.before_profile.measure() yield result gc.collect() current_platform.empty_cache() result.after_profile.measure() diff_profile = result.after_profile - result.before_profile diff_from_create = result.after_profile - result.before_create result.torch_peak_increase = diff_profile.torch_peak result.non_torch_increase = diff_from_create.non_torch_memory result.profile_time = diff_profile.timestamp non_torch_memory = result.non_torch_increase peak_activation_memory = result.torch_peak_increase result.non_kv_cache_memory = ( non_torch_memory + peak_activation_memory + result.weights_memory )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/mem_utils.py", "license": "Apache License 2.0", "lines": 222, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/entrypoints/openai/test_gptoss_structural_tags_integration.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Integration tests for GPT-OSS structural tags functionality (PR #25515).""" import json from unittest.mock import Mock import pytest from vllm.entrypoints.mcp.tool_server import ToolServer from vllm.reasoning.gptoss_reasoning_parser import ( GptOssReasoningParser, ) from vllm.sampling_params import StructuredOutputsParams class TestGptOssStructuralTagsIntegration: """Integration tests for structural tags in GPT-OSS tool calls.""" @pytest.fixture def mock_tokenizer(self): """Create a mock tokenizer.""" tokenizer = Mock() tokenizer.encode = Mock(return_value=[1, 2, 3, 4, 5]) tokenizer.vocab = {"<|end|>": 6} return tokenizer @pytest.fixture def gptoss_parser(self, mock_tokenizer): """Create a real GptOssReasoningParser instance.""" return GptOssReasoningParser(mock_tokenizer) @pytest.fixture def tool_server_with_python(self): """Create a tool server with Python tool enabled.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(side_effect=lambda tool: tool == "python") return tool_server @pytest.fixture def tool_server_empty(self): """Create a tool server with no tools.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(return_value=False) return tool_server def test_end_to_end_no_tools(self, gptoss_parser): """Test end-to-end flow when no tools are available.""" # Test the parser directly result = gptoss_parser.prepare_structured_tag(None, None) parsed_result = json.loads(result) # Verify basic structure assert parsed_result["type"] == "structural_tag" assert parsed_result["format"]["type"] == "triggered_tags" assert len(parsed_result["format"]["tags"]) == 1 # Verify only analysis channel is allowed analysis_tag = parsed_result["format"]["tags"][0] assert analysis_tag["begin"] == "<|channel|>analysis<|message|>" assert analysis_tag["content"]["type"] == "any_text" assert analysis_tag["end"] == "<|end|>" # Verify triggers assert parsed_result["format"]["triggers"] == ["<|channel|>analysis"] assert parsed_result["format"]["stop_after_first"] is False def test_end_to_end_with_python_tool(self, gptoss_parser, tool_server_with_python): """Test end-to-end flow with Python tool enabled.""" result = gptoss_parser.prepare_structured_tag(None, tool_server_with_python) parsed_result = json.loads(result) # Should have analysis tag + 2 python tags assert len(parsed_result["format"]["tags"]) == 3 # Verify all expected tags are present tag_begins = [tag["begin"] for tag in parsed_result["format"]["tags"]] expected_begins = [ "<|channel|>analysis<|message|>", "<|channel|>commentary to=python", "<|channel|>analysis to=python", ] for expected in expected_begins: assert expected in tag_begins # Verify triggers include commentary assert "<|channel|>analysis" in parsed_result["format"]["triggers"] assert "<|channel|>commentary to=" in parsed_result["format"]["triggers"] def test_structured_outputs_params_integration( self, gptoss_parser, tool_server_with_python ): """Test integration with StructuredOutputsParams.""" # Generate structural tag structural_tag = gptoss_parser.prepare_structured_tag( None, tool_server_with_python ) # Create StructuredOutputsParams params = StructuredOutputsParams(structural_tag=structural_tag) # Verify the tag is properly stored and accessible assert params.structural_tag == structural_tag # Verify the tag is valid JSON parsed_tag = json.loads(params.structural_tag) assert parsed_tag["type"] == "structural_tag" @pytest.mark.parametrize( "browser, python, container, expected_tags", [ # No tools (False, False, False, 1), # Single tool (True, False, False, 3), # Multiple tools (True, True, False, 5), # All tools (True, True, True, 7), ], ) def test_tool_server_interaction_flow( self, gptoss_parser, browser, python, container, expected_tags ): """Test the complete tool server interaction flow.""" # Create a mock ToolServer tool_server = Mock(spec=ToolServer) # Simulate tool availability based on parameters tool_server.has_tool = Mock( side_effect=lambda tool: { "browser": browser, "python": python, "container": container, }.get(tool, False) ) # Run the parser and verify results result = gptoss_parser.prepare_structured_tag(None, tool_server) parsed_result = json.loads(result) # Validate number of tags assert len(parsed_result["format"]["tags"]) == expected_tags # Verify tool-specific tags exist for enabled tools tag_begins = [tag["begin"] for tag in parsed_result["format"]["tags"]] for tool, enabled in { "browser": browser, "python": python, "container": container, }.items(): if enabled: assert f"<|channel|>commentary to={tool}" in tag_begins assert f"<|channel|>analysis to={tool}" in tag_begins def test_original_tag_preservation(self, gptoss_parser, tool_server_with_python): """Test that original tags are preserved when provided.""" original_tag = '{"type": "custom_tag", "data": "preserved"}' result = gptoss_parser.prepare_structured_tag( original_tag, tool_server_with_python ) # Should return original tag unchanged assert result == original_tag @pytest.mark.parametrize( "tools", [ [], ["browser"], ["python"], ["container"], ["browser", "python"], ["browser", "container"], ["python", "container"], ["browser", "python", "container"], ], ) def test_json_validity_comprehensive(self, gptoss_parser, tools): """Test JSON validity across all possible tool combinations.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(side_effect=lambda tool: tool in tools) result = gptoss_parser.prepare_structured_tag(None, tool_server) # Should be valid JSON parsed_result = json.loads(result) # Should have correct structure assert parsed_result["type"] == "structural_tag" assert "format" in parsed_result assert "tags" in parsed_result["format"] assert "triggers" in parsed_result["format"] # Tag count should be: 1 (analysis) + 2 * len(tools) expected_tag_count = 1 + (2 * len(tools)) assert len(parsed_result["format"]["tags"]) == expected_tag_count def test_error_handling_invalid_tool_server(self, gptoss_parser): """Test error handling with invalid tool server.""" # Tool server that raises exceptions tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(side_effect=Exception("Tool server error")) # Should handle gracefully and still return a valid tag with pytest.raises(Exception, match="Tool server error"): gptoss_parser.prepare_structured_tag(None, tool_server) def test_concurrent_requests_isolation(self, gptoss_parser): """Test that concurrent requests don't interfere with each other.""" # Simulate concurrent requests with different tool servers tool_server_1 = Mock(spec=ToolServer) tool_server_1.has_tool = Mock(side_effect=lambda tool: tool == "python") tool_server_2 = Mock(spec=ToolServer) tool_server_2.has_tool = Mock(side_effect=lambda tool: tool == "browser") # Generate tags concurrently result_1 = gptoss_parser.prepare_structured_tag(None, tool_server_1) result_2 = gptoss_parser.prepare_structured_tag(None, tool_server_2) # Parse results parsed_1 = json.loads(result_1) parsed_2 = json.loads(result_2) # Verify they have different tool configurations tags_1 = [tag["begin"] for tag in parsed_1["format"]["tags"]] tags_2 = [tag["begin"] for tag in parsed_2["format"]["tags"]] # Result 1 should have python tags assert "<|channel|>commentary to=python" in tags_1 assert "<|channel|>commentary to=browser" not in tags_1 # Result 2 should have browser tags assert "<|channel|>commentary to=browser" in tags_2 assert "<|channel|>commentary to=python" not in tags_2 def test_tag_format_consistency(self, gptoss_parser): """Test that all generated tags follow consistent format.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock( side_effect=lambda tool: tool in ["python", "browser"] ) result = gptoss_parser.prepare_structured_tag(None, tool_server) parsed_result = json.loads(result) # Verify all tags have required fields for tag in parsed_result["format"]["tags"]: assert "begin" in tag assert "content" in tag assert "end" in tag assert tag["content"]["type"] == "any_text" assert tag["end"] == "<|end|>" # Verify begin format assert tag["begin"].startswith("<|channel|>") def test_trigger_configuration(self, gptoss_parser): """Test trigger configuration for different tool setups.""" # Test with no tools result_no_tools = gptoss_parser.prepare_structured_tag(None, None) parsed_no_tools = json.loads(result_no_tools) assert parsed_no_tools["format"]["triggers"] == ["<|channel|>analysis"] # Test with tools tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(side_effect=lambda tool: tool == "python") result_with_tools = gptoss_parser.prepare_structured_tag(None, tool_server) parsed_with_tools = json.loads(result_with_tools) expected_triggers = ["<|channel|>analysis", "<|channel|>commentary to="] assert set(parsed_with_tools["format"]["triggers"]) == set(expected_triggers)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/entrypoints/openai/test_gptoss_structural_tags_integration.py", "license": "Apache License 2.0", "lines": 224, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/v1/structured_output/test_gptoss_structural_tags.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Unit tests for GPT-OSS structural tag support in reasoning (PR #25515).""" import json from unittest.mock import Mock import pytest from vllm.entrypoints.mcp.tool_server import ToolServer from vllm.reasoning.gptoss_reasoning_parser import ( GptOssReasoningParser, from_builtin_tool_to_tag, no_func_reaonsing_tag, tag_with_builtin_funcs, ) class TestGptOssReasoningParser: """Test cases for GptOssReasoningParser structural tag functionality.""" @pytest.fixture def mock_tokenizer(self): """Create a mock tokenizer for testing.""" tokenizer = Mock() tokenizer.encode = Mock(return_value=[1, 2, 3, 4, 5]) tokenizer.vocab = {"<|end|>": 6} return tokenizer @pytest.fixture def reasoning_parser(self, mock_tokenizer): """Create a GptOssReasoningParser instance.""" return GptOssReasoningParser(mock_tokenizer) @pytest.fixture def mock_tool_server_empty(self): """Create a mock ToolServer with no tools.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(return_value=False) return tool_server @pytest.fixture def mock_tool_server_with_browser(self): """Create a mock ToolServer with browser tool.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(side_effect=lambda tool: tool == "browser") return tool_server @pytest.fixture def mock_tool_server_with_all_tools(self): """Create a mock ToolServer with all builtin tools.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock( side_effect=lambda tool: tool in ["browser", "python", "container"] ) return tool_server def test_prepare_structured_tag_no_tool_server(self, reasoning_parser): """Test prepare_structured_tag with no tool server.""" result = reasoning_parser.prepare_structured_tag(None, None) expected = json.dumps(no_func_reaonsing_tag) assert result == expected # Verify the structure is correct parsed = json.loads(result) assert parsed["type"] == "structural_tag" assert parsed["format"]["type"] == "triggered_tags" assert len(parsed["format"]["tags"]) == 1 assert parsed["format"]["tags"][0]["begin"] == "<|channel|>analysis<|message|>" assert parsed["format"]["triggers"] == ["<|channel|>analysis"] def test_prepare_structured_tag_with_all_tools( self, reasoning_parser, mock_tool_server_with_all_tools ): """Test prepare_structured_tag with all builtin tools.""" result = reasoning_parser.prepare_structured_tag( None, mock_tool_server_with_all_tools ) parsed = json.loads(result) # Should have analysis tag + tags for all 3 tools (2 tags each) assert len(parsed["format"]["tags"]) == 7 # 1 analysis + 6 tool tags # Check all tool tags are present tag_begins = [tag["begin"] for tag in parsed["format"]["tags"]] for tool in ["browser", "python", "container"]: assert f"<|channel|>commentary to={tool}" in tag_begins assert f"<|channel|>analysis to={tool}" in tag_begins def test_prepare_structured_tag_with_original_tag(self, reasoning_parser): """Test prepare_structured_tag when original_tag is provided.""" original_tag = '{"custom": "tag"}' result = reasoning_parser.prepare_structured_tag(original_tag, None) # Should return the original tag unchanged assert result == original_tag def test_from_builtin_tool_to_tag(self): """Test from_builtin_tool_to_tag function.""" tags = from_builtin_tool_to_tag("python") assert len(tags) == 2 assert tags[0]["begin"] == "<|channel|>commentary to=python" assert tags[0]["content"]["type"] == "any_text" assert tags[0]["end"] == "<|end|>" assert tags[1]["begin"] == "<|channel|>analysis to=python" assert tags[1]["content"]["type"] == "any_text" assert tags[1]["end"] == "<|end|>" def test_tag_with_builtin_funcs(self): """Test tag_with_builtin_funcs function.""" builtin_tools = ["browser", "python"] result = tag_with_builtin_funcs(no_func_reaonsing_tag, builtin_tools) assert result["type"] == "structural_tag" # Should have original analysis tag + 2 tags per tool assert len(result["format"]["tags"]) == 5 # 1 + 2*2 # Should have added commentary trigger assert "<|channel|>commentary to=" in result["format"]["triggers"] assert "<|channel|>analysis" in result["format"]["triggers"] def test_tag_structure_invariants(self): """Test that the basic tag structure follows expected format.""" # Test the base no_func_reaonsing_tag structure assert no_func_reaonsing_tag["type"] == "structural_tag" assert no_func_reaonsing_tag["format"]["type"] == "triggered_tags" assert no_func_reaonsing_tag["format"]["stop_after_first"] is False # Verify analysis tag structure analysis_tag = no_func_reaonsing_tag["format"]["tags"][0] assert analysis_tag["begin"] == "<|channel|>analysis<|message|>" assert analysis_tag["content"]["type"] == "any_text" assert analysis_tag["end"] == "<|end|>" def test_json_serialization_valid( self, reasoning_parser, mock_tool_server_with_all_tools ): """Test that all generated tags produce valid JSON.""" # Test with no tool server result1 = reasoning_parser.prepare_structured_tag(None, None) json.loads(result1) # Should not raise # Test with empty tool server empty_server = Mock(spec=ToolServer) empty_server.has_tool = Mock(return_value=False) result2 = reasoning_parser.prepare_structured_tag(None, empty_server) json.loads(result2) # Should not raise # Test with tools result3 = reasoning_parser.prepare_structured_tag( None, mock_tool_server_with_all_tools ) json.loads(result3) # Should not raise @pytest.mark.parametrize("tool_name", ["browser", "python", "container"]) def test_single_tool_integration(self, reasoning_parser, tool_name): """Test integration with individual tools.""" tool_server = Mock(spec=ToolServer) tool_server.has_tool = Mock(side_effect=lambda tool: tool == tool_name) result = reasoning_parser.prepare_structured_tag(None, tool_server) parsed = json.loads(result) # Should have 1 analysis + 2 tool-specific tags assert len(parsed["format"]["tags"]) == 3 tag_begins = [tag["begin"] for tag in parsed["format"]["tags"]] assert f"<|channel|>commentary to={tool_name}" in tag_begins assert f"<|channel|>analysis to={tool_name}" in tag_begins
{ "repo_id": "vllm-project/vllm", "file_path": "tests/v1/structured_output/test_gptoss_structural_tags.py", "license": "Apache License 2.0", "lines": 139, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/v1/structured_output/test_reasoning_structured_output.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Unit tests for reasoning-aware structured output functionality (PR #25515).""" from unittest.mock import Mock import pytest from vllm.config import ModelConfig, SchedulerConfig, VllmConfig from vllm.reasoning import ReasoningParser from vllm.v1.request import Request from vllm.v1.structured_output import StructuredOutputManager class TestReasoningStructuredOutput: """Test reasoning-aware structured output functionality.""" @pytest.fixture def mock_model_config(self): """Create a mock ModelConfig.""" config = Mock(spec=ModelConfig) config.skip_tokenizer_init = True # Skip tokenizer init to avoid network calls config.get_vocab_size = Mock(return_value=50000) # Add missing runner_type attribute that tokenizer initialization expects config.runner_type = "generate" # Add other attributes that tokenizer initialization might need config.tokenizer = "test-tokenizer" config.tokenizer_mode = "auto" config.trust_remote_code = False config.tokenizer_revision = None return config @pytest.fixture def mock_scheduler_config(self): """Create a mock SchedulerConfig.""" config = Mock(spec=SchedulerConfig) config.max_num_seqs = 128 return config @pytest.fixture def mock_vllm_config(self, mock_model_config, mock_scheduler_config): """Create a mock VllmConfig.""" config = Mock(spec=VllmConfig) config.model_config = mock_model_config config.scheduler_config = mock_scheduler_config config.structured_outputs_config = Mock() config.structured_outputs_config.reasoning_parser = None config.structured_outputs_config.enable_in_reasoning = False config.speculative_config = None return config @pytest.fixture def mock_reasoning_parser(self): """Create a mock ReasoningParser.""" parser = Mock(spec=ReasoningParser) parser.is_reasoning_end = Mock(return_value=False) return parser @pytest.fixture def mock_request_with_structured_output(self): """Create a mock request with structured output.""" request = Mock(spec=Request) request.structured_output_request = Mock() request.structured_output_request.reasoning_ended = None request.structured_output_request.grammar = Mock() request.structured_output_request.grammar.is_terminated = Mock( return_value=False ) request.use_structured_output = True request.prompt_token_ids = [1, 2, 3, 4, 5] request.all_token_ids = [1, 2, 3, 4, 5, 6, 7, 8] request.num_computed_tokens = 5 request.num_output_placeholders = 0 return request def test_should_fill_bitmask_with_enable_in_reasoning( self, mock_vllm_config, mock_request_with_structured_output ): """Test should_fill_bitmask when enable_in_reasoning is True.""" # Enable enable_in_reasoning mock_vllm_config.structured_outputs_config.enable_in_reasoning = True manager = StructuredOutputManager(mock_vllm_config) # Should always return True when enable_in_reasoning is enabled result = manager.should_fill_bitmask(mock_request_with_structured_output) assert result is True def test_should_fill_bitmask_without_enable_in_reasoning( self, mock_vllm_config, mock_request_with_structured_output, mock_reasoning_parser, ): """Test should_fill_bitmask when enable_in_reasoning is False.""" # Keep enable_in_reasoning as False (default) config = mock_vllm_config.structured_outputs_config assert config.enable_in_reasoning is False manager = StructuredOutputManager(mock_vllm_config) manager.reasoner = mock_reasoning_parser # Mock reasoning not ended mock_reasoning_parser.is_reasoning_end.return_value = False result = manager.should_fill_bitmask(mock_request_with_structured_output) # Should set reasoning_ended and return its value assert ( mock_request_with_structured_output.structured_output_request.reasoning_ended is False ) assert result is False def test_should_fill_bitmask_no_reasoner( self, mock_vllm_config, mock_request_with_structured_output ): """Test should_fill_bitmask when no reasoner is configured.""" manager = StructuredOutputManager(mock_vllm_config) manager.reasoner = None result = manager.should_fill_bitmask(mock_request_with_structured_output) # Should default to True when no reasoner assert result is True def test_should_advance_with_enable_in_reasoning( self, mock_vllm_config, mock_request_with_structured_output, mock_reasoning_parser, ): """Test should_advance when enable_in_reasoning is True.""" # Enable enable_in_reasoning mock_vllm_config.structured_outputs_config.enable_in_reasoning = True manager = StructuredOutputManager(mock_vllm_config) manager.reasoner = mock_reasoning_parser # Should always return True when enable_in_reasoning is enabled result = manager.should_advance(mock_request_with_structured_output) assert result is True def test_should_advance_reasoning_not_ended( self, mock_vllm_config, mock_request_with_structured_output, mock_reasoning_parser, ): """Test should_advance when reasoning has not ended.""" manager = StructuredOutputManager(mock_vllm_config) manager.reasoner = mock_reasoning_parser # Set reasoning as not ended ( mock_request_with_structured_output.structured_output_request ).reasoning_ended = False mock_reasoning_parser.is_reasoning_end.return_value = False result = manager.should_advance(mock_request_with_structured_output) # Should return False since reasoning hasn't ended assert result is False def test_should_advance_reasoning_just_ended( self, mock_vllm_config, mock_request_with_structured_output, mock_reasoning_parser, ): """Test should_advance when reasoning ends in current step.""" manager = StructuredOutputManager(mock_vllm_config) manager.reasoner = mock_reasoning_parser # Set reasoning as not ended initially, but ends in this step ( mock_request_with_structured_output.structured_output_request ).reasoning_ended = False mock_reasoning_parser.is_reasoning_end.return_value = True result = manager.should_advance(mock_request_with_structured_output) # Should set reasoning_ended to True but return False for this step assert ( mock_request_with_structured_output.structured_output_request.reasoning_ended is True ) assert result is False def test_should_advance_reasoning_already_ended( self, mock_vllm_config, mock_request_with_structured_output, mock_reasoning_parser, ): """Test should_advance when reasoning has already ended.""" manager = StructuredOutputManager(mock_vllm_config) manager.reasoner = mock_reasoning_parser # Set reasoning as already ended ( mock_request_with_structured_output.structured_output_request ).reasoning_ended = True result = manager.should_advance(mock_request_with_structured_output) # Should return True since reasoning has ended assert result is True
{ "repo_id": "vllm-project/vllm", "file_path": "tests/v1/structured_output/test_reasoning_structured_output.py", "license": "Apache License 2.0", "lines": 172, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/model_executor/models/lightonocr.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Iterable, Mapping, Sequence from typing import TypeVar import torch import torch.nn as nn from transformers import ( BatchFeature, PixtralVisionConfig, ) from vllm.config import VllmConfig from vllm.model_executor.models.mistral3 import ( Mistral3DummyInputsBuilder, Mistral3ForConditionalGeneration, Mistral3MultiModalProjector, Mistral3ProcessingInfo, _build_mistral3_info, init_vision_tower_for_llava, ) from vllm.model_executor.models.pixtral import PixtralHFEncoderInfo from vllm.model_executor.models.utils import ( AutoWeightsLoader, WeightsMapper, init_vllm_registered_model, maybe_prefix, ) from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.cache import BaseMultiModalProcessorCache from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems from vllm.multimodal.parse import ImageProcessorItems, MultiModalDataItems from vllm.multimodal.processing import ( BaseDummyInputsBuilder, BaseMultiModalProcessor, PromptReplacement, PromptUpdate, PromptUpdateDetails, ) _I = TypeVar("_I", bound=Mistral3ProcessingInfo) class LightOnOCRMultiModalProcessor(BaseMultiModalProcessor[Mistral3ProcessingInfo]): def _call_hf_processor( self, prompt: str, mm_data: Mapping[str, object], mm_kwargs: Mapping[str, object], tok_kwargs: Mapping[str, object], ) -> BatchFeature: processed_outputs = super()._call_hf_processor( prompt=prompt, mm_data=mm_data, mm_kwargs=mm_kwargs, tok_kwargs=tok_kwargs, ) # NOTE: LightOnOCR does not use break/end tokens, so we remove them here. input_ids = processed_outputs.get("input_ids") if input_ids is not None: processor = self.info.get_hf_processor() tokenizer = self.info.get_tokenizer() vocab = tokenizer.get_vocab() break_id = vocab.get(processor.image_break_token) end_id = vocab.get(processor.image_end_token) # create mask to remove break/end tokens keep_mask = ~torch.isin( input_ids, torch.tensor([break_id, end_id]), ) processed_outputs["input_ids"] = input_ids[keep_mask].unsqueeze(0) if "attention_mask" in processed_outputs: processed_outputs["attention_mask"] = processed_outputs[ "attention_mask" ][keep_mask].unsqueeze(0) # un-pad pixel_values per-image so caches remain independent. pixel_values = processed_outputs.get("pixel_values") if pixel_values is not None: image_sizes = processed_outputs["image_sizes"] assert len(pixel_values) == len(image_sizes) processed_outputs["pixel_values"] = [ p[:, :h, :w] for p, (h, w) in zip(pixel_values, image_sizes) ] return processed_outputs def _get_mm_fields_config( self, hf_inputs: BatchFeature, hf_processor_mm_kwargs: Mapping[str, object], ) -> Mapping[str, MultiModalFieldConfig]: return dict( pixel_values=MultiModalFieldConfig.batched("image"), image_embeds=MultiModalFieldConfig.batched("image"), ) def _get_prompt_updates( self, mm_items: MultiModalDataItems, hf_processor_mm_kwargs: Mapping[str, object], out_mm_kwargs: MultiModalKwargsItems, ) -> Sequence[PromptUpdate]: hf_config = self.info.get_hf_config() image_token_id = hf_config.image_token_index assert isinstance(hf_config.vision_config, PixtralVisionConfig) encoder_info = PixtralHFEncoderInfo(hf_config) def replace(item_idx: int): images = mm_items.get_items("image", ImageProcessorItems) size = images.get_image_size(item_idx) ncols, nrows = encoder_info.get_patch_grid_size( image_width=size.width, image_height=size.height ) # break/end tokens are not used in LightOnOCR tokens = [image_token_id] * (ncols * nrows) return PromptUpdateDetails.select_token_id(tokens, image_token_id) return [ PromptReplacement( modality="image", target=[image_token_id], replacement=replace ) ] def _build_LightOnOCR_processor( info: _I, dummy_inputs: BaseDummyInputsBuilder[_I], *, cache: BaseMultiModalProcessorCache | None = None, ): assert isinstance(info, Mistral3ProcessingInfo) return LightOnOCRMultiModalProcessor(info, dummy_inputs, cache=cache) @MULTIMODAL_REGISTRY.register_processor( _build_LightOnOCR_processor, info=_build_mistral3_info, dummy_inputs=Mistral3DummyInputsBuilder, ) class LightOnOCRForConditionalGeneration(Mistral3ForConditionalGeneration): hf_to_vllm_mapper = WeightsMapper( orig_to_new_prefix={ "model.vision_encoder.": "vision_tower.", "model.vision_projection.": "multi_modal_projector.", "lm_head.": "language_model.lm_head.", "model.language_model.": "language_model.model.", } ) def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: nn.Module.__init__(self) config = vllm_config.model_config.hf_config quant_config = vllm_config.quant_config multimodal_config = vllm_config.model_config.multimodal_config self.config = config self.multimodal_config = multimodal_config self.vision_tower = init_vision_tower_for_llava( config, quant_config=quant_config, require_post_norm=False, prefix=maybe_prefix(prefix, "vision_tower"), ) self.multi_modal_projector = Mistral3MultiModalProjector( vision_hidden_size=config.vision_config.hidden_size, text_hidden_size=config.text_config.hidden_size, projector_hidden_act=config.projector_hidden_act, spatial_merge_size=config.spatial_merge_size, patch_size=config.vision_config.patch_size, multimodal_projector_bias=config.multimodal_projector_bias, quant_config=quant_config, prefix=maybe_prefix(prefix, "multi_modal_projector"), ) self.language_model = init_vllm_registered_model( vllm_config=vllm_config, hf_config=config.text_config, prefix=maybe_prefix(prefix, "language_model"), ) self.make_empty_intermediate_tensors = ( self.language_model.make_empty_intermediate_tensors ) def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: loader = AutoWeightsLoader(self) return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/lightonocr.py", "license": "Apache License 2.0", "lines": 168, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/utils_/test_import_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.utils.import_utils import PlaceholderModule def _raises_module_not_found(): return pytest.raises(ModuleNotFoundError, match="No module named") def test_placeholder_module_error_handling(): placeholder = PlaceholderModule("placeholder_1234") with _raises_module_not_found(): int(placeholder) with _raises_module_not_found(): placeholder() with _raises_module_not_found(): _ = placeholder.some_attr with _raises_module_not_found(): # Test conflict with internal __name attribute _ = placeholder.name # OK to print the placeholder or use it in a f-string _ = repr(placeholder) _ = str(placeholder) # No error yet; only error when it is used downstream placeholder_attr = placeholder.placeholder_attr("attr") with _raises_module_not_found(): int(placeholder_attr) with _raises_module_not_found(): placeholder_attr() with _raises_module_not_found(): _ = placeholder_attr.some_attr with _raises_module_not_found(): # Test conflict with internal __module attribute _ = placeholder_attr.module
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_import_utils.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/import_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Contains helpers related to importing modules. This is similar in concept to the `importlib` module. """ import importlib.metadata import importlib.util import os import sys from functools import cache from types import ModuleType from typing import Any import regex as re from typing_extensions import Never from vllm.logger import init_logger logger = init_logger(__name__) def import_pynvml(): """ Historical comments: libnvml.so is the library behind nvidia-smi, and pynvml is a Python wrapper around it. We use it to get GPU status without initializing CUDA context in the current process. Historically, there are two packages that provide pynvml: - `nvidia-ml-py` (https://pypi.org/project/nvidia-ml-py/): The official wrapper. It is a dependency of vLLM, and is installed when users install vLLM. It provides a Python module named `pynvml`. - `pynvml` (https://pypi.org/project/pynvml/): An unofficial wrapper. Prior to version 12.0, it also provides a Python module `pynvml`, and therefore conflicts with the official one. What's worse, the module is a Python package, and has higher priority than the official one which is a standalone Python file. This causes errors when both of them are installed. Starting from version 12.0, it migrates to a new module named `pynvml_utils` to avoid the conflict. It is so confusing that many packages in the community use the unofficial one by mistake, and we have to handle this case. For example, `nvcr.io/nvidia/pytorch:24.12-py3` uses the unofficial one, and it will cause errors, see the issue https://github.com/vllm-project/vllm/issues/12847 for example. After all the troubles, we decide to copy the official `pynvml` module to our codebase, and use it directly. """ import vllm.third_party.pynvml as pynvml return pynvml @cache def import_triton_kernels(): """ For convenience, prioritize triton_kernels that is available in `site-packages`. Use `vllm.third_party.triton_kernels` as a fall-back. """ if _has_module("triton_kernels"): import triton_kernels logger.debug_once( f"Loading module triton_kernels from {triton_kernels.__file__}.", scope="local", ) elif _has_module("vllm.third_party.triton_kernels"): import vllm.third_party.triton_kernels as triton_kernels logger.debug_once( f"Loading module triton_kernels from {triton_kernels.__file__}.", scope="local", ) sys.modules["triton_kernels"] = triton_kernels else: logger.info_once( "triton_kernels unavailable in this build. " "Please consider installing triton_kernels from " "https://github.com/triton-lang/triton/tree/main/python/triton_kernels" ) def import_from_path(module_name: str, file_path: str | os.PathLike): """ Import a Python file according to its file path. Based on the official recipe: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly """ spec = importlib.util.spec_from_file_location(module_name, file_path) if spec is None: raise ModuleNotFoundError(f"No module named {module_name!r}") assert spec.loader is not None module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) return module def resolve_obj_by_qualname(qualname: str) -> Any: """ Resolve an object by its fully-qualified class name. """ module_name, obj_name = qualname.rsplit(".", 1) module = importlib.import_module(module_name) return getattr(module, obj_name) @cache def get_vllm_optional_dependencies(): metadata = importlib.metadata.metadata("vllm") requirements = metadata.get_all("Requires-Dist", []) extras = metadata.get_all("Provides-Extra", []) return { extra: [ re.split(r";|>=|<=|==", req)[0] for req in requirements if req.endswith(f'extra == "{extra}"') ] for extra in extras } class _PlaceholderBase: """ Disallows downstream usage of placeholder modules. We need to explicitly override each dunder method because [`__getattr__`][vllm.utils.import_utils._PlaceholderBase.__getattr__] is not called when they are accessed. Info: [Special method lookup](https://docs.python.org/3/reference/datamodel.html#special-lookup) """ def __getattr__(self, key: str) -> Never: """ The main class should implement this to throw an error for attribute accesses representing downstream usage. """ raise NotImplementedError # [Basic customization] def __lt__(self, other: object): return self.__getattr__("__lt__") def __le__(self, other: object): return self.__getattr__("__le__") def __eq__(self, other: object): return self.__getattr__("__eq__") def __ne__(self, other: object): return self.__getattr__("__ne__") def __gt__(self, other: object): return self.__getattr__("__gt__") def __ge__(self, other: object): return self.__getattr__("__ge__") def __hash__(self): return self.__getattr__("__hash__") def __bool__(self): return self.__getattr__("__bool__") # [Callable objects] def __call__(self, *args: object, **kwargs: object): return self.__getattr__("__call__") # [Container types] def __len__(self): return self.__getattr__("__len__") def __getitem__(self, key: object): return self.__getattr__("__getitem__") def __setitem__(self, key: object, value: object): return self.__getattr__("__setitem__") def __delitem__(self, key: object): return self.__getattr__("__delitem__") # __missing__ is optional according to __getitem__ specification, # so it is skipped # __iter__ and __reversed__ have a default implementation # based on __len__ and __getitem__, so they are skipped. # [Numeric Types] def __add__(self, other: object): return self.__getattr__("__add__") def __sub__(self, other: object): return self.__getattr__("__sub__") def __mul__(self, other: object): return self.__getattr__("__mul__") def __matmul__(self, other: object): return self.__getattr__("__matmul__") def __truediv__(self, other: object): return self.__getattr__("__truediv__") def __floordiv__(self, other: object): return self.__getattr__("__floordiv__") def __mod__(self, other: object): return self.__getattr__("__mod__") def __divmod__(self, other: object): return self.__getattr__("__divmod__") def __pow__(self, other: object, modulo: object = ...): return self.__getattr__("__pow__") def __lshift__(self, other: object): return self.__getattr__("__lshift__") def __rshift__(self, other: object): return self.__getattr__("__rshift__") def __and__(self, other: object): return self.__getattr__("__and__") def __xor__(self, other: object): return self.__getattr__("__xor__") def __or__(self, other: object): return self.__getattr__("__or__") # r* and i* methods have lower priority than # the methods for left operand so they are skipped def __neg__(self): return self.__getattr__("__neg__") def __pos__(self): return self.__getattr__("__pos__") def __abs__(self): return self.__getattr__("__abs__") def __invert__(self): return self.__getattr__("__invert__") # __complex__, __int__ and __float__ have a default implementation # based on __index__, so they are skipped. def __index__(self): return self.__getattr__("__index__") def __round__(self, ndigits: object = ...): return self.__getattr__("__round__") def __trunc__(self): return self.__getattr__("__trunc__") def __floor__(self): return self.__getattr__("__floor__") def __ceil__(self): return self.__getattr__("__ceil__") # [Context managers] def __enter__(self): return self.__getattr__("__enter__") def __exit__(self, *args: object, **kwargs: object): return self.__getattr__("__exit__") class PlaceholderModule(_PlaceholderBase): """ A placeholder object to use when a module does not exist. This enables more informative errors when trying to access attributes of a module that does not exist. """ def __init__(self, name: str) -> None: super().__init__() # Apply name mangling to avoid conflicting with module attributes self.__name = name def placeholder_attr(self, attr_path: str): return _PlaceholderModuleAttr(self, attr_path) def __getattr__(self, key: str) -> Never: name = self.__name try: importlib.import_module(name) except ImportError as exc: for extra, names in get_vllm_optional_dependencies().items(): if name in names: msg = f"Please install vllm[{extra}] for {extra} support" raise ImportError(msg) from exc raise exc raise AssertionError( "PlaceholderModule should not be used " "when the original module can be imported" ) class _PlaceholderModuleAttr(_PlaceholderBase): def __init__(self, module: PlaceholderModule, attr_path: str) -> None: super().__init__() # Apply name mangling to avoid conflicting with module attributes self.__module = module self.__attr_path = attr_path def placeholder_attr(self, attr_path: str): return _PlaceholderModuleAttr(self.__module, f"{self.__attr_path}.{attr_path}") def __getattr__(self, key: str) -> Never: getattr(self.__module, f"{self.__attr_path}.{key}") raise AssertionError( "PlaceholderModule should not be used " "when the original module can be imported" ) class LazyLoader(ModuleType): """ `LazyLoader` module borrowed from [Tensorflow] (https://github.com/tensorflow/tensorflow/blob/main/tensorflow/python/util/lazy_loader.py) with an addition of "module caching". Lazily import a module, mainly to avoid pulling in large dependencies. Modules such as `xgrammar` might do additional side effects, so we only want to use this when it is needed, delaying all eager effects. """ def __init__( self, local_name: str, parent_module_globals: dict[str, Any], name: str, ): self._local_name = local_name self._parent_module_globals = parent_module_globals self._module: ModuleType | None = None super().__init__(str(name)) def _load(self) -> ModuleType: # Import the target module and insert it into the parent's namespace try: module = importlib.import_module(self.__name__) self._parent_module_globals[self._local_name] = module # The additional add to sys.modules # ensures library is actually loaded. sys.modules[self._local_name] = module except ModuleNotFoundError as err: raise err from None # Update this object's dict so that if someone keeps a # reference to the LazyLoader, lookups are efficient # (__getattr__ is only called on lookups that fail). self.__dict__.update(module.__dict__) return module def __getattr__(self, item: Any) -> Any: if self._module is None: self._module = self._load() return getattr(self._module, item) def __dir__(self) -> list[str]: if self._module is None: self._module = self._load() return dir(self._module) # Optional dependency detection utilities @cache def _has_module(module_name: str) -> bool: """Return True if *module_name* can be found in the current environment. The result is cached so that subsequent queries for the same module incur no additional overhead. """ return importlib.util.find_spec(module_name) is not None def has_deep_ep() -> bool: """Whether the optional `deep_ep` package is available.""" return _has_module("deep_ep") def has_deep_gemm() -> bool: """Whether the optional `deep_gemm` package is available.""" return _has_module("deep_gemm") def has_triton_kernels() -> bool: """Whether the optional `triton_kernels` package is available.""" is_available = _has_module("triton_kernels") or _has_module( "vllm.third_party.triton_kernels" ) if is_available: import_triton_kernels() return is_available def has_tilelang() -> bool: """Whether the optional `tilelang` package is available.""" return _has_module("tilelang") def has_arctic_inference() -> bool: """Whether the optional `arctic_inference` package is available.""" return _has_module("arctic_inference") def has_helion() -> bool: """Whether the optional `helion` package is available. Helion is a Python-embedded DSL for writing ML kernels. See: https://github.com/pytorch/helion Usage: if has_helion(): import helion import helion.language as hl # use helion... """ return _has_module("helion") def has_aiter() -> bool: """Whether the optional `aiter` package is available.""" return _has_module("aiter") def has_mori() -> bool: """Whether the optional `mori` package is available.""" return _has_module("mori")
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/import_utils.py", "license": "Apache License 2.0", "lines": 336, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/transformers/base.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 The vLLM team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformers modeling backend base class.""" from collections.abc import Iterable from typing import TYPE_CHECKING import regex as re import torch import transformers from packaging.version import Version from torch import nn from transformers import AutoModel from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS from vllm.config.utils import getattr_iter from vllm.distributed import get_pp_group, get_tp_group from vllm.distributed.utils import get_pp_indices from vllm.logger import init_logger from vllm.model_executor.layers.attention import ( Attention, EncoderOnlyAttention, ) from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding from vllm.model_executor.models.interfaces import ( SupportsEagle, SupportsEagle3, SupportsLoRA, SupportsPP, SupportsQuant, ) from vllm.model_executor.models.interfaces_base import VllmModel from vllm.model_executor.models.transformers.utils import ( get_feature_request_tip, init_on_device_without_buffers, log_replacement, replace_conv_class, replace_linear_class, replace_rms_norm_class, ) from vllm.model_executor.models.utils import ( AutoWeightsLoader, PPMissingLayer, WeightsMapper, make_empty_intermediate_tensors_factory, maybe_prefix, ) from vllm.sequence import IntermediateTensors from vllm.v1.attention.backend import AttentionType if TYPE_CHECKING: from transformers import PreTrainedModel from vllm.config import VllmConfig else: PreTrainedModel = object logger = init_logger(__name__) def vllm_flash_attention_forward( # Transformers args module: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor, # Transformers kwargs scaling: float | None = None, # vLLM kwargs attention_instances: dict[int, Attention] | None = None, **kwargs, ): self_attn = attention_instances[module.layer_idx] if scaling is not None: self_attn.impl.scale = float(scaling) hidden = query.shape[-2] query, key, value = (x.transpose(1, 2) for x in (query, key, value)) query, key, value = (x.reshape(hidden, -1) for x in (query, key, value)) return self_attn.forward(query, key, value), None ALL_ATTENTION_FUNCTIONS["vllm"] = vllm_flash_attention_forward class Base( nn.Module, VllmModel, SupportsQuant, SupportsLoRA, SupportsPP, SupportsEagle, SupportsEagle3, ): embedding_modules = ["embed_tokens"] # TODO transformers will have a util to get it hf_to_vllm_mapper = WeightsMapper( orig_to_new_prefix={ # Add `model.` prefix for base model checkpoints, # handling the case where it is already present "": "model.", "model.model.": "model.", # Heads will be adjacent to `model` (pooling included because of adapters) "model.lm_head.": "lm_head.", "model.score.": "classifier.", "model.classifier.": "classifier.", } ) def __init_subclass__(cls, *args, **kwargs): """Merge hf_to_vllm_mapper in MRO from most specific to least specific.""" super().__init_subclass__(*args, **kwargs) hf_to_vllm_mapper = WeightsMapper() for base in cls.__mro__: if base_hf_to_vllm_mapper := getattr(base, "hf_to_vllm_mapper", None): hf_to_vllm_mapper |= base_hf_to_vllm_mapper cls.hf_to_vllm_mapper = hf_to_vllm_mapper def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): super().__init__() logger.info("Using Transformers modeling backend.") self.config = vllm_config.model_config.hf_config self.text_config = self.config.get_text_config() self.cache_config = vllm_config.cache_config self.device_config = vllm_config.device_config self.model_config = vllm_config.model_config self.parallel_config = vllm_config.parallel_config self.quant_config = vllm_config.quant_config self.pp_group = get_pp_group() self.tp_group = get_tp_group() # Attrs for weight loading (see self.load_weights) self.skip_prefixes: list[str] = [] """Skip loading weights whose qualname starts with these prefixes.""" self.skip_substrs: list[str] = [] """Skip loading weights whose qualname contains these substrings.""" self.ignore_unexpected_prefixes: list[str] = [] """Ignore unexpected weights whose qualname starts with these prefixes.""" self.ignore_unexpected_suffixes: list[str] = [] """Ignore unexpected weights whose qualname ends with these suffixes.""" # Attrs for Eagle3 (see self.set_aux_hidden_state_layers) self._target_class: type[nn.Module] = nn.Module """Target class for Eagle3 aux hidden state recording.""" self._layer_names: dict[int, str] = {} """Mapping from layer index to layer name for Eagle3.""" self._output_aux_hidden_states_kwargs: dict[str, bool] = {} """Kwargs to pass to model forward for Eagle3 aux hidden states.""" if self.quant_config: quant_method_name = self.quant_config.get_name() # Check for unsupported quantization methods. if quant_method_name == "mxfp4": raise NotImplementedError( "Transformers modeling backend does " "not support MXFP4 quantization yet." ) # Skip loading extra bias for GPTQ models. if "gptq" in quant_method_name: self.ignore_unexpected_suffixes.append(".bias") # Set correct attn and init on "meta" to delay allocating GPU tensors self.text_config._attn_implementation = "vllm" with init_on_device_without_buffers("meta"): self.model: PreTrainedModel = AutoModel.from_config( self.config, dtype=self.model_config.dtype, trust_remote_code=self.model_config.trust_remote_code, ) # Remove layers not on this pipeline parallel rank self.pipeline_parallel() # Substitute remaining layers with vLLM's layers as needed self.recursive_replace() # Create attention instances for KV cache allocation self.attention_instances = self.create_attention_instances() # Input embeddings self.embed_scale = None input_embeddings = self.model.get_input_embeddings() if not isinstance(input_embeddings, PPMissingLayer): # Some models scale embeddings inside the input embedding layer self.embed_scale = getattr(input_embeddings, "embed_scale", None) names = ("embedding_size", "hidden_size") embedding_dim = getattr_iter(self.text_config, names, None) assert embedding_dim is not None self.model.set_input_embeddings( VocabParallelEmbedding( self.text_config.vocab_size, embedding_dim=embedding_dim, org_num_embeddings=self.text_config.vocab_size, quant_config=self.quant_config, ) ) # Initialize any parameters that have not had their modules replaced self.init_parameters(self.model) # Pipeline parallel intermediate tensors self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( ["hidden_states"], self.text_config.hidden_size ) def pipeline_parallel(self): """ Apply the model's pipeline parallelization plan. """ if self.pp_group.world_size <= 1: return if not self.model.supports_pp_plan: tip = get_feature_request_tip( self.model_config.model, self.model_config.trust_remote_code ) raise ValueError( f"{type(self.model)} does not support pipeline parallel. {tip}" ) module_lists = [] module_list_idx = None pp_plan = list(self.model._pp_plan.keys()) for i, name in enumerate(pp_plan): if isinstance(getattr(self.model, name), nn.ModuleList): module_lists.append(name) module_list_idx = i if len(module_lists) > 1: raise ValueError( "Pipeline parallel of models with multiple `ModuleList`s " "in the base model are not supported yet!" ) if module_list_idx is None: raise ValueError(f"Could not find `ModuleList` in {type(self.model)}") # Layers before module list for name in pp_plan[:module_list_idx]: if self.pp_group.is_first_rank or ( getattr(self.text_config, "tie_word_embeddings", False) and self.pp_group.is_last_rank ): continue setattr(self.model, name, PPMissingLayer()) # Module list start_layer, end_layer = get_pp_indices( self.text_config.num_hidden_layers, self.pp_group.rank_in_group, self.pp_group.world_size, ) layers_name = pp_plan[module_list_idx] layers = getattr(self.model, layers_name) for i in range(len(layers)): if start_layer <= i and i < end_layer: continue layers[i] = PPMissingLayer() # Layers after module list for name in pp_plan[module_list_idx + 1 :]: # Modules that should be on last rank if not self.pp_group.is_last_rank: setattr(self.model, name, PPMissingLayer()) def recursive_replace(self): """Recursively replace modules in the model as needed. Currently, this replaces: - `nn.Linear` with vLLM's tensor parallel linear classes - `*RMSNorm` with vLLM's `RMSNorm` """ tp_plan = self.model.tp_plan if not tp_plan and self.tp_group.world_size > 1: tip = get_feature_request_tip( self.model_config.model, self.model_config.trust_remote_code ) raise ValueError( f"{type(self.model)} does not support tensor parallel. {tip}" ) # Prefix the patterns because we always start from `self.model` tp_plan = {maybe_prefix("model", k): v for k, v in tp_plan.items()} def _recursive_replace(module: nn.Module, prefix: str): for child_name, child_module in module.named_children(): new_module = child_module qual_name = maybe_prefix(prefix, child_name) if ( isinstance(module, nn.ModuleList) and len(module) == self.text_config.num_hidden_layers ): # Populate Eagle3 attrs self._target_class = type(child_module) layer_name = qual_name.removeprefix("model.") self._layer_names[int(child_name)] = layer_name # MTP weights should not be loaded into the base model num_hidden_layers = self.text_config.num_hidden_layers names = ( "n_predict", # Override from SpeculativeConfig "num_nextn_predict_layers", # Most models "mtp_num_hidden_layers", # Qwen 3.5 ) n_predict = getattr_iter(self.text_config, names, 0) for i in range(num_hidden_layers, num_hidden_layers + n_predict): mtp_prefix = f"{prefix}.{i}." if mtp_prefix not in self.ignore_unexpected_prefixes: self.ignore_unexpected_prefixes.append(mtp_prefix) # Replace modules as needed if isinstance(child_module, nn.Linear): generator = (p for p in tp_plan if re.match(p, qual_name)) pattern = next(generator, None) # Some weight loaders expect all linear layers to inherit # LinearBase, so we set a default style which causes any # unspecified layers to be replaced with ReplicatedLinear style = tp_plan.get(pattern, "replicate") new_module = replace_linear_class( child_module, style, self.quant_config, prefix=qual_name ) elif isinstance(child_module, (nn.Conv2d, nn.Conv3d)): new_module = replace_conv_class(child_module) elif child_module.__class__.__name__.endswith("RMSNorm"): new_module = replace_rms_norm_class( child_module, self.text_config.hidden_size ) else: _recursive_replace(child_module, prefix=qual_name) if new_module is not child_module: setattr(module, child_name, new_module) log_replacement(qual_name, child_module, new_module) _recursive_replace(self.model, prefix="model") def create_attention_instances(self) -> dict[int, Attention]: """ Create `Attention` instances to inform KV cache allocation. """ text_config = self.text_config num_heads = self.model_config.get_num_attention_heads(self.parallel_config) head_size = self.model_config.get_head_size() num_kv_heads = self.model_config.get_num_kv_heads(self.parallel_config) logits_soft_cap = getattr(text_config, "attn_logit_softcapping", None) # In encoder models, the attention layers will have `is_causal=False` is_encoder = lambda module: not getattr(module, "is_causal", True) has_encoder = lambda model: any(is_encoder(m) for m in model.modules()) is_multimodal = lambda config: config != config.get_text_config() # vLLM does not support encoder-decoder models, so if any encoder layer is # found in a text only model, we assume the whole model is an encoder model if has_encoder(self.model) and not is_multimodal(self.config): self.check_version("5.0.0", "encoder models support") attn_type = AttentionType.ENCODER_ONLY else: attn_type = AttentionType.DECODER pp_rank = self.pp_group.rank_in_group pp_size = self.pp_group.world_size start, end = get_pp_indices(text_config.num_hidden_layers, pp_rank, pp_size) attention_instances = {} for i in range(start, end): # Handle interleaved sliding window attention per_layer_sliding_window = None if ( hasattr(self.config, "layer_types") and self.config.layer_types[i] == "sliding_attention" ): per_layer_sliding_window = self.config.sliding_window attn_cls = ( EncoderOnlyAttention if attn_type == AttentionType.ENCODER_ONLY else Attention ) attention_instances[i] = attn_cls( num_heads=num_heads, head_size=head_size, # NOTE: We use Llama scale as default, if it's set by # Transformers, it's updated in vllm_flash_attention_forward scale=head_size**-0.5, num_kv_heads=num_kv_heads, cache_config=self.cache_config, quant_config=self.quant_config, logits_soft_cap=logits_soft_cap, per_layer_sliding_window=per_layer_sliding_window, prefix=f"{i}.attn", attn_type=attn_type, ) return attention_instances def init_parameters(self, module: nn.Module, dtype: torch.dtype | None = None): """ If a `parameter` is on the `meta` device, then its parent `module` is the original module created by: ```python with torch.device("meta"): self.model: "PreTrainedModel" = AutoModel.from_config(...) ``` """ def _init_parameters(module: nn.Module, dtype: torch.dtype | None): for name, param in module.named_parameters(recurse=False): if param.device == torch.device("meta"): new_param = nn.Parameter( torch.empty_like( param.data, dtype=dtype or self.model_config.dtype, device=self.device_config.device, ) ) setattr(module, name, new_param) for child in module.children(): _init_parameters(child, dtype) _init_parameters(module, dtype) def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: inputs_embeds = self.model.get_input_embeddings()(input_ids) if self.embed_scale is not None: inputs_embeds *= self.embed_scale return inputs_embeds def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, **kwargs, ) -> torch.Tensor | IntermediateTensors: if not self.pp_group.is_first_rank: assert intermediate_tensors is not None input_ids = None inputs_embeds = intermediate_tensors["hidden_states"] if input_ids is not None: input_ids = input_ids[None, ...] if inputs_embeds is not None: inputs_embeds = inputs_embeds[None, ...] # If the model scales embeddings inside the input embedding layer we must # ensure they are scaled here since VocabParallelEmbedding will not do it if ( self.embed_scale is not None and input_ids is not None and inputs_embeds is None ): inputs_embeds = self.embed_input_ids(input_ids) input_ids = None if self.model_config.uses_mrope: position_ids = positions[:, None] else: position_ids = positions[None, ...] outputs = self.model( input_ids=input_ids, inputs_embeds=inputs_embeds, use_cache=False, position_ids=position_ids, attention_instances=self.attention_instances, return_dict=False, **self._output_aux_hidden_states_kwargs, **kwargs, ) # We must remove the batch dimension from these outputs hidden_states = outputs[0][0, ...] if self._output_aux_hidden_states_kwargs: aux_hidden_states = [x[0][0, ...] for x in outputs[1:]] if not self.pp_group.is_last_rank: return IntermediateTensors({"hidden_states": hidden_states}) if self._output_aux_hidden_states_kwargs and len(aux_hidden_states) > 0: return hidden_states, aux_hidden_states return hidden_states def load_weights( self, weights: Iterable[tuple[str, torch.Tensor]], ) -> set[str]: loader = AutoWeightsLoader( self, skip_prefixes=self.skip_prefixes, skip_substrs=self.skip_substrs, ignore_unexpected_prefixes=self.ignore_unexpected_prefixes, ignore_unexpected_suffixes=self.ignore_unexpected_suffixes, ) return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) @staticmethod def check_version(min_version: str, feature: str): installed = Version(transformers.__version__) required = Version(min_version) if installed < required: raise ImportError( f"Transformers modeling backend requires transformers>={required} " f"for {feature}, but got {installed}" ) def set_aux_hidden_state_layers(self, layers: tuple[int, ...]) -> None: self.check_version("5.0.0", "Eagle3 support") from transformers.utils.generic import OutputRecorder # The default value in PreTrainedModel is None if self.model._can_record_outputs is None: self.model._can_record_outputs = {} target_class = self._target_class for layer in layers: # layer - 1 because we want the input to the layer layer_name = self._layer_names[layer - 1] layer_key = f"aux_hidden_state_{layer}" aux_hidden_state_i = OutputRecorder(target_class, layer_name=layer_name) self.model._can_record_outputs[layer_key] = aux_hidden_state_i self._output_aux_hidden_states_kwargs[f"output_{layer_key}"] = True def get_eagle3_aux_hidden_state_layers(self) -> tuple[int, ...]: num_layers = self.text_config.num_hidden_layers return (2, num_layers // 2, num_layers - 3)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/transformers/base.py", "license": "Apache License 2.0", "lines": 473, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/transformers/causal.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 The vLLM team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformers modeling backend mixin for causal language models.""" from typing import TYPE_CHECKING 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_base import VllmModelForTextGeneration from vllm.model_executor.models.utils import PPMissingLayer, maybe_prefix if TYPE_CHECKING: import torch from vllm.config import VllmConfig class CausalMixin(VllmModelForTextGeneration): def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): # Skip VllmModelForTextGeneration.__init__ and call the next class in MRO super(VllmModelForTextGeneration, self).__init__( vllm_config=vllm_config, prefix=prefix ) # Tell `Base.load_weights` to skip # `lm_head` if the model has tied word embeddings tie_word_embeddings = getattr(self.text_config, "tie_word_embeddings", False) if tie_word_embeddings: self.skip_prefixes.append("lm_head.") if self.pp_group.is_last_rank: self.lm_head = ParallelLMHead( self.text_config.vocab_size, self.text_config.hidden_size, quant_config=self.quant_config, prefix=maybe_prefix(prefix, "lm_head"), ) if tie_word_embeddings: self.lm_head = self.lm_head.tie_weights( self.model.get_input_embeddings() ) logit_scale = getattr(self.text_config, "logit_scale", 1.0) self.logits_processor = LogitsProcessor( self.text_config.vocab_size, scale=logit_scale ) else: self.lm_head = PPMissingLayer() def compute_logits(self, hidden_states: "torch.Tensor") -> "torch.Tensor | None": logits = self.logits_processor(self.lm_head, hidden_states) return logits
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/transformers/causal.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/transformers/legacy.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 The vLLM team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformers modeling backend mixin for legacy models.""" from typing import TYPE_CHECKING import torch from vllm.model_executor.models.utils import WeightsMapper from vllm.sequence import IntermediateTensors if TYPE_CHECKING: from vllm.config import VllmConfig class LegacyMixin: hf_to_vllm_mapper = WeightsMapper( # These are applied in order, so the order matters! orig_to_new_prefix={ # Handle BERT-like models "roberta": "model", "bert": "model", }, orig_to_new_suffix={ # Replace legacy suffixes used for norms ".gamma": ".weight", ".beta": ".bias", }, ) def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): super().__init__(vllm_config=vllm_config, prefix=prefix) # Skip unsupported/unwanted output embeddings layers self.skip_prefixes.extend( [ "model.lm_head.", "model.predictions.", "model.qa_outputs.", "model.embeddings_project.", "model.discriminator_predictions.", ] ) # Some encoder models have the position_ids buffer in the checkpoint. # vLLM will always pass position_ids as an argument, so we skip loading # the buffer if it exists self.skip_substrs.append("position_ids") # Some encoder models have the bias of the final classifier layer # in the checkpoint. vLLM does not use this bias, so we skip loading # it if it exists self.skip_substrs.append("score.bias") # roberta-like models an extra padding in positions. # FIXME(Isotr0py): This is quite hacky for roberta edge case, # we should find a better way to handle this. self.is_roberta = "roberta" in self.text_config.model_type self.padding_idx = self.text_config.pad_token_id def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, ) -> torch.Tensor | IntermediateTensors: if self.is_roberta: # RoBERTa-specific positions padding positions += self.padding_idx + 1 return super().forward( input_ids=input_ids, positions=positions, intermediate_tensors=intermediate_tensors, inputs_embeds=inputs_embeds, )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/transformers/legacy.py", "license": "Apache License 2.0", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/transformers/multimodal.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 The vLLM team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformers modeling backend mixin for multi-modal models.""" from collections.abc import Mapping from typing import TYPE_CHECKING import torch from vllm.config.utils import getattr_iter from vllm.logger import init_logger from vllm.model_executor.models.interfaces import SupportsMRoPE, SupportsMultiModal from vllm.model_executor.models.utils import WeightsMapper from vllm.multimodal import MultiModalKwargsItems from vllm.multimodal.inputs import ( MultiModalDataDict, MultiModalFeatureSpec, MultiModalFieldConfig, MultiModalInputs, PlaceholderRange, mm_inputs, ) from vllm.multimodal.parse import ( ImageProcessorItems, MultiModalDataItems, ) from vllm.multimodal.processing import ( BaseDummyInputsBuilder, BaseMultiModalProcessor, BaseProcessingInfo, ProcessorInputs, TimingContext, ) from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors if TYPE_CHECKING: from transformers import BatchFeature from vllm.config import VllmConfig from vllm.config.multimodal import BaseDummyOptions DYNAMIC_ARG_DIMS = { "input_ids": 0, # set `positions` to last dim to support Qwen-mrope "positions": -1, "intermediate_tensors": 0, "inputs_embeds": 0, } logger = init_logger(__name__) class MultiModalProcessingInfo(BaseProcessingInfo): def get_supported_mm_limits(self): return {"image": None} def get_mm_max_tokens_per_item(self, seq_len, mm_counts): return {"image": self.get_max_image_tokens()} def get_max_image_tokens(self) -> int: width, height = self.get_max_image_size() processor = self.get_hf_processor() multimodal_config = self.ctx.model_config.multimodal_config mm_processor_kwargs = multimodal_config.mm_processor_kwargs or {} mm_tokens = processor._get_num_multimodal_tokens( image_sizes=([height, width],), **mm_processor_kwargs ) image_tokens = mm_tokens["num_image_tokens"][0] return image_tokens def get_max_image_size(self): return 10_000, 10_000 # hardcode for arbitrary very large size class MultiModalDummyInputsBuilder(BaseDummyInputsBuilder[MultiModalProcessingInfo]): def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str: num_images = mm_counts.get("image", 0) processor = self.info.get_hf_processor() if "gemma3" in processor.__class__.__name__.lower(): image_token = processor.boi_token else: image_token = getattr(processor, "image_token", "") return image_token * num_images def get_dummy_mm_data( self, seq_len: int, mm_counts: Mapping[str, int], mm_options: Mapping[str, "BaseDummyOptions"], ) -> MultiModalDataDict: num_images = mm_counts.get("image", 0) target_width, target_height = self.info.get_max_image_size() image_overrides = mm_options.get("image") return { "image": self._get_dummy_images( width=target_width, height=target_height, num_images=num_images, overrides=image_overrides, ), } class MultiModalProcessor(BaseMultiModalProcessor[MultiModalProcessingInfo]): def _get_prompt_updates( self, mm_items: MultiModalDataItems, hf_processor_mm_kwargs: Mapping[str, object], out_mm_kwargs: MultiModalKwargsItems, ): """ Given the original multi-modal items for this modality and HF-processed data, output the updates to perform. The information returned by this method is used to update token inputs which bypass the HF processor. It is also used to update the output of HF processor if the HF process does not apply prompt updates to text inputs. Moreover, this information is critical to determine the token positions in order to construct :class:`~vllm-multimodal.input.PlaceholderRange` for each multi-modal item. """ return None def _get_mm_fields_config( self, hf_inputs: "BatchFeature", hf_processor_mm_kwargs: Mapping[str, object], ) -> Mapping[str, MultiModalFieldConfig]: # HF Processors always return a mask but vLLM doesn't need it hf_inputs.pop("attention_mask", None) num_image_patches = hf_inputs.get("num_image_patches") mm_fields = { key: MultiModalFieldConfig.flat_from_sizes("image", num_image_patches) for key in hf_inputs } mm_fields["image_embeds"] = MultiModalFieldConfig.flat_from_sizes( "image", num_image_patches ) # Keep these as batched, as they always have batch size as first dim mm_fields["image_grid_thw"] = MultiModalFieldConfig.batched("image") mm_fields["video_grid_thw"] = MultiModalFieldConfig.batched("image") mm_fields["num_image_patches"] = MultiModalFieldConfig.batched("image") return mm_fields def _get_hf_mm_data( self, mm_items: MultiModalDataItems, ) -> tuple[Mapping[str, object], Mapping[str, object]]: """ In contrast to the base class, this method always adds `return_mm_token_type_ids` to the processor data """ processor_data, passthrough_data = super()._get_hf_mm_data(mm_items) processor_data["return_mm_token_type_ids"] = True return processor_data, passthrough_data def apply( self, inputs: ProcessorInputs, timing_ctx: TimingContext, ) -> MultiModalInputs: """ Process multi-modal inputs to be used in vLLM. Apply HF Processor on prompt text and multi-modal data together, outputting token IDs and processed tensors. """ prompt = inputs.prompt mm_items = inputs.mm_data_items hf_processor_mm_kwargs = inputs.hf_processor_mm_kwargs tokenization_kwargs = inputs.tokenization_kwargs with timing_ctx.record("apply_hf_processor"): hf_processor = self.info.get_hf_processor(**hf_processor_mm_kwargs) if not isinstance(prompt, str): # the prompt is the tokenized ids which is not supported # by the hf_processor, which is why we would need to decode the ids # into string prompt = hf_processor.decode(prompt) # Bypass cached processor and always apply to the full set of mm inputs # NOTE: we can't just set caching=False because base class method # transforms outputs to `MultiModalKwargs` which is not going to # work for Transformers. We have a lot of logic tied to # `mm_tokens_per_modality` below prompt_ids, processed_data, _ = self._apply_hf_processor_text_mm( prompt_text=prompt, mm_items=mm_items, hf_processor_mm_kwargs=hf_processor_mm_kwargs, tokenization_kwargs=tokenization_kwargs, ) # For gemma3 we check `token_type_ids` as the key token_type_key = ( "mm_token_type_ids" if "mm_token_type_ids" in processed_data else "token_type_ids" ) mm_token_type_ids = processed_data.get(token_type_key) # We can infer vLLM style placeholder from token type ids, if we split # it for each input `mm_data`. mm_positions = torch.where(mm_token_type_ids == 1)[1] images = mm_items.get_items("image", ImageProcessorItems) image_sizes = [] for item_idx in range(len(images)): image_size = images.get_image_size(item_idx) image_sizes.append((image_size.height, image_size.width)) mm_tokens_per_modality = hf_processor._get_num_multimodal_tokens( image_sizes=image_sizes, **self.info.ctx.get_merged_mm_kwargs({}), ) mm_placeholders = {} split_sizes = mm_tokens_per_modality["num_image_tokens"] if split_sizes: chunked_mm_positions = torch.split(mm_positions, split_sizes) mm_tokens = torch.tensor(prompt_ids)[mm_token_type_ids[0].bool()] chunked_mm_tokens = torch.split(mm_tokens, split_sizes) ranges = [ PlaceholderRange( offset=positions[0].item(), length=positions.shape[0], is_embed=(mm_tokens == hf_processor.image_token_id).bool(), ) for positions, mm_tokens in zip(chunked_mm_positions, chunked_mm_tokens) ] mm_placeholders = {"image": ranges} processed_data["num_image_patches"] = torch.tensor( mm_tokens_per_modality["num_image_patches"] ) mm_kwargs = MultiModalKwargsItems.from_hf_inputs( processed_data, self._get_mm_fields_config(processed_data, hf_processor_mm_kwargs), ) # Use overrides if provided; fallback to data-dependent hashing. with timing_ctx.record("get_mm_hashes"): mm_hashes = inputs.get_mm_hashes(self.info.model_id) return mm_inputs( prompt_token_ids=prompt_ids, mm_kwargs=mm_kwargs, mm_hashes=mm_hashes, mm_placeholders=mm_placeholders, ) class MultiModalMixin(SupportsMultiModal, SupportsMRoPE): supports_multimodal_raw_input_only = True # Backwards compatibility for prev released models. State dicts back then # had different formats and cannot be loaded with `AutoModel` mapping as is hf_to_vllm_mapper = WeightsMapper( orig_to_new_prefix={ "language_model.model": "model.language_model", "text_model.model": "model.text_model", "vision_tower": "model.vision_tower", "vqmodel": "model.vqmodel", "visual": "model.visual", "vision_model": "model.vision_model", "vision_embed_tokens": "model.vision_embed_tokens", "image_newline": "model.image_newline", "multi_modal_projector": "model.multi_modal_projector", "text_model.lm_head": "lm_head", "language_model.lm_head": "lm_head", # Qwen models used "model" as the name for the language model. # Therefore, we must map each of submodule explicitly to avoid # conflicts with newer models that use "model.language_model". "model.embed_tokens": "model.language_model.embed_tokens", "model.layers": "model.language_model.layers", "model.norm": "model.language_model.norm", } ) def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): # Skip SupportsMRoPE.__init__ and call the next class in MRO super(SupportsMRoPE, self).__init__(vllm_config=vllm_config, prefix=prefix) def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, **kwargs: object, ) -> torch.Tensor | IntermediateTensors: # Gemma3 and PaliGemma needs `token_type_ids` to work correctly # Other models will not have `token_type_ids` in kwargs kwargs = {k: v for k, v in kwargs.items() if k == "token_type_ids"} model_output = super().forward( input_ids, positions, intermediate_tensors, inputs_embeds, **kwargs ) return model_output def get_language_model(self) -> torch.nn.Module: """Transformers modeling backend multimodal classes do not contain a separate vLLM language model class. Therefore, in order to return a language model vLLM class, we use a wrapper to give `self` the same interface as a text model.""" # Exclude self and object bases = self.__class__.mro()[1:-1] # Keep only classes defined in `vllm.model_executor.models.transformers` bases = [b for b in bases if ".transformers." in b.__module__] # Exclude MultiModalMixin itself bases = [b for b in bases if b is not MultiModalMixin] class LanguageModel(*bases): def __init__(self, multimodal_model): # Don't call super().__init__() to avoid re-initialization self.__dict__.update(multimodal_model.__dict__) model = getattr_iter(self.model, ("language_model", "text_model"), None) return LanguageModel(self) def embed_multimodal(self, **kwargs): pixel_values: torch.Tensor | None = kwargs.pop("pixel_values", None) image_embeds: torch.Tensor | None = kwargs.pop("image_embeds", None) # Model might use `image_patches` instead of `pixel_values` if pixel_values is None: pixel_values = kwargs.pop("image_patches", None) if image_embeds is not None: return image_embeds if pixel_values is None: return None num_image_patches = kwargs.pop("num_image_patches") kwargs.pop("token_type_ids", None) # used only in `forward` kwargs.pop("mm_token_type_ids", None) # used only in `model.get_rope_index` if pixel_values is not None: # ROCm: Force math SDP backend for vision encoder to avoid accuracy issues # with flash_sdp and mem_efficient_sdp if current_platform.is_rocm(): # TODO: [ROCm] Fix accuracy issues with flash backend logger.debug( "ROCm platform detected. Forcing math SDP backend " "for vision encoder. Currently ROCm platform has " "accuracy issues with `flash_sdp` and" "`mem_efficient_sdp` backends. See issue: " "https://github.com/vllm-project/vllm/issues/30167" ) with torch.nn.attention.sdpa_kernel( backends=[torch.nn.attention.SDPBackend.MATH] ): vision_embeddings = self.model.get_image_features( pixel_values, **kwargs ) else: vision_embeddings = self.model.get_image_features( pixel_values, **kwargs ) # Transformers `v5`, `self.get_image_features` returns a tuple # containing the features and optionally attentions/hidden_states # After v5 is settled, we can enable qwen3-vl with several outputs # from `self.get_image_features` if isinstance(vision_embeddings, tuple): vision_embeddings = vision_embeddings[0] elif isinstance(vision_embeddings, dict): vision_embeddings = vision_embeddings.pooler_output if isinstance(vision_embeddings, torch.Tensor): split_sizes = num_image_patches.flatten().tolist() total_patches = sum(split_sizes) # Flatten to 2D: [total_tokens, hidden_dim] if vision_embeddings.ndim == 3: vision_embeddings = vision_embeddings.view( -1, vision_embeddings.shape[-1] ) total_tokens = vision_embeddings.shape[0] if total_tokens == total_patches: # Direct match: num_image_patches are actual token counts # (e.g., Qwen2.5-VL style) token_split_sizes = split_sizes elif total_patches > 0 and total_tokens % total_patches == 0: # Uniform expansion: each patch expands to N tokens # (e.g., Idefics3 style) tokens_per_patch = total_tokens // total_patches token_split_sizes = [s * tokens_per_patch for s in split_sizes] elif total_patches > 0: # Mismatch (profiling with dummy data) - pad/truncate if total_tokens == 0: raise ValueError( "Vision encoder returned empty embeddings. " f"Expected {total_patches} patches from " f"num_image_patches={split_sizes}" ) if total_tokens < total_patches: repeat_factor = ( total_patches + total_tokens - 1 ) // total_tokens vision_embeddings = vision_embeddings.repeat(repeat_factor, 1) vision_embeddings = vision_embeddings[:total_patches] token_split_sizes = split_sizes else: return [] return list(torch.split(vision_embeddings, token_split_sizes, dim=0)) return vision_embeddings else: logger.debug( "No pixel values or image embeddings provided for multimodal embedding." ) return None def get_mrope_input_positions( self, input_tokens: list[int], mm_features: list[MultiModalFeatureSpec], ) -> tuple[torch.Tensor, int]: kwargs = MultiModalFeatureSpec.gather_kwargs( mm_features, { "image_grid_thw", "video_grid_thw", "mm_token_type_ids", "second_per_grid_ts", "audio_feature_lengths", "use_audio_in_video", }, ) if any( v for k, v in kwargs.items() if k not in {"image_grid_thw", "mm_token_type_ids"} ): raise NotImplementedError( "Transformers modeling backend only supports images." ) image_grid_thw = kwargs.get("image_grid_thw", []) video_grid_thw = kwargs.get("video_grid_thw", []) mm_token_type_ids = kwargs.get("mm_token_type_ids") image_grid_thw = (torch.stack if image_grid_thw else torch.tensor)( image_grid_thw ) video_grid_thw = (torch.stack if video_grid_thw else torch.tensor)( video_grid_thw ) # In v4 `get_rope_index` doesn't have wildcard `kwargs`, and # can't accept arbitrary args, even if its value is `None` kwargs = {} if mm_token_type_ids: kwargs["mm_token_type_ids"] = torch.cat(mm_token_type_ids) mrope_positions, mrope_position_delta = self.model.get_rope_index( input_ids=torch.tensor(input_tokens).unsqueeze(0), image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, **kwargs, ) mrope_positions = mrope_positions[:, 0] mrope_position_delta = mrope_position_delta[0].item() return mrope_positions, mrope_position_delta
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/transformers/multimodal.py", "license": "Apache License 2.0", "lines": 423, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/transformers/pooling.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 The vLLM team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformers modeling backend mixins for pooling models.""" from typing import TYPE_CHECKING import torch from transformers import AutoModelForSequenceClassification from vllm.config.utils import getattr_iter from vllm.model_executor.layers.pooler import DispatchPooler from vllm.model_executor.models.interfaces import SupportsCrossEncoding from vllm.model_executor.models.interfaces_base import VllmModelForPooling if TYPE_CHECKING: from vllm.config import VllmConfig class EmbeddingMixin(VllmModelForPooling): default_seq_pooling_type = "CLS" def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): # Skip VllmModelForPooling.__init__ and call the next class in MRO super(VllmModelForPooling, self).__init__( vllm_config=vllm_config, prefix=prefix ) pooler_config = vllm_config.model_config.pooler_config assert pooler_config is not None self.pooler = DispatchPooler.for_embedding(pooler_config) class SequenceClassificationMixin(SupportsCrossEncoding, VllmModelForPooling): default_seq_pooling_type = "CLS" def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): # Skip VllmModelForPooling.__init__ and call the next class in MRO super(VllmModelForPooling, self).__init__( vllm_config=vllm_config, prefix=prefix ) pooler_config = vllm_config.model_config.pooler_config assert pooler_config is not None # Certain information about the the model and classifier can only be # inferred from the `ForSequenceClassification` class. Therefore, we # instantiate it on the "meta" device to avoid allocating GPU memory. with torch.device("meta"): seq_cls_model = AutoModelForSequenceClassification.from_config( self.config, dtype=self.model_config.dtype, trust_remote_code=self.model_config.trust_remote_code, ) # When used for sequence classification, some models have their # pooling layers removed. Make sure this is reflected in vLLM. for module in seq_cls_model.modules(): if hasattr(module, "pooler") and module.pooler is None: self.model.pooler = None break # Unlike `lm_head`, `classifier` is not always `nn.Linear`. self.classifier = getattr_iter(seq_cls_model, ["classifier", "score"], None) if self.classifier is None: raise ValueError( "Could not find `classifier` or `score` layer in the " "`AutoModelForSequenceClassification` instance." ) self.init_parameters(self.classifier, dtype=self.model_config.head_dtype) class ClassifierWithReshape(self.classifier.__class__): """ Token extraction has already been applied in `pooler.pooling`. Add dim to match expected input shape of `classifier.forward`. """ def forward(self, *args, **kwargs): if len(args) > 0: args = (args[0].unsqueeze(1), *args[1:]) return super().forward(*args, **kwargs) self.classifier.__class__ = ClassifierWithReshape self.pooler = DispatchPooler.for_seq_cls( pooler_config, classifier=self.classifier, )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/transformers/pooling.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/transformers/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 The vLLM team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformers modeling backend utilities.""" from contextlib import contextmanager from pathlib import Path from typing import TYPE_CHECKING, Literal import torch from torch import nn from vllm.config.utils import getattr_iter from vllm.logger import init_logger from vllm.model_executor.layers.conv import Conv2dLayer, Conv3dLayer from vllm.model_executor.layers.layernorm import GemmaRMSNorm, RMSNorm from vllm.model_executor.layers.linear import ( ColumnParallelLinear, ReplicatedLinear, RowParallelLinear, ) from vllm.transformers_utils.config import is_rope_parameters_nested if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.model_executor.layers.quantization import QuantizationConfig logger = init_logger(__name__) # Copied from `accelerate` @contextmanager def init_on_device_without_buffers(device: torch.device): """ A context manager under which models are initialized with all parameters on the specified device. However buffers are not initialized on specified device. Args: device (`torch.device`): Device to initialize all parameters on. """ old_register_parameter = nn.Module.register_parameter def register_empty_parameter(module, name, param): old_register_parameter(module, name, param) if param is not None: param_cls = type(module._parameters[name]) kwargs = module._parameters[name].__dict__ kwargs["requires_grad"] = param.requires_grad module._parameters[name] = param_cls( module._parameters[name].to(device), **kwargs ) tensor_constructors_to_patch = {} def patch_tensor_constructor(fn): def wrapper(*args, **kwargs): kwargs["device"] = device return fn(*args, **kwargs) return wrapper try: nn.Module.register_parameter = register_empty_parameter for torch_function_name in tensor_constructors_to_patch: setattr( torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)), ) yield finally: nn.Module.register_parameter = old_register_parameter for ( torch_function_name, old_torch_function, ) in tensor_constructors_to_patch.items(): setattr(torch, torch_function_name, old_torch_function) Style = Literal["colwise", "colwise_rep", "rowwise", "rowwise_rep", "replicate"] def replace_linear_class( linear: nn.Linear, style: Style = "replicate", quant_config: "QuantizationConfig | None" = None, *, prefix: str = "", ) -> ColumnParallelLinear | RowParallelLinear | ReplicatedLinear: """ Replace nn.Linear with one of vLLM's tensor parallel linear classes. Args: linear: `nn.Linear` to be replaced. style: Tensor parallel style of the new linear, e.g. "colwise". quant_config: Quantization config for the new linear. Returns: The new linear. """ if not isinstance(style, str): raise ValueError(f"Unsupported parallel style type {type(style)}, expected str") vllm_linear_cls, vllm_linear_kwargs = { "colwise": (ColumnParallelLinear, {}), "colwise_rep": (ColumnParallelLinear, {"gather_output": True}), "rowwise": (RowParallelLinear, {}), "rowwise_rep": (RowParallelLinear, {"input_is_parallel": False}), "replicate": (ReplicatedLinear, {}), }.get(style, (ReplicatedLinear, {})) return vllm_linear_cls( input_size=linear.in_features, output_size=linear.out_features, bias=linear.bias is not None, quant_config=quant_config, prefix=prefix, return_bias=False, **vllm_linear_kwargs, ) TorchConv = nn.Conv2d | nn.Conv3d VllmConv = Conv2dLayer | Conv3dLayer def replace_conv_class(conv: TorchConv) -> VllmConv | TorchConv: """Replace a Transformers Conv2d/Conv3d with vLLM's Conv2d/Conv3d. Args: conv: `nn.Conv2d` or `nn.Conv3d` to be replaced. Returns: The new `Conv2dLayer` or `Conv3dLayer`. If the conv module is not supported, returns the original conv module. """ # vLLM does not handle non-zero padding modes if conv.padding_mode != "zeros": return conv vllm_conv_cls = { nn.Conv2d: Conv2dLayer, nn.Conv3d: Conv3dLayer, }.get(type(conv)) if vllm_conv_cls is None: return conv return vllm_conv_cls( in_channels=conv.in_channels, out_channels=conv.out_channels, kernel_size=conv.kernel_size, stride=conv.stride, padding=conv.padding, dilation=conv.dilation, groups=conv.groups, bias=conv.bias is not None, padding_mode=conv.padding_mode, params_dtype=conv.weight.dtype, ) def replace_rms_norm_class(rms_norm: nn.Module, hidden_size: int) -> RMSNorm: """Replace a Transformers RMSNorm with vLLM's RMSNorm. This method assumes: - Weight is stored as `weight`. - Epsilon is stored as `eps` or `variance_epsilon`. - `with_scale` indicates whether the layer has a weight (Gemma3n only). - `var_hidden_size` is only ever used for Intern vision encoder in vLLM and Transformers doesn't appear to have the same concept. """ eps = getattr_iter(rms_norm, ("eps", "variance_epsilon"), 1e-6) kwargs = {"hidden_size": hidden_size, "eps": eps} # Update hidden size if weight is available weight_meta = getattr(rms_norm, "weight", None) if weight_meta is not None: kwargs["hidden_size"] = weight_meta.size(0) # Check if weight is all zeros, which indicates GemmaRMSNorm # We must create a new instance because rms_norm is on meta try: with torch.device("cpu"): weight_test = getattr(rms_norm.__class__(1), "weight", None) except Exception: logger.warning( "Failed to determine if RMSNorm weight is centered on zero or one. " "Defaulting to one." ) weight_test = None if weight_test is not None and torch.all(weight_test == 0): return GemmaRMSNorm(**kwargs) # Otherwise assume it's a regular RMSNorm kwargs["has_weight"] = getattr(rms_norm, "with_scale", True) if weight_meta is not None: kwargs["dtype"] = weight_meta.dtype else: # No weight, fall back to weightless RMSNorm kwargs["has_weight"] = False return RMSNorm(**kwargs) def log_replacement(name: str, old_module: nn.Module, new_module: nn.Module): logger.debug("%s: %s -> %s", name, old_module, new_module) def get_feature_request_tip( model: str, trust_remote_code: bool, ) -> str: hf_url = f"a discussion at https://huggingface.co/{model}/discussions/new" gh_url = "an issue at https://github.com/huggingface/transformers/issues/new/choose" url = hf_url if trust_remote_code else gh_url prefix = f"Please open {url} to request support for this feature. " if Path(model).exists(): prefix = "" doc_url = "https://docs.vllm.ai/en/latest/models/supported_models.html#writing-custom-models" tip = f"See {doc_url} for instructions on how to add support yourself." return f"{prefix}{tip}" def can_enable_torch_compile(vllm_config: "VllmConfig") -> bool: """ Callable to be passed to `@support_torch_compile`'s `enable_if` argument. Defaults to `True` but is disabled in the following situations: - The model uses dynamic rope scaling. """ text_config = vllm_config.model_config.hf_config.get_text_config() # Dynamic rope scaling is not compatible with torch.compile rope_parameters: dict | None = getattr(text_config, "rope_parameters", None) or {} if rope_parameters: # Nest rope_parameters if not nested already to simplify logic if not is_rope_parameters_nested(rope_parameters): rope_parameters = {"": rope_parameters} return all(rp["rope_type"] != "dynamic" for rp in rope_parameters.values()) return True
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/transformers/utils.py", "license": "Apache License 2.0", "lines": 210, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/entrypoints/openai/tool_parsers/test_olmo3_tool_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from unittest.mock import MagicMock, patch import pytest from tests.entrypoints.openai.tool_parsers.utils import ( run_tool_extraction, run_tool_extraction_streaming, ) from vllm.entrypoints.openai.engine.protocol import FunctionCall from vllm.tokenizers import TokenizerLike from vllm.tool_parsers import ToolParser, ToolParserManager # https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/text_prompt_format.md#model-response-format-1 SIMPLE_FUNCTION_OUTPUT = "get_weather(city='San Francisco', metric='celsius')" SIMPLE_FUNCTION_CALL = FunctionCall( name="get_weather", arguments='{"city": "San Francisco", "metric": "celsius"}', ) MORE_TYPES_FUNCTION_OUTPUT = ( "register_user(name='John Doe', " "age=37, " "address={'city': 'San Francisco', 'state': 'CA'}, " "role=None, " "passed_test=True, " "aliases=['John', 'Johnny'])" ) MORE_TYPES_FUNCTION_OUTPUT_JSON_LITERALS = ( "register_user(name='John Doe', " "age=37, " "address={'city': 'San Francisco', 'state': 'CA'}, " "role=null, " "passed_test=true, " "aliases=['John', 'Johnny'])" ) MORE_TYPES_FUNCTION_CALL = FunctionCall( name="register_user", arguments='{"name": "John Doe", ' '"age": 37, ' '"address": {"city": "San Francisco", "state": "CA"}, ' '"role": null, ' '"passed_test": true, ' '"aliases": ["John", "Johnny"]}', ) PARAMETERLESS_FUNCTION_OUTPUT = "get_weather()" PARAMETERLESS_FUNCTION_CALL = FunctionCall( name="get_weather", arguments="{}", ) EMPTY_DICT_FUNCTION_OUTPUT = "do_something_cool(additional_data={})" EMPTY_DICT_FUNCTION_CALL = FunctionCall( name="do_something_cool", arguments='{"additional_data": {}}', ) EMPTY_LIST_FUNCTION_OUTPUT = "do_something_cool(steps=[])" EMPTY_LIST_FUNCTION_CALL = FunctionCall( name="do_something_cool", arguments='{"steps": []}', ) ESCAPED_STRING_FUNCTION_OUTPUT = ( r"get_weather(city='Martha\'s Vineyard', metric='\"cool units\"')" ) ESCAPED_STRING_FUNCTION_CALL = FunctionCall( name="get_weather", arguments='{"city": "Martha\'s Vineyard", "metric": "\\"cool units\\""}', ) @pytest.mark.parametrize("streaming", [True, False]) def test_no_tool_call(streaming: bool, default_tokenizer: TokenizerLike): tool_parser: ToolParser = ToolParserManager.get_tool_parser("olmo3")( default_tokenizer ) model_output = "How can I help you today?" content, tool_calls = run_tool_extraction( tool_parser, model_output, streaming=streaming ) assert content == model_output assert len(tool_calls) == 0 TEST_CASES = [ pytest.param( True, f"<function_calls>{SIMPLE_FUNCTION_OUTPUT}</function_calls>", [SIMPLE_FUNCTION_CALL], id="simple_streaming", ), pytest.param( False, f"<function_calls>{SIMPLE_FUNCTION_OUTPUT}</function_calls>", [SIMPLE_FUNCTION_CALL], id="simple_nonstreaming", ), pytest.param( True, f"<function_calls>{MORE_TYPES_FUNCTION_OUTPUT}</function_calls>", [MORE_TYPES_FUNCTION_CALL], id="more_types_streaming", ), pytest.param( False, f"<function_calls>{MORE_TYPES_FUNCTION_OUTPUT}</function_calls>", [MORE_TYPES_FUNCTION_CALL], id="more_types_nonstreaming", ), pytest.param( True, f"<function_calls>{MORE_TYPES_FUNCTION_OUTPUT_JSON_LITERALS}</function_calls>", [MORE_TYPES_FUNCTION_CALL], id="more_types_streaming_json_literals", ), pytest.param( False, f"<function_calls>{MORE_TYPES_FUNCTION_OUTPUT_JSON_LITERALS}</function_calls>", [MORE_TYPES_FUNCTION_CALL], id="more_types_nonstreaming_json_literals", ), pytest.param( True, f"<function_calls>{PARAMETERLESS_FUNCTION_OUTPUT}</function_calls>", [PARAMETERLESS_FUNCTION_CALL], id="parameterless_streaming", ), pytest.param( False, f"<function_calls>{PARAMETERLESS_FUNCTION_OUTPUT}</function_calls>", [PARAMETERLESS_FUNCTION_CALL], id="parameterless_nonstreaming", ), pytest.param( True, f"<function_calls>{EMPTY_DICT_FUNCTION_OUTPUT}</function_calls>", [EMPTY_DICT_FUNCTION_CALL], id="empty_dict_streaming", ), pytest.param( False, f"<function_calls>{EMPTY_DICT_FUNCTION_OUTPUT}</function_calls>", [EMPTY_DICT_FUNCTION_CALL], id="empty_dict_nonstreaming", ), pytest.param( True, f"<function_calls>{EMPTY_LIST_FUNCTION_OUTPUT}</function_calls>", [EMPTY_LIST_FUNCTION_CALL], id="empty_list_streaming", ), pytest.param( False, f"<function_calls>{EMPTY_LIST_FUNCTION_OUTPUT}</function_calls>", [EMPTY_LIST_FUNCTION_CALL], id="empty_list_nonstreaming", ), pytest.param( True, f"<function_calls>{ESCAPED_STRING_FUNCTION_OUTPUT}</function_calls>", [ESCAPED_STRING_FUNCTION_CALL], id="escaped_string_streaming", ), pytest.param( False, f"<function_calls>{ESCAPED_STRING_FUNCTION_OUTPUT}</function_calls>", [ESCAPED_STRING_FUNCTION_CALL], id="escaped_string_nonstreaming", ), pytest.param( True, f"<function_calls>{SIMPLE_FUNCTION_OUTPUT}\n{MORE_TYPES_FUNCTION_OUTPUT}</function_calls>", [SIMPLE_FUNCTION_CALL, MORE_TYPES_FUNCTION_CALL], id="parallel_calls_streaming", ), pytest.param( False, f"<function_calls>{SIMPLE_FUNCTION_OUTPUT}\n{MORE_TYPES_FUNCTION_OUTPUT}</function_calls>", [SIMPLE_FUNCTION_CALL, MORE_TYPES_FUNCTION_CALL], id="parallel_calls_nonstreaming", ), ] @pytest.mark.parametrize("streaming, model_output, expected_tool_calls", TEST_CASES) def test_tool_call( streaming: bool, model_output: str, expected_tool_calls: list[FunctionCall], default_tokenizer: TokenizerLike, ): tool_parser: ToolParser = ToolParserManager.get_tool_parser("olmo3")( default_tokenizer ) content, tool_calls = run_tool_extraction( tool_parser, model_output, streaming=streaming ) assert content is None assert len(tool_calls) == len(expected_tool_calls) for actual, expected in zip(tool_calls, expected_tool_calls): assert actual.type == "function" assert actual.function == expected def test_streaming_tool_call_with_large_steps(default_tokenizer: TokenizerLike): tool_parser: ToolParser = ToolParserManager.get_tool_parser("olmo3")( default_tokenizer ) model_output_deltas = [ "<function_calls>get_weather(city='San", " Francisco', metric='celsius')\n" f"{PARAMETERLESS_FUNCTION_OUTPUT}\n" f"{EMPTY_LIST_FUNCTION_OUTPUT}</function_calls>", ] reconstructor = run_tool_extraction_streaming( tool_parser, model_output_deltas, assert_one_tool_per_delta=False ) assert reconstructor.other_content == "" assert len(reconstructor.tool_calls) == 3 assert reconstructor.tool_calls[0].function == SIMPLE_FUNCTION_CALL assert reconstructor.tool_calls[1].function == PARAMETERLESS_FUNCTION_CALL assert reconstructor.tool_calls[2].function == EMPTY_LIST_FUNCTION_CALL @pytest.mark.parametrize("streaming", [False]) def test_regex_timeout_handling(streaming: bool, default_tokenizer: TokenizerLike): """test regex timeout is handled gracefully""" tool_parser: ToolParser = ToolParserManager.get_tool_parser("olmo3")( default_tokenizer ) fake_problematic_input = "hello world[A(A=" + "\t)A(A=,\t" * 2 # create a mock regex that raises TimeoutError mock_regex = MagicMock() mock_regex.match.side_effect = TimeoutError("Regex timeout") with patch.object(tool_parser, "TOOL_CALL_REGEX", mock_regex): content, tool_calls = run_tool_extraction( tool_parser, fake_problematic_input, streaming=streaming ) # should treat as regular text when regex times out assert content == fake_problematic_input assert len(tool_calls) == 0 mock_regex.match.assert_called_once()
{ "repo_id": "vllm-project/vllm", "file_path": "tests/entrypoints/openai/tool_parsers/test_olmo3_tool_parser.py", "license": "Apache License 2.0", "lines": 227, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/utils_/test_async_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import asyncio from collections.abc import AsyncIterator import pytest from vllm.utils.async_utils import merge_async_iterators async def _mock_async_iterator(idx: int): try: while True: yield f"item from iterator {idx}" await asyncio.sleep(0.1) except asyncio.CancelledError: print(f"iterator {idx} cancelled") @pytest.mark.asyncio async def test_merge_async_iterators(): iterators = [_mock_async_iterator(i) for i in range(3)] merged_iterator = merge_async_iterators(*iterators) async def stream_output(generator: AsyncIterator[tuple[int, str]]): async for idx, output in generator: print(f"idx: {idx}, output: {output}") task = asyncio.create_task(stream_output(merged_iterator)) await asyncio.sleep(0.5) task.cancel() with pytest.raises(asyncio.CancelledError): await task for iterator in iterators: try: await asyncio.wait_for(anext(iterator), 1) except StopAsyncIteration: # All iterators should be cancelled and print this message. print("Iterator was cancelled normally") except (Exception, asyncio.CancelledError) as e: raise AssertionError() from e
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_async_utils.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/async_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Contains helpers related to asynchronous code. This is similar in concept to the `asyncio` module. """ import asyncio import contextlib from asyncio import FIRST_COMPLETED, AbstractEventLoop, Future, Task from collections.abc import AsyncGenerator, Awaitable, Callable from concurrent.futures import Executor, ThreadPoolExecutor from functools import partial from typing import TYPE_CHECKING, TypeVar from transformers.tokenization_utils_base import BatchEncoding from typing_extensions import ParamSpec P = ParamSpec("P") T = TypeVar("T") class AsyncMicrobatchTokenizer: """Asynchronous tokenizer with micro-batching. Pulls pending encode/decode requests from a queue and batches them up to reduce overhead. A single-thread ThreadPoolExecutor is used so the event loop stays responsive. """ def __init__( self, tokenizer, max_batch_size: int = 32, batch_wait_timeout_s: float = 0.002, ) -> None: self.tokenizer = tokenizer self.max_batch_size = max_batch_size self.batch_wait_timeout_s = batch_wait_timeout_s self._loop = asyncio.get_running_loop() self._queues: dict[ tuple, asyncio.Queue[tuple[str, dict, Future] | tuple[list[int], Future]], ] = {} self._batcher_tasks: list[Task] = [] # Single-thread executor for blocking tokenizer calls. self._executor = ThreadPoolExecutor(max_workers=1) # === Public async API === async def __call__(self, prompt, **kwargs) -> BatchEncoding: result_future: Future = self._loop.create_future() key = self._queue_key("encode", kwargs) queue = self._get_queue(self._loop, key) await queue.put((prompt, kwargs, result_future)) return await result_future async def encode(self, prompt, **kwargs) -> list[int]: return (await self(prompt, **kwargs)).input_ids async def decode(self, token_ids, **kwargs) -> str: result_future: Future = self._loop.create_future() key = self._queue_key("decode", kwargs) queue = self._get_queue(self._loop, key) await queue.put((token_ids, result_future)) return await result_future # === Internal helpers === def _get_queue( self, loop: asyncio.AbstractEventLoop, key: tuple ) -> asyncio.Queue[tuple[str, dict, Future] | tuple[list[int], Future]]: """Get the request queue for the given operation key, creating a new queue and batcher task if needed.""" queue = self._queues.get(key) if queue is None: self._queues[key] = queue = asyncio.Queue() if key[0] == "encode": can_batch = key[1] != "other" coro = self._batch_encode_loop(queue, can_batch) else: assert key[0] == "decode", f"Unknown operation type: {key[0]}." coro = self._batch_decode_loop(queue) self._batcher_tasks.append(loop.create_task(coro)) return queue async def _batch_encode_loop(self, queue: asyncio.Queue, can_batch: bool): """Batch incoming encode requests for efficiency.""" while True: prompt, kwargs, result_future = await queue.get() prompts = [prompt] kwargs_list = [kwargs] result_futures = [result_future] deadline = self._loop.time() + self.batch_wait_timeout_s while len(prompts) < self.max_batch_size: timeout = deadline - self._loop.time() if timeout <= 0: break try: prompt, kwargs, result_future = await asyncio.wait_for( queue.get(), timeout ) prompts.append(prompt) result_futures.append(result_future) if not can_batch: kwargs_list.append(kwargs) except asyncio.TimeoutError: break try: # If every request uses identical kwargs we can run a single # batched tokenizer call for a big speed-up. if can_batch and len(prompts) > 1: batch_encode_fn = partial(self.tokenizer, prompts, **kwargs) results = await self._loop.run_in_executor( self._executor, batch_encode_fn ) for i, fut in enumerate(result_futures): if not fut.done(): data = {k: v[i] for k, v in results.items()} fut.set_result(BatchEncoding(data)) else: encode_fn = lambda prompts=prompts, kwargs=kwargs_list: [ self.tokenizer(p, **kw) for p, kw in zip(prompts, kwargs) ] results = await self._loop.run_in_executor( self._executor, encode_fn ) for fut, res in zip(result_futures, results): if not fut.done(): fut.set_result(res) except Exception as e: for fut in result_futures: if not fut.done(): fut.set_exception(e) async def _batch_decode_loop(self, queue: asyncio.Queue): """Batch incoming decode requests for efficiency.""" while True: token_ids, result_future = await queue.get() token_ids_list = [token_ids] result_futures = [result_future] deadline = self._loop.time() + self.batch_wait_timeout_s while len(token_ids_list) < self.max_batch_size: timeout = deadline - self._loop.time() if timeout <= 0: break try: token_ids, result_future = await asyncio.wait_for( queue.get(), timeout ) token_ids_list.append(token_ids) result_futures.append(result_future) except asyncio.TimeoutError: break try: # Perform a single batched decode call for all requests results = await self._loop.run_in_executor( self._executor, self.tokenizer.batch_decode, token_ids_list ) for fut, res in zip(result_futures, results): if not fut.done(): fut.set_result(res) except Exception as e: for fut in result_futures: if not fut.done(): fut.set_exception(e) def _queue_key(self, op: str, kwargs: dict) -> tuple: """ Return a normalized key describing operation + kwargs. - `add_special_tokens`: {True/False} - `truncation`: {True/False} - If `truncation` is False (`max_length` is None), returns a key for a can_batch queue. - If `truncation` is True and `max_length` is None or equals `tokenizer.model_max_length`, returns a key for a can_batch queue. - Otherwise, returns a key for a cannot_batch queue. Examples: - Decode: ("decode",) - Encode typical: ("encode", add_special_tokens, bool_truncation, max_length_label) - Fallback: ("encode", "other") """ if op == "decode": return ("decode",) add_special_tokens = kwargs.get("add_special_tokens", True) truncation = kwargs.get("truncation", False) max_length = kwargs.get("max_length") if not truncation: return "encode", add_special_tokens, False, None model_max = getattr(self.tokenizer, "model_max_length", None) if max_length is None or (model_max is not None and max_length == model_max): return "encode", add_special_tokens, True, "model_max" return "encode", "other" def __del__(self): if ( (tasks := getattr(self, "_batcher_tasks", None)) and (loop := getattr(self, "_loop", None)) and not loop.is_closed() ): def cancel_tasks(): for task in tasks: task.cancel() loop.call_soon_threadsafe(cancel_tasks) def cancel_task_threadsafe(task: Task): if task and not task.done(): run_in_loop(task.get_loop(), task.cancel) def make_async( func: Callable[P, T], executor: Executor | None = None, ) -> Callable[P, Awaitable[T]]: """ Take a blocking function, and run it on in an executor thread. This function prevents the blocking function from blocking the asyncio event loop. The code in this function needs to be thread safe. """ def _async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Future[T]: loop = asyncio.get_event_loop() p_func = partial(func, *args, **kwargs) return loop.run_in_executor(executor=executor, func=p_func) return _async_wrapper def run_in_loop(loop: AbstractEventLoop, function: Callable, *args): if in_loop(loop): function(*args) elif not loop.is_closed(): loop.call_soon_threadsafe(function, *args) def in_loop(event_loop: AbstractEventLoop) -> bool: try: return asyncio.get_running_loop() == event_loop except RuntimeError: return False # A hack to pass mypy if TYPE_CHECKING: def anext(it: AsyncGenerator[T, None]): return it.__anext__() async def merge_async_iterators( *iterators: AsyncGenerator[T, None], ) -> AsyncGenerator[tuple[int, T], None]: """Merge multiple asynchronous iterators into a single iterator. This method handle the case where some iterators finish before others. When it yields, it yields a tuple (i, item) where i is the index of the iterator that yields the item. """ if len(iterators) == 1: # Fast-path single iterator case. async for item in iterators[0]: yield 0, item return loop = asyncio.get_running_loop() awaits = {loop.create_task(anext(it)): (i, it) for i, it in enumerate(iterators)} try: while awaits: done, _ = await asyncio.wait(awaits.keys(), return_when=FIRST_COMPLETED) for d in done: pair = awaits.pop(d) try: item = await d i, it = pair awaits[loop.create_task(anext(it))] = pair yield i, item except StopAsyncIteration: pass finally: # Cancel any remaining iterators for f, (_, it) in awaits.items(): with contextlib.suppress(BaseException): f.cancel() await it.aclose() async def collect_from_async_generator(iterator: AsyncGenerator[T, None]) -> list[T]: """Collect all items from an async generator into a list.""" items = [] async for item in iterator: items.append(item) return items
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/async_utils.py", "license": "Apache License 2.0", "lines": 259, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/utils_/test_func_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # ruff: noqa import pytest from vllm.utils.func_utils import deprecate_kwargs, supports_kw from ..utils import error_on_warning def test_deprecate_kwargs_always(): @deprecate_kwargs("old_arg", is_deprecated=True) def dummy(*, old_arg: object = None, new_arg: object = None): pass with pytest.warns(DeprecationWarning, match="'old_arg'"): dummy(old_arg=1) with error_on_warning(DeprecationWarning): dummy(new_arg=1) def test_deprecate_kwargs_never(): @deprecate_kwargs("old_arg", is_deprecated=False) def dummy(*, old_arg: object = None, new_arg: object = None): pass with error_on_warning(DeprecationWarning): dummy(old_arg=1) with error_on_warning(DeprecationWarning): dummy(new_arg=1) def test_deprecate_kwargs_dynamic(): is_deprecated = True @deprecate_kwargs("old_arg", is_deprecated=lambda: is_deprecated) def dummy(*, old_arg: object = None, new_arg: object = None): pass with pytest.warns(DeprecationWarning, match="'old_arg'"): dummy(old_arg=1) with error_on_warning(DeprecationWarning): dummy(new_arg=1) is_deprecated = False with error_on_warning(DeprecationWarning): dummy(old_arg=1) with error_on_warning(DeprecationWarning): dummy(new_arg=1) def test_deprecate_kwargs_additional_message(): @deprecate_kwargs("old_arg", is_deprecated=True, additional_message="abcd") def dummy(*, old_arg: object = None, new_arg: object = None): pass with pytest.warns(DeprecationWarning, match="abcd"): dummy(old_arg=1) @pytest.mark.parametrize( ("callable", "kw_name", "requires_kw_only", "allow_var_kwargs", "is_supported"), [ # Tests for positional argument support (lambda foo: None, "foo", True, True, False), (lambda foo: None, "foo", False, True, True), # Tests for positional or keyword / keyword only (lambda foo=100: None, "foo", True, True, False), (lambda *, foo: None, "foo", False, True, True), # Tests to make sure the names of variadic params are NOT supported (lambda *args: None, "args", False, True, False), (lambda **kwargs: None, "kwargs", False, True, False), # Tests for if we allow var kwargs to add support (lambda foo: None, "something_else", False, True, False), (lambda foo, **kwargs: None, "something_else", False, True, True), (lambda foo, **kwargs: None, "kwargs", True, True, False), (lambda foo, **kwargs: None, "foo", True, True, False), ], ) def test_supports_kw( callable, kw_name, requires_kw_only, allow_var_kwargs, is_supported ): assert ( supports_kw( callable=callable, kw_name=kw_name, requires_kw_only=requires_kw_only, allow_var_kwargs=allow_var_kwargs, ) == is_supported )
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_func_utils.py", "license": "Apache License 2.0", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/utils_/test_jsontree.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.utils.jsontree import json_count_leaves def test_json_count_leaves(): """Test json_count_leaves function from jsontree utility.""" # Single leaf values assert json_count_leaves(42) == 1 assert json_count_leaves("hello") == 1 assert json_count_leaves(None) == 1 # Empty containers assert json_count_leaves([]) == 0 assert json_count_leaves({}) == 0 assert json_count_leaves(()) == 0 # Flat structures assert json_count_leaves([1, 2, 3]) == 3 assert json_count_leaves({"a": 1, "b": 2}) == 2 assert json_count_leaves((1, 2, 3)) == 3 # Nested structures nested_dict = {"a": 1, "b": {"c": 2, "d": 3}} assert json_count_leaves(nested_dict) == 3 nested_list = [1, [2, 3], 4] assert json_count_leaves(nested_list) == 4 mixed_nested = {"list": [1, 2], "dict": {"x": 3}, "value": 4} assert json_count_leaves(mixed_nested) == 4
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_jsontree.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/models/language/pooling/test_multi_vector_retrieval.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from transformers import AutoModel from tests.models.utils import check_embeddings_close @pytest.mark.parametrize( "model", ["BAAI/bge-m3"], ) @pytest.mark.parametrize("dtype", ["half"]) @torch.inference_mode def test_embed_models(hf_runner, vllm_runner, example_prompts, model: str, dtype: str): with vllm_runner( model, runner="pooling", max_model_len=None, ) as vllm_model: vllm_outputs = vllm_model.token_embed(example_prompts) with hf_runner( model, auto_cls=AutoModel, ) as hf_model: tokenizer = hf_model.tokenizer hf_outputs = [] for prompt in example_prompts: inputs = tokenizer([prompt], return_tensors="pt") inputs = hf_model.wrap_device(inputs) output = hf_model.model(**inputs) embedding = output.last_hidden_state[0].float() # normal hf_outputs.append(embedding.cpu()) for hf_output, vllm_output in zip(hf_outputs, vllm_outputs): check_embeddings_close( embeddings_0_lst=hf_output, embeddings_1_lst=vllm_output, name_0="hf", name_1="vllm", tol=1e-2, )
{ "repo_id": "vllm-project/vllm", "file_path": "tests/models/language/pooling/test_multi_vector_retrieval.py", "license": "Apache License 2.0", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/reasoning/test_deepseekv3_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from transformers import AutoTokenizer from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest from vllm.entrypoints.openai.engine.protocol import DeltaMessage from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser from vllm.reasoning.deepseek_v3_reasoning_parser import DeepSeekV3ReasoningParser from vllm.reasoning.identity_reasoning_parser import IdentityReasoningParser REASONING_MODEL_NAME = "deepseek-ai/DeepSeek-V3.1" @pytest.fixture(scope="module") def tokenizer(): return AutoTokenizer.from_pretrained(REASONING_MODEL_NAME) @pytest.mark.parametrize( "thinking,expected_parser_type", [ (True, DeepSeekR1ReasoningParser), (False, IdentityReasoningParser), ], ) def test_parser_selection(tokenizer, thinking, expected_parser_type): parser = DeepSeekV3ReasoningParser( tokenizer, chat_template_kwargs={"thinking": thinking} ) assert isinstance(parser._parser, expected_parser_type) def test_identity_reasoning_parser_basic(tokenizer): parser = IdentityReasoningParser(tokenizer) # Test is_reasoning_end always returns True input_text = "This is some output" input_tokens = tokenizer.tokenize(input_text) input_ids = tokenizer.convert_tokens_to_ids(input_tokens) assert parser.is_reasoning_end(input_ids) is True assert parser.is_reasoning_end_streaming(input_ids, input_ids) is True # Test extract_content_ids returns all input_ids assert parser.extract_content_ids(input_ids) == input_ids # Test extract_reasoning returns (None, model_output) request = ChatCompletionRequest(model="test-model", messages=[], temperature=1.0) reasoning, content = parser.extract_reasoning(input_text, request) assert reasoning is None assert content == input_text # Test extract_reasoning_streaming returns DeltaMessage or None result = parser.extract_reasoning_streaming( previous_text="", current_text="Hello world", delta_text="Hello world", previous_token_ids=[], current_token_ids=input_ids, delta_token_ids=input_ids, ) assert isinstance(result, DeltaMessage) assert result.content == "Hello world" # If delta_text is empty, should return None result_none = parser.extract_reasoning_streaming( previous_text="Hello world", current_text="Hello world", delta_text="", previous_token_ids=input_ids, current_token_ids=input_ids, delta_token_ids=[], ) assert result_none is None
{ "repo_id": "vllm-project/vllm", "file_path": "tests/reasoning/test_deepseekv3_reasoning_parser.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/reasoning/deepseek_v3_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Iterable, Sequence from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.chat_completion.protocol import ( ChatCompletionRequest, ) from vllm.entrypoints.openai.engine.protocol import DeltaMessage from vllm.logger import init_logger from vllm.reasoning import ReasoningParser from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser from .identity_reasoning_parser import IdentityReasoningParser logger = init_logger(__name__) class DeepSeekV3ReasoningParser(ReasoningParser): """ V3 parser that delegates to either DeepSeekR1ReasoningParser or IdentityReasoningParser based on `thinking` and `separate_reasoning`. """ def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {} thinking = bool(chat_kwargs.get("thinking", False)) enable_thinking = bool(chat_kwargs.get("enable_thinking", False)) thinking = thinking or enable_thinking if thinking: self._parser = DeepSeekR1ReasoningParser(tokenizer, *args, **kwargs) else: self._parser = IdentityReasoningParser(tokenizer, *args, **kwargs) def is_reasoning_end(self, input_ids: Sequence[int]) -> bool: return self._parser.is_reasoning_end(input_ids) def is_reasoning_end_streaming( self, input_ids: Sequence[int], delta_ids: Iterable[int] ) -> bool: return self._parser.is_reasoning_end_streaming(input_ids, delta_ids) def extract_content_ids(self, input_ids: list[int]) -> list[int]: return self._parser.extract_content_ids(input_ids) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: return self._parser.extract_reasoning(model_output, request) def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: return self._parser.extract_reasoning_streaming( previous_text, current_text, delta_text, previous_token_ids, current_token_ids, delta_token_ids, ) class DeepSeekV3ReasoningWithThinkingParser(DeepSeekV3ReasoningParser): """ DeepSeekV3ReasoningParser that defaults to thinking mode. """ def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {} thinking = chat_kwargs.get("thinking", None) enable_thinking = chat_kwargs.get("enable_thinking", None) if thinking is None and enable_thinking is None: chat_kwargs["thinking"] = True chat_kwargs["enable_thinking"] = True kwargs["chat_template_kwargs"] = chat_kwargs super().__init__(tokenizer, *args, **kwargs)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/reasoning/deepseek_v3_reasoning_parser.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/reasoning/identity_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Iterable, Sequence from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.chat_completion.protocol import ( ChatCompletionRequest, ) from vllm.entrypoints.openai.engine.protocol import DeltaMessage from vllm.logger import init_logger from vllm.reasoning import ReasoningParser logger = init_logger(__name__) class IdentityReasoningParser(ReasoningParser): """ Identity reasoning parser. This parser does not attempt to parse or strip out reasoning tokens. It treats the entire model output as content and ignores reasoning. """ def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) if not self.model_tokenizer: raise ValueError( "The model tokenizer must be passed to the ReasoningParser " "constructor during construction." ) def is_reasoning_end(self, input_ids: Sequence[int]) -> bool: # Always return True, since we never treat reasoning specially return True def is_reasoning_end_streaming( self, input_ids: Sequence[int], delta_ids: Iterable[int] ) -> bool: return True def extract_content_ids(self, input_ids: list[int]) -> list[int]: # Identity: return all tokens as content return input_ids def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: # Just wrap delta_text as content, ignore reasoning if delta_text: return DeltaMessage(content=delta_text) return None def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: # No reasoning separation: return None for reasoning, # and full model_output as content return None, model_output
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/reasoning/identity_reasoning_parser.py", "license": "Apache License 2.0", "lines": 53, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/entrypoints/openai/test_enable_force_include_usage.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import openai import pytest import pytest_asyncio from ...utils import RemoteOpenAIServer @pytest.fixture(scope="module") def chat_server_with_force_include_usage(request): args = [ # use half precision for speed and memory savings in CI environment "--dtype", "bfloat16", "--max-model-len", "128", "--enforce-eager", "--max-num-seqs", "4", "--enable-force-include-usage", "--port", "55857", "--gpu-memory-utilization", "0.2", ] with RemoteOpenAIServer("Qwen/Qwen3-0.6B", args, auto_port=False) as remote_server: yield remote_server @pytest_asyncio.fixture async def chat_client_with_force_include_usage(chat_server_with_force_include_usage): async with chat_server_with_force_include_usage.get_async_client() as async_client: yield async_client @pytest.mark.asyncio async def test_chat_with_enable_force_include_usage( chat_client_with_force_include_usage: openai.AsyncOpenAI, ): messages = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is the capital of France?"}, ] stream = await chat_client_with_force_include_usage.chat.completions.create( model="Qwen/Qwen3-0.6B", messages=messages, max_completion_tokens=10, extra_body=dict(min_tokens=10), temperature=0.0, stream=True, ) last_completion_tokens = 0 async for chunk in stream: if not len(chunk.choices): assert chunk.usage.prompt_tokens >= 0 assert ( last_completion_tokens == 0 or chunk.usage.completion_tokens > last_completion_tokens or ( not chunk.choices and chunk.usage.completion_tokens == last_completion_tokens ) ) assert chunk.usage.total_tokens == ( chunk.usage.prompt_tokens + chunk.usage.completion_tokens ) else: assert chunk.usage is None @pytest.fixture(scope="module") def transcription_server_with_force_include_usage(): args = [ # use half precision for speed and memory savings in CI environment "--dtype", "bfloat16", "--max-num-seqs", "4", "--enforce-eager", "--enable-force-include-usage", "--gpu-memory-utilization", "0.2", ] with RemoteOpenAIServer("openai/whisper-large-v3-turbo", args) as remote_server: yield remote_server @pytest_asyncio.fixture async def transcription_client_with_force_include_usage( transcription_server_with_force_include_usage, ): async with ( transcription_server_with_force_include_usage.get_async_client() as async_client ): yield async_client @pytest.mark.asyncio async def test_transcription_with_enable_force_include_usage( transcription_client_with_force_include_usage, winning_call ): res = ( await transcription_client_with_force_include_usage.audio.transcriptions.create( model="openai/whisper-large-v3-turbo", file=winning_call, language="en", temperature=0.0, stream=True, timeout=30, ) ) async for chunk in res: if not len(chunk.choices): # final usage sent usage = chunk.usage assert isinstance(usage, dict) assert usage["prompt_tokens"] > 0 assert usage["completion_tokens"] > 0 assert usage["total_tokens"] > 0 else: assert not hasattr(chunk, "usage")
{ "repo_id": "vllm-project/vllm", "file_path": "tests/entrypoints/openai/test_enable_force_include_usage.py", "license": "Apache License 2.0", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/v1/e2e/test_pooling_chunked_prefill.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch.nn as nn from vllm.platforms import current_platform prompt = """ Generals gathered in their masses Just like witches at black masses Evil minds that plot destruction Sorcerer of death's construction In the fields, the bodies burning As the war machine keeps turning Death and hatred to mankind Poisoning their brainwashed minds Oh, Lord, yeah Politicians hide themselves away They only started the war Why should they go out to fight? They leave that all to the poor, yeah Time will tell on their power minds Making war just for fun Treating people just like pawns in chess Wait till their judgment day comes, yeah Now, in darkness, world stops turning Ashes where their bodies burning No more war pigs have the power Hand of God has struck the hour Day of Judgment, God is calling On their knees, the war pigs crawling Begging mercies for their sins Satan, laughing, spreads his wings Oh, Lord, yeah """ class WrapperPooler(nn.Module): def __init__(self, pooler): super().__init__() self.pooler = pooler self.chunks = [] def get_pooling_updates(self, task): return self.pooler.get_pooling_updates(task) def forward( self, hidden_states, pooling_metadata, ): self.chunks.append(hidden_states.shape[0]) return self.pooler(hidden_states, pooling_metadata) def inject_pooler(self): model = self.get_model() wrapper = WrapperPooler(model.pooler) model.pooler = wrapper def retrieve_chunks(self): model = self.get_model() chunks = model.pooler.chunks model.pooler.chunks = [] return chunks @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA not available") def test_pooling_chunked_prefill(vllm_runner, monkeypatch): """Test chunked prefill for pooling models with LastPool.""" with monkeypatch.context() as m: m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1") model_id = "Qwen/Qwen3-Embedding-0.6B" chunk_size = 10 # Set chunking parameters to force chunked prefill # Note: Chunked prefill is automatically handled by vLLM # internally based on the model size and prompt with vllm_runner( model_id, runner="pooling", long_prefill_token_threshold=chunk_size, tensor_parallel_size=1, enforce_eager=True, enable_chunked_prefill=True, ) as llm: llm.get_llm().llm_engine.collective_rpc(inject_pooler) tokenizer = llm.get_llm().get_tokenizer() tokens = tokenizer(prompt)["input_ids"] prompt_len = len(tokens) full_chunks, last_chunk = divmod(prompt_len, chunk_size) expected_chunks = [chunk_size] * full_chunks if last_chunk: expected_chunks.append(last_chunk) llm.embed([prompt]) chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0] # Check that PoolerWrapper was called and chunks were received assert len(chunks) > 1 assert chunks == expected_chunks # Disable chunked prefill with vllm_runner( model_id, runner="pooling", tensor_parallel_size=1, enforce_eager=True, ) as llm: llm.get_llm().llm_engine.collective_rpc(inject_pooler) llm.embed([prompt]) chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0] # Check that PoolerWrapper was called and no chunks were received assert len(chunks) == 1 assert chunks[0] == prompt_len @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA not available") def test_pooling_prefix_cache(vllm_runner, monkeypatch): """Test chunked prefill for pooling models with LastPool.""" verses = prompt.split("\n\n") with monkeypatch.context() as m: m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1") model_id = "Qwen/Qwen3-Embedding-0.6B" with vllm_runner( model_id, runner="pooling", enable_prefix_caching=True, tensor_parallel_size=1, enforce_eager=True, ) as llm: llm.get_llm().llm_engine.collective_rpc(inject_pooler) tokenizer = llm.get_llm().get_tokenizer() prompt1 = "\n\n".join([verses[0], verses[1]]) prompt2 = "\n\n".join([verses[0], verses[2]]) tokens1 = tokenizer(prompt1)["input_ids"] tokens2 = tokenizer(prompt2)["input_ids"] prompt1_len = len(tokens1) prompt2_len = len(tokens2) llm.embed([prompt1]) chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0] assert len(chunks) == 1 assert chunks[0] == prompt1_len llm.embed([prompt2]) chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0] assert len(chunks) == 1 assert chunks[0] <= prompt1_len assert chunks[0] < prompt2_len vllm_config = llm.get_llm().llm_engine.vllm_config cache_config = vllm_config.cache_config print(f"{cache_config=}") # Prefixes are cached in blocks assert (prompt2_len - chunks[0]) % cache_config.block_size == 0
{ "repo_id": "vllm-project/vllm", "file_path": "tests/v1/e2e/test_pooling_chunked_prefill.py", "license": "Apache License 2.0", "lines": 136, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/entrypoints/openai/test_protocol.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from openai_harmony import ( Message, ) from vllm.entrypoints.openai.responses.protocol import ( serialize_message, serialize_messages, ) def test_serialize_message() -> None: dict_value = {"a": 1, "b": "2"} assert serialize_message(dict_value) == dict_value msg_value = { "role": "assistant", "name": None, "content": [{"type": "text", "text": "Test 1"}], "channel": "analysis", } msg = Message.from_dict(msg_value) assert serialize_message(msg) == msg_value def test_serialize_messages() -> None: assert serialize_messages(None) is None assert serialize_messages([]) is None dict_value = {"a": 3, "b": "4"} msg_value = { "role": "assistant", "name": None, "content": [{"type": "text", "text": "Test 2"}], "channel": "analysis", } msg = Message.from_dict(msg_value) assert serialize_messages([msg, dict_value]) == [msg_value, dict_value]
{ "repo_id": "vllm-project/vllm", "file_path": "tests/entrypoints/openai/test_protocol.py", "license": "Apache License 2.0", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/models/language/pooling/test_head_dtype.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest import torch from transformers import AutoModelForSequenceClassification @pytest.mark.parametrize( "model", ["nie3e/sentiment-polish-gpt2-small"], ) @pytest.mark.parametrize("dtype", ["half"]) def test_classify_models( hf_runner, vllm_runner, example_prompts, model: str, dtype: str, ) -> None: with hf_runner( model, dtype=dtype, auto_cls=AutoModelForSequenceClassification ) as hf_model: hf_outputs = hf_model.classify(example_prompts) for head_dtype_str in ["float32", "model"]: with vllm_runner( model, max_model_len=512, dtype=dtype, hf_overrides={"head_dtype": head_dtype_str}, ) as vllm_model: model_config = vllm_model.llm.llm_engine.model_config model_dtype = model_config.dtype head_dtype = model_config.head_dtype if head_dtype_str == "float32": assert head_dtype == torch.float32 elif head_dtype_str == "model": assert head_dtype == model_dtype vllm_outputs = vllm_model.classify(example_prompts) for hf_output, vllm_output in zip(hf_outputs, vllm_outputs): hf_output = torch.tensor(hf_output).float() vllm_output = torch.tensor(vllm_output).float() assert torch.allclose(hf_output, vllm_output, atol=1e-2)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/models/language/pooling/test_head_dtype.py", "license": "Apache License 2.0", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/reasoning/test_ernie45_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from transformers import AutoTokenizer from tests.reasoning.utils import run_reasoning_extraction from vllm.reasoning import ReasoningParser, ReasoningParserManager parser_name = "ernie45" REASONING_MODEL_NAME = "baidu/ERNIE-4.5-21B-A3B-Thinking" @pytest.fixture(scope="module") def ernie45_tokenizer(): return AutoTokenizer.from_pretrained(REASONING_MODEL_NAME) # 带 </think>,非stream WITH_THINK = { "output": "abc</think>def", "reasoning": "abc", "content": "def", } # 带 </think>,stream WITH_THINK_STREAM = { "output": "abc</think>def", "reasoning": "abc", "content": "def", } # without </think>, all is reasoning WITHOUT_THINK = { "output": "abc", "reasoning": "abc", "content": None, } # without </think>, all is reasoning WITHOUT_THINK_STREAM = { "output": "abc", "reasoning": "abc", "content": None, } COMPLETE_REASONING = { "output": "abc</think>", "reasoning": "abc", "content": None, } MULTILINE_REASONING = { "output": "abc\nABC</think>def\nDEF", "reasoning": "abc\nABC", "content": "def\nDEF", } TEST_CASES = [ pytest.param( False, WITH_THINK, id="with_think", ), pytest.param( True, WITH_THINK_STREAM, id="with_think_stream", ), pytest.param( False, WITHOUT_THINK, id="without_think", ), pytest.param( True, WITHOUT_THINK_STREAM, id="without_think_stream", ), pytest.param( False, COMPLETE_REASONING, id="complete_reasoning", ), pytest.param( True, COMPLETE_REASONING, id="complete_reasoning_stream", ), pytest.param( False, MULTILINE_REASONING, id="multiline_reasoning", ), pytest.param( True, MULTILINE_REASONING, id="multiline_reasoning_stream", ), ] @pytest.mark.parametrize("streaming, param_dict", TEST_CASES) def test_reasoning( streaming: bool, param_dict: dict, ernie45_tokenizer, ): output = ernie45_tokenizer.tokenize(param_dict["output"]) output_tokens: list[str] = [] for token in output: one_token = ernie45_tokenizer.convert_tokens_to_string([token]) if one_token: output_tokens.append(one_token) parser: ReasoningParser = ReasoningParserManager.get_reasoning_parser(parser_name)( ernie45_tokenizer ) reasoning, content = run_reasoning_extraction( parser, output_tokens, streaming=streaming ) print() assert reasoning == param_dict["reasoning"] assert content == param_dict["content"]
{ "repo_id": "vllm-project/vllm", "file_path": "tests/reasoning/test_ernie45_reasoning_parser.py", "license": "Apache License 2.0", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/reasoning/ernie45_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.chat_completion.protocol import ( ChatCompletionRequest, ) from vllm.entrypoints.openai.engine.protocol import DeltaMessage from vllm.logger import init_logger from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser logger = init_logger(__name__) class Ernie45ReasoningParser(BaseThinkingReasoningParser): """ Reasoning parser for Ernie45 thinking model. The Ernie45 thinking model ouput format is abc\n</think>\n\n<response>\ndef\n</response>\n or abc\n</think>\ndef """ response_start_token: str = "<response>" response_end_token: str = "</response>" newline_token: str = "<0x0A>" @property def start_token(self) -> str: """The token that starts reasoning content.""" return "<think>" @property def end_token(self) -> str: """The token that ends reasoning content.""" return "</think>" def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) if not self.model_tokenizer: raise ValueError( "The model tokenizer must be passed to the ReasoningParser " "constructor during construction." ) self.start_token_id = self.vocab.get(self.start_token) self.end_token_id = self.vocab.get(self.end_token) self.response_start_token_id = self.vocab.get(self.response_start_token) self.response_end_token_id = self.vocab.get(self.response_end_token) self.newline_token_id = self.vocab.get(self.newline_token) self.parser_token_ids = [self.end_token_id, self.response_end_token_id] if self.start_token_id is None or self.end_token_id is None: raise RuntimeError( "Ernie45 reasoning parser could not locate think start/end " "tokens in the tokenizer!" ) def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: """ Extract reasoning content from a delta message. Handles streaming output where previous + delta = current. Uses token IDs for faster processing. The Ernie45 thinking model ouput format is abc\n</think>\n\n<response>\ndef\n</response>\n or abc\n</think>\ndef - 'abc' goes to reasoning - 'def' goes to content """ # Skip single special tokens if len(delta_token_ids) == 1 and ( delta_token_ids[0] in [ self.start_token_id, self.end_token_id, self.response_start_token_id, self.response_end_token_id, ] ): return None # No <think> in previous or delta, also need to check for </think>. # Because the model may have generated </think> without <think> if self.end_token_id in delta_token_ids: # </think> in delta with more tokens, # extract reasoning content and content think_end_index = delta_text.find(self.end_token) reasoning = delta_text[:think_end_index] content = delta_text[think_end_index + len(self.end_token) :] content = content.lstrip("\n") response_start_idx = content.find(self.response_start_token) response_end_idx = content.rfind(self.response_end_token) if response_start_idx != -1: content = content[response_start_idx + len(self.response_start_token) :] if response_end_idx != -1: content = content[:response_end_idx] return DeltaMessage( reasoning=reasoning, content=content if content else None, ) elif self.end_token_id in previous_token_ids: # </think> in previous, thinking content ends content = delta_text if self.response_start_token_id in delta_token_ids: content = content.lstrip("\n") response_start_idx = content.find(self.response_start_token) content = content[response_start_idx + len(self.response_start_token) :] # if have </response>, remove it response_end_idx = content.rfind(self.response_end_token) if response_end_idx != -1: content = content[:response_end_idx] elif self.response_end_token_id in delta_token_ids: response_end_idx = content.rfind(self.response_end_token) content = content[:response_end_idx] # remove \n after </think> or </response> if previous_token_ids[-1] in self.parser_token_ids and ( len(delta_token_ids) > 0 and delta_token_ids[0] == self.newline_token_id ): content = content.lstrip("\n") # remove \n after </think>\n if ( len(previous_token_ids) > 1 and previous_token_ids[-2] == self.end_token_id ) and ( len(delta_token_ids) > 0 and delta_token_ids[0] == self.newline_token_id ): content = content.lstrip("\n") return DeltaMessage(content=content if content else None) else: # no </think> in previous or delta, reasoning content continues return DeltaMessage(reasoning=delta_text) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: """ Extract reasoning content from the model output. The Ernie45 thinking model ouput format is abc\n</think>\n\n\n<response>\ndef\n</response>\n or abc\n</think>\ndef - 'abc' goes to reasoning - 'def' goes to content Returns: tuple[Optional[str], Optional[str]]: reasoning content and content """ reasoning, content = super().extract_reasoning(model_output, request) if content: start_idx = content.find(self.response_start_token) end_idx = content.rfind(self.response_end_token) # Simultaneously existing and in the correct order if start_idx != -1 and end_idx != -1 and start_idx < end_idx: content = content[start_idx + len(self.response_start_token) : end_idx] final_content = content or None return reasoning, final_content
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/reasoning/ernie45_reasoning_parser.py", "license": "Apache License 2.0", "lines": 149, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/models/language/pooling/test_splade_sparse_pooler.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import types import pytest import torch import torch.nn as nn from vllm.model_executor.models.bert import ( BertMLMHead, SPLADESparsePooler, ) # --------------------------------------------------------------------- # Functional test: SPLADE formula correctness (no HF download needed) # --------------------------------------------------------------------- @pytest.mark.parametrize("B,T,H,V", [(2, 3, 5, 7)]) @torch.inference_mode def test_splade_pooler_matches_reference_formula(B, T, H, V): """Ensure SPLADESparsePooler forward() matches the mathematical formula: log1p(relu(logits)) -> max over sequence length (after masking).""" torch.manual_seed(0) # Prepare [B] sequences of shape [T, H] hs_list = [torch.randn(T, H) for _ in range(B)] hs_tenser = torch.cat(hs_list) # Simulate PoolingMetadata (only required fields) prompt_lens = [T, T - 1] prompt_lens_tenser = torch.tensor(prompt_lens, dtype=torch.int32) token_ids = torch.tensor( [ [101, 5, 102], # Batch 0: [CLS], token, [SEP] [101, 6, 6], # Batch 1: [CLS], token, token (last token ignored) ], dtype=torch.long, ) meta = types.SimpleNamespace( prompt_lens=prompt_lens_tenser, prompt_token_ids=token_ids ) # MLM head (prefer BertMLMHead, fallback to Linear if unavailable) try: mlm_head = BertMLMHead(hidden_size=H, vocab_size=V, layer_norm_eps=1e-12) except Exception: mlm_head = nn.Linear(H, V, bias=True) # Forward pass through SPLADE pooler pooler = SPLADESparsePooler(mlm_head=mlm_head, pooling="max", remove_cls_sep=True) pooled = pooler(hidden_states=hs_tenser, pooling_metadata=meta) # list of [V] # Basic output checks assert isinstance(pooled, torch.Tensor) and len(pooled) == B for vec in pooled: assert vec.shape == (V,) assert torch.isfinite(vec).all() assert (vec >= 0).all(), "SPLADE outputs must be non-negative." # Reference implementation for comparison def ref_one(hs: torch.Tensor, L: int, tid_row: torch.Tensor) -> torch.Tensor: keep = torch.ones(L, dtype=torch.bool) if L > 0 and tid_row[0].item() == 101: # remove CLS keep[0] = False if L > 0 and tid_row[L - 1].item() == 102: # remove SEP keep[L - 1] = False valid = hs[:L][keep[:L]] if valid.numel() == 0: return torch.zeros(V, dtype=torch.float32) logits = mlm_head(valid) # [L', V] scores = torch.log1p(torch.relu(logits)) # [L', V] return scores.max(dim=0).values.to(torch.float32) torch.testing.assert_close( pooled[0], ref_one(hs_list[0], prompt_lens[0], token_ids[0]), rtol=1e-4, atol=1e-4, ) torch.testing.assert_close( pooled[1], ref_one(hs_list[1], prompt_lens[1], token_ids[1]), rtol=1e-4, atol=1e-4, )
{ "repo_id": "vllm-project/vllm", "file_path": "tests/models/language/pooling/test_splade_sparse_pooler.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm: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.utils.torch_utils import set_random_seed 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.float16, 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.""" set_random_seed(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.""" set_random_seed(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}" ) set_random_seed(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.""" set_random_seed(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.""" set_random_seed(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.""" set_random_seed(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.""" set_random_seed(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) @pytest.mark.parametrize("num_tokens", [1, 128, 1024]) @pytest.mark.parametrize("hidden_size", [64, 256, 1024]) @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32]) @pytest.mark.parametrize("has_gate", [True, False]) @pytest.mark.parametrize("group_size", [None, 64]) @pytest.mark.parametrize("norm_before_gate", [True, False]) @torch.inference_mode() def test_rmsnorm_gated_forward_native_dtype( default_vllm_config, num_tokens: int, hidden_size: int, dtype: torch.dtype, has_gate: bool, group_size: int | None, norm_before_gate: bool, ): """Test that RMSNormGated.forward_native preserves input dtype.""" if group_size is not None and hidden_size % group_size != 0: pytest.skip( f"hidden_size {hidden_size} not divisible by group_size {group_size}" ) from vllm.model_executor.layers.layernorm import RMSNormGated device = torch.device("cuda:0") set_random_seed(42) layer = RMSNormGated( hidden_size, eps=1e-5, group_size=group_size, norm_before_gate=norm_before_gate, device=device, dtype=dtype, ) x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) z = ( torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) if has_gate else None ) out = layer.forward_native(x, z) # Verify dtype preservation assert out.dtype == dtype, f"Expected {dtype}, got {out.dtype}" # Verify numerical correctness against reference ref_out = rms_norm_ref( x, layer.weight, layer.bias, z=z, eps=1e-5, group_size=group_size, norm_before_gate=norm_before_gate, upcast=True, ) 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!")
{ "repo_id": "vllm-project/vllm", "file_path": "tests/kernels/test_fla_layernorm_guard.py", "license": "Apache License 2.0", "lines": 377, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/compile/test_aot_compile.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import functools import hashlib import multiprocessing import pickle import tempfile from contextlib import contextmanager from pathlib import Path from unittest.mock import Mock, patch import pytest import torch import vllm.model_executor.layers.activation from vllm.compilation.caching import ( StandaloneCompiledArtifacts, VllmSerializableFunction, ) from vllm.compilation.decorators import support_torch_compile from vllm.config import ( CompilationConfig, CompilationMode, VllmConfig, set_current_vllm_config, ) from vllm.envs import disable_envs_cache from vllm.forward_context import set_forward_context from vllm.utils.torch_utils import is_torch_equal_or_newer from ..utils import create_new_process_for_each_test @pytest.fixture def vllm_tmp_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: """Fixture that sets VLLM_CACHE_ROOT to a temporary directory.""" monkeypatch.setenv("VLLM_CACHE_ROOT", str(tmp_path / "vllm_cache")) return tmp_path def reference_fn(x: torch.Tensor): assert x.shape[0] <= 42 assert x.shape[0] % 2 == 0 for _ in range(3000): x = x + x.shape[0] return x def reference_fn_tuple(x: torch.Tensor): """Reference function that returns a tuple of tensors.""" assert x.shape[0] <= 42 assert x.shape[0] % 2 == 0 for _ in range(3000): x = x + x.shape[0] return x, x * 2 @support_torch_compile class CompiledMod(torch.nn.Module): def __init__(self, **kwargs): super().__init__() def forward(self, x: torch.Tensor): return reference_fn(x) @support_torch_compile class CompiledModTuple(torch.nn.Module): """A compiled module that returns a tuple of tensors.""" def __init__(self, **kwargs): super().__init__() def forward(self, x: torch.Tensor): return reference_fn_tuple(x) def make_vllm_config() -> VllmConfig: return VllmConfig( compilation_config=CompilationConfig( mode=CompilationMode.VLLM_COMPILE, backend="inductor", ) ) @contextmanager def use_vllm_config(vllm_config: VllmConfig): with set_forward_context({}, vllm_config), set_current_vllm_config(vllm_config): yield @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_no_dynamo_cache_entry(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: vllm_config = make_vllm_config() args = (torch.randn(10, 10),) expected = reference_fn(*args) with use_vllm_config(vllm_config): m.setenv("VLLM_USE_AOT_COMPILE", "0") m.setenv("VLLM_USE_MEGA_AOT_ARTIFACT", "1") m.setenv("VLLM_USE_STANDALONE_COMPILE", "1") with ( pytest.raises(RuntimeError, match="Detected recompile"), torch.compiler.set_stance("fail_on_recompile"), ): CompiledMod(vllm_config=vllm_config)(*args) disable_envs_cache() m.setenv("VLLM_USE_AOT_COMPILE", "1") torch._dynamo.reset() with torch.compiler.set_stance("fail_on_recompile"): actual = CompiledMod(vllm_config=vllm_config)(*args) assert torch.allclose(actual, expected) @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_force_aot_load(monkeypatch: pytest.MonkeyPatch): with tempfile.TemporaryDirectory() as tmpdirname, monkeypatch.context() as m: args = (torch.randn(10, 10),) m.setenv("VLLM_USE_AOT_COMPILE", "1") m.setenv("VLLM_USE_MEGA_AOT_ARTIFACT", "1") m.setenv("VLLM_USE_STANDALONE_COMPILE", "1") m.setenv("VLLM_FORCE_AOT_LOAD", "1") m.setenv("VLLM_CACHE_ROOT", tmpdirname) vllm_config = make_vllm_config() with use_vllm_config(vllm_config), pytest.raises(FileNotFoundError): CompiledMod(vllm_config=vllm_config)(*args) @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_save_and_load(monkeypatch: pytest.MonkeyPatch): with monkeypatch.context() as m: args = (torch.randn(10, 10),) with tempfile.TemporaryDirectory() as tmpdirname: m.setenv("VLLM_CACHE_ROOT", tmpdirname) m.setenv("VLLM_USE_AOT_COMPILE", "1") m.setenv("VLLM_USE_MEGA_AOT_ARTIFACT", "1") m.setenv("VLLM_USE_STANDALONE_COMPILE", "1") vllm_config = make_vllm_config() with use_vllm_config(vllm_config): compiled_mod = CompiledMod(vllm_config=vllm_config) expected = compiled_mod(*args) disable_envs_cache() m.setenv("VLLM_FORCE_AOT_LOAD", "1") vllm_config = make_vllm_config() with use_vllm_config(vllm_config): cached_mod = CompiledMod(vllm_config=vllm_config) ret = cached_mod(*args) assert cached_mod.was_aot_compile_fn_loaded_from_disk, ( "Expected was_aot_compile_fn_loaded_from_disk to be True" ) assert torch.allclose(ret, expected) @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_save_and_load_slice(monkeypatch: pytest.MonkeyPatch): def foo(x: torch.Tensor): return x[slice(0, x.shape[0])] vllm_config = make_vllm_config() example_input = torch.randn(10, 10) torch._dynamo.mark_dynamic(example_input, 0) gm = torch.fx.symbolic_trace(foo) assert "getitem_1 = x[slice(0, getitem, None)]" in gm.code with use_vllm_config(vllm_config): payload = VllmSerializableFunction.serialize_compile_artifacts( VllmSerializableFunction(gm, (example_input,), "", foo) ) fn = VllmSerializableFunction.deserialize_compile_artifacts(payload) assert gm.code == fn.graph_module.code @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_cache_load_returns_tuple_consistency(monkeypatch: pytest.MonkeyPatch): """ Test that cache loading correctly handles the returns_tuple logic. This verifies that when a model returns a single tensor (not a tuple), the output type is consistent between fresh compilation and cache load. Without the fix, cached artifacts would return [tensor] instead of tensor. """ with monkeypatch.context() as m: args = (torch.randn(10, 10),) with tempfile.TemporaryDirectory() as tmpdirname: m.setenv("VLLM_CACHE_ROOT", tmpdirname) m.setenv("VLLM_USE_AOT_COMPILE", "1") m.setenv("VLLM_USE_MEGA_AOT_ARTIFACT", "1") m.setenv("VLLM_USE_STANDALONE_COMPILE", "1") vllm_config = make_vllm_config() # Fresh compilation with use_vllm_config(vllm_config): compiled_mod = CompiledMod(vllm_config=vllm_config) fresh_result = compiled_mod(*args) fresh_result_type = type(fresh_result) # Verify fresh result is a tensor, not a tuple/list assert isinstance(fresh_result, torch.Tensor), ( f"Fresh compile should return tensor, got {fresh_result_type}" ) disable_envs_cache() # Load from cache m.setenv("VLLM_FORCE_AOT_LOAD", "1") vllm_config = make_vllm_config() with use_vllm_config(vllm_config): cached_mod = CompiledMod(vllm_config=vllm_config) cached_result = cached_mod(*args) cached_result_type = type(cached_result) # Verify cache was actually loaded assert cached_mod.was_aot_compile_fn_loaded_from_disk, ( "Expected was_aot_compile_fn_loaded_from_disk to be True after " "loading from cache" ) # Verify cached result has same type as fresh result assert isinstance(cached_result, torch.Tensor), ( f"Cache load should return tensor, got {cached_result_type}. " "This indicates the returns_tuple logic is not being applied " "correctly when loading from cache." ) # Verify values match assert torch.allclose(cached_result, fresh_result), ( "Cached result values should match fresh compilation" ) @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_cache_load_returns_tuple_consistency_tuple_output( monkeypatch: pytest.MonkeyPatch, ): """ Test that cache loading correctly handles models that return tuples. This verifies that when a model returns a tuple of tensors, the output type is preserved as a tuple between fresh compilation and cache load. """ with monkeypatch.context() as m: args = (torch.randn(10, 10),) with tempfile.TemporaryDirectory() as tmpdirname: m.setenv("VLLM_CACHE_ROOT", tmpdirname) m.setenv("VLLM_USE_AOT_COMPILE", "1") m.setenv("VLLM_USE_MEGA_AOT_ARTIFACT", "1") m.setenv("VLLM_USE_STANDALONE_COMPILE", "1") vllm_config = make_vllm_config() # Fresh compilation with tuple-returning model with use_vllm_config(vllm_config): compiled_mod = CompiledModTuple(vllm_config=vllm_config) fresh_result = compiled_mod(*args) fresh_result_type = type(fresh_result) # Verify fresh result is a tuple assert isinstance(fresh_result, tuple), ( f"Fresh compile should return tuple, got {fresh_result_type}" ) assert len(fresh_result) == 2, ( f"Fresh compile should return 2-tuple, got {len(fresh_result)}" ) disable_envs_cache() # Load from cache m.setenv("VLLM_FORCE_AOT_LOAD", "1") vllm_config = make_vllm_config() with use_vllm_config(vllm_config): cached_mod = CompiledModTuple(vllm_config=vllm_config) cached_result = cached_mod(*args) cached_result_type = type(cached_result) # Verify cache was actually loaded assert cached_mod.was_aot_compile_fn_loaded_from_disk, ( "Expected was_aot_compile_fn_loaded_from_disk to be True after " "loading from cache" ) # Verify cached result is also a tuple assert isinstance(cached_result, tuple), ( f"Cache load should return tuple, got {cached_result_type}. " "This indicates the returns_tuple logic is not preserving " "tuple outputs when loading from cache." ) assert len(cached_result) == 2, ( f"Cache load should return 2-tuple, got {len(cached_result)}" ) # Verify values match assert torch.allclose(cached_result[0], fresh_result[0]), ( "Cached result[0] values should match fresh compilation" ) assert torch.allclose(cached_result[1], fresh_result[1]), ( "Cached result[1] values should match fresh compilation" ) @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_shape_env(monkeypatch: pytest.MonkeyPatch): """ Test that the shape environment is correctly serialized and preserved when loading from cache. """ with monkeypatch.context() as m: args = (torch.randn(10, 10),) with tempfile.TemporaryDirectory() as tmpdirname: m.setenv("VLLM_CACHE_ROOT", tmpdirname) m.setenv("VLLM_USE_AOT_COMPILE", "1") m.setenv("VLLM_USE_MEGA_AOT_ARTIFACT", "1") m.setenv("VLLM_USE_STANDALONE_COMPILE", "1") vllm_config = make_vllm_config() with use_vllm_config(vllm_config): compiled_mod = CompiledMod(vllm_config=vllm_config) compiled_mod(*args) artifacts = compiled_mod.aot_compiled_fn._artifacts guards_string = artifacts.compiled_fn.shape_env.format_guards() assert guards_string == " - s77 <= 42\n - Eq(Mod(s77, 2), 0)" disable_envs_cache() m.setenv("VLLM_FORCE_AOT_LOAD", "1") vllm_config = make_vllm_config() with use_vllm_config(vllm_config): compiled_mod = CompiledMod(vllm_config=vllm_config) compiled_mod(*args) assert compiled_mod.was_aot_compile_fn_loaded_from_disk, ( "Expected was_aot_compile_fn_loaded_from_disk to be True" ) artifacts = compiled_mod.aot_compiled_fn._artifacts guards_string = artifacts.compiled_fn.shape_env.format_guards() assert guards_string == " - s77 <= 42\n - Eq(Mod(s77, 2), 0)" @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") def test_partition_wrapper_applied_on_aot_load( monkeypatch: pytest.MonkeyPatch, vllm_tmp_cache: Path, mocker ): """ Test that partition wrappers are applied when loading AOT cached functions. This test verifies the fix for GitHub issue #31439 where AOT compile caused 2x latency regression when use_inductor_graph_partition=True. The root cause was that partition wrapper context was bypassed when loading from AOT cache. """ from vllm.config import CUDAGraphMode args = (torch.randn(10, 10),) monkeypatch.setenv("VLLM_USE_AOT_COMPILE", "1") # Create config with partition enabled vllm_config = VllmConfig( compilation_config=CompilationConfig( mode=CompilationMode.VLLM_COMPILE, use_inductor_graph_partition=True, cudagraph_mode=CUDAGraphMode.PIECEWISE, ) ) # First compilation - save to cache with use_vllm_config(vllm_config): compiled_mod = CompiledMod(vllm_config=vllm_config) compiled_mod(*args) disable_envs_cache() # Second run - load from cache, verify partition wrapper applied monkeypatch.setenv("VLLM_FORCE_AOT_LOAD", "1") vllm_config = VllmConfig( compilation_config=CompilationConfig( mode=CompilationMode.VLLM_COMPILE, use_inductor_graph_partition=True, cudagraph_mode=CUDAGraphMode.PIECEWISE, ) ) # Use mocker to spy on set_customized_partition_wrappers spy = mocker.spy(torch._inductor.utils, "set_customized_partition_wrappers") with use_vllm_config(vllm_config): compiled_mod = CompiledMod(vllm_config=vllm_config) # First call after restart: loads from AOT cache. # This tests the fix for the first call after a restart. compiled_mod(*args) # Verify cache was loaded assert compiled_mod.was_aot_compile_fn_loaded_from_disk, ( "Expected was_aot_compile_fn_loaded_from_disk to be True" ) # Verify partition wrapper was called on AOT load. assert spy.call_count >= 2, ( "Expected partition wrapper to be set and cleared on AOT load, " f"got {spy.call_count} calls" ) # First call should set a wrapper, last call should clear it assert spy.call_args_list[0][0][0] is not None, ( "First call on AOT load should set a wrapper function" ) assert spy.call_args_list[-1][0][0] is None, ( "Last call on AOT load should clear the wrapper" ) # Reset for the next check. spy.reset_mock() # Subsequent call: uses the cached `aot_compiled_fn`. # This tests the fix for subsequent calls. compiled_mod(*args) # Verify partition wrapper was called on the subsequent call. assert spy.call_count >= 2, ( "Expected partition wrapper set and cleared on subsequent " f"call, got {spy.call_count} calls" ) assert spy.call_args_list[0][0][0] is not None, ( "First call on subsequent call should set a wrapper function" ) assert spy.call_args_list[-1][0][0] is None, ( "Last call on subsequent call should clear the wrapper" ) @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") @create_new_process_for_each_test("spawn") def test_gpt2_cache_hit(monkeypatch: pytest.MonkeyPatch): """ Test that compiling gpt2 twice results in a cache hit and capture torch dynamic symbol creations to ensure make_symbol not called on cache hit. """ import torch.fx.experimental.symbolic_shapes as symbolic_shapes_module from torch.utils._sympy.symbol import make_symbol from vllm import LLM create_symbol_counter = multiprocessing.Value("i", 0) original_make_symbol = make_symbol @functools.wraps(original_make_symbol) def counting_make_symbol(prefix, idx, **kwargs): with create_symbol_counter.get_lock(): create_symbol_counter.value += 1 return original_make_symbol(prefix, idx, **kwargs) symbolic_shapes_module.make_symbol = counting_make_symbol try: with monkeypatch.context() as m, tempfile.TemporaryDirectory() as tmpdirname: m.setenv("VLLM_CACHE_ROOT", tmpdirname) m.setenv("VLLM_USE_AOT_COMPILE", "1") # First compilation - initialize model and generate llm_model = LLM( model="gpt2", compilation_config=CompilationConfig( mode=CompilationMode.VLLM_COMPILE, ), max_model_len=256, ) llm_model.generate("Hello, my name is") assert create_symbol_counter.value == 2 create_symbol_counter.value = 0 # Clean up first model del llm_model disable_envs_cache() vllm.model_executor.layers.activation._ACTIVATION_REGISTRY._dict.clear() # Second compilation - should hit cache m.setenv("VLLM_FORCE_AOT_LOAD", "1") llm_model = LLM( model="gpt2", compilation_config=CompilationConfig( mode=CompilationMode.VLLM_COMPILE, ), max_model_len=256, ) llm_model.generate("Hello, my name is") assert create_symbol_counter.value == 0 finally: # Restore original method symbolic_shapes_module.make_symbol = original_make_symbol @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") class TestStandaloneCompiledArtifacts: def test_init(self): cache = StandaloneCompiledArtifacts() assert cache.submodule_bytes == {} assert cache.submodule_bytes_store == {} assert cache.loaded_submodule_store == {} def test_insert_new_artifact(self): cache = StandaloneCompiledArtifacts() test_data = b"test_artifact_data" submod_name = "test_submod" shape = "s1" hasher = hashlib.sha256() hasher.update(test_data) expected_hash = hasher.hexdigest() cache.insert(submod_name, shape, test_data) assert f"{submod_name}_{shape}" in cache.submodule_bytes assert cache.submodule_bytes[f"{submod_name}_{shape}"] == expected_hash assert expected_hash in cache.submodule_bytes_store assert cache.submodule_bytes_store[expected_hash] == test_data def test_insert_duplicate_artifact(self): cache = StandaloneCompiledArtifacts() test_data = b"duplicate_test_data" submod_name1 = "submod1" submod_name2 = "submod2" shape = "s2" cache.insert(submod_name1, shape, test_data) cache.insert(submod_name2, shape, test_data) hash1 = cache.submodule_bytes[f"{submod_name1}_{shape}"] hash2 = cache.submodule_bytes[f"{submod_name2}_{shape}"] assert hash1 == hash2 assert len(cache.submodule_bytes_store) == 1 assert len(cache.submodule_bytes) == 2 def test_get_artifact(self): cache = StandaloneCompiledArtifacts() test_data = b"retrievable_data" submod_name = "mod1" shape = "shape16" cache.insert(submod_name, shape, test_data) retrieved_data = cache.get(submod_name, shape) assert retrieved_data == test_data def test_get_nonexistent_artifact(self): cache = StandaloneCompiledArtifacts() with pytest.raises(KeyError): cache.get("nonexistent", "shape") def test_size_bytes(self): cache = StandaloneCompiledArtifacts() assert cache.size_bytes() == 0 data1 = b"x" * 100 data2 = b"y" * 200 cache.insert("mod1", "shape1", data1) cache.insert("mod2", "shape2", data2) assert cache.size_bytes() == 300 def test_num_artifacts_and_entries(self): cache = StandaloneCompiledArtifacts() assert cache.num_artifacts() == 0 assert cache.num_entries() == 0 cache.insert("mod1", "shape1", b"data1") cache.insert("mod2", "shape2", b"data2") assert cache.num_artifacts() == 2 assert cache.num_entries() == 2 cache.insert("mod3", "shape3", b"data1") assert cache.num_artifacts() == 2 assert cache.num_entries() == 3 @patch("torch._inductor.standalone_compile.AOTCompiledArtifact.deserialize") def test_load_all_success(self, mock_deserialize): """Test successful loading of all artifacts""" cache = StandaloneCompiledArtifacts() mock_artifact1 = Mock() mock_artifact2 = Mock() mock_deserialize.side_effect = [mock_artifact1, mock_artifact2] cache.insert("mod1", "shape1", pickle.dumps(b"data1")) cache.insert("mod2", "shape2", pickle.dumps(b"data2")) cache.load_all() assert len(cache.loaded_submodule_store) == 2 assert mock_deserialize.call_count == 2 @patch("torch._inductor.standalone_compile.AOTCompiledArtifact.deserialize") def test_load_all_already_loaded(self, mock_deserialize): """Test that load_all skips if already loaded""" cache = StandaloneCompiledArtifacts() mock_artifact = Mock() cache.submodule_bytes_store["hash1"] = pickle.dumps(b"data1") cache.loaded_submodule_store["hash1"] = mock_artifact cache.load_all() mock_deserialize.assert_not_called() @patch("torch._inductor.standalone_compile.AOTCompiledArtifact.deserialize") def test_get_loaded_artifact(self, mock_deserialize): """Test retrieving loaded artifacts""" cache = StandaloneCompiledArtifacts() mock_artifact = Mock() mock_deserialize.return_value = mock_artifact submod_name = "test_mod" shape = "test_shape" cache.insert(submod_name, shape, pickle.dumps(b"test_data")) cache.load_all() retrieved_artifact = cache.get_loaded(submod_name, shape) assert retrieved_artifact == mock_artifact def test_getstate_setstate(self): cache = StandaloneCompiledArtifacts() cache.insert("mod1", "shape1", b"data1") cache.insert("mod2", "shape2", b"data2") cache.loaded_submodule_store["hash1"] = Mock() state = cache.__getstate__() assert "submodule_bytes" in state assert "submodule_bytes_store" in state assert "loaded_submodule_store" not in state new_cache = StandaloneCompiledArtifacts() new_cache.__setstate__(state) assert new_cache.submodule_bytes == cache.submodule_bytes assert new_cache.submodule_bytes_store == cache.submodule_bytes_store assert new_cache.loaded_submodule_store == {} def test_pickle_roundtrip(self): cache = StandaloneCompiledArtifacts() test_data1 = b"pickle_test_data_1" test_data2 = b"pickle_test_data_2" cache.insert("mod1", "shape1", test_data1) cache.insert("mod2", "shape2", test_data2) pickled_data = pickle.dumps(cache) restored_cache = pickle.loads(pickled_data) assert restored_cache.get("mod1", "shape1") == test_data1 assert restored_cache.get("mod2", "shape2") == test_data2 assert restored_cache.num_artifacts() == cache.num_artifacts() assert restored_cache.num_entries() == cache.num_entries() assert restored_cache.size_bytes() == cache.size_bytes() assert len(restored_cache.loaded_submodule_store) == 0 @pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10") class TestStandaloneCompiledArtifactsIntegration: def test_add_pickle_unpickle(self): cache = StandaloneCompiledArtifacts() artifacts = { ("mod1", "shape1"): b"m1s1_artifact", ("mod1", "shape2"): b"m1s2_artifact", ("mod2", "shape1"): b"m2s1_artifact", ("mod2", "shape2"): b"m2s2_artifact", } for (submod, shape), data in artifacts.items(): cache.insert(submod, shape, data) assert cache.num_entries() == 4 assert cache.num_artifacts() == 4 for (submod, shape), expected_data in artifacts.items(): retrieved_data = cache.get(submod, shape) assert retrieved_data == expected_data pickled = pickle.dumps(cache) restored_cache = pickle.loads(pickled) for (submod, shape), expected_data in artifacts.items(): retrieved_data = restored_cache.get(submod, shape) assert retrieved_data == expected_data def test_deduplication(self): cache = StandaloneCompiledArtifacts() shared_data = b"shared_artifact_data" * 1000 cache.insert("mod1", "shape1", shared_data) cache.insert("mod2", "shape1", shared_data) cache.insert("mod1", "shape2", shared_data) cache.insert("mod3", "shape3", shared_data) assert cache.num_entries() == 4 assert cache.num_artifacts() == 1 assert cache.size_bytes() == len(shared_data) for submod, shape in [ ("mod1", "shape1"), ("mod2", "shape1"), ("mod1", "shape2"), ("mod3", "shape3"), ]: assert cache.get(submod, shape) == shared_data
{ "repo_id": "vllm-project/vllm", "file_path": "tests/compile/test_aot_compile.py", "license": "Apache License 2.0", "lines": 570, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/compilation/caching.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import hashlib import inspect import os import pickle from collections.abc import Callable, Sequence from typing import Any, Literal from unittest.mock import patch import torch from torch.utils import _pytree as pytree import vllm.envs as envs from vllm.compilation.compiler_interface import get_inductor_factors from vllm.config import VllmConfig, get_current_vllm_config from vllm.config.utils import hash_factors from vllm.logger import init_logger from vllm.utils.hashing import safe_hash try: from torch._dynamo.aot_compile import SerializableCallable except ImportError: SerializableCallable = object assert isinstance(SerializableCallable, type) logger = init_logger(__name__) class StandaloneCompiledArtifacts: """Storage for standalone compiled artifacts with content-based deduplication. Deduplication works via a two-level indirection: 1. `submodule_bytes` maps "{submod_name}_{shape}" -> SHA256 hash 2. `submodule_bytes_store` maps SHA256 hash -> actual bytes When inserting, we compute the SHA256 hash of the bytes. If the hash already exists in `submodule_bytes_store`, we reuse the existing entry rather than storing duplicate bytes. This is common because submodules often compile to identical artifacts (e.g., identical transformer layers split on attn) """ def __init__(self) -> None: # dict from submodule name to byte hash self.submodule_bytes: dict[str, str] = {} # dict from byte hash to bytes self.submodule_bytes_store: dict[str, bytes] = {} # dict from byte hash to loaded module self.loaded_submodule_store: dict[str, Any] = {} def insert(self, submod_name: str, shape: str, entry: bytes) -> None: hasher = hashlib.sha256() hasher.update(entry) hex_digest = hasher.hexdigest() self.submodule_bytes[f"{submod_name}_{shape}"] = hex_digest if hex_digest not in self.submodule_bytes_store: self.submodule_bytes_store[hex_digest] = entry logger.debug( "inserting new artifact for submod %s with shape %s " "(%s bytes) at hash %s", submod_name, shape, len(entry), hex_digest, ) else: logger.debug( "reusing existing cache artifact for submod %s " "with shape %s (%s bytes) at hash %s", submod_name, shape, len(entry), hex_digest, ) def get(self, submod_name: str, shape: str) -> bytes: logger.debug( "getting artifact for submod %s with shape %s", submod_name, shape, ) return self.submodule_bytes_store[ self.submodule_bytes[f"{submod_name}_{shape}"] ] def get_loaded(self, submod_name: str, shape: str) -> Any: logger.debug( "getting artifact for submod %s with shape %s", submod_name, shape, ) return self.loaded_submodule_store[ self.submodule_bytes[f"{submod_name}_{shape}"] ] def size_bytes(self) -> int: return sum(len(entry) for entry in self.submodule_bytes_store.values()) def num_artifacts(self) -> int: return len(self.submodule_bytes_store) def num_entries(self) -> int: return len(self.submodule_bytes) def submodule_names(self) -> list[str]: # get unique "{submod_name}" from "{submod_name}_{shape}", preserving order names = [cache_key.rsplit("_", 1)[0] for cache_key in self.submodule_bytes] return list(dict.fromkeys(names)) def load_all(self) -> None: import concurrent.futures # check already loaded if len(self.loaded_submodule_store) == len(self.submodule_bytes_store): return from torch._inductor.standalone_compile import AOTCompiledArtifact def _load_entry(entry_bytes: bytes) -> AOTCompiledArtifact: entry = pickle.loads(entry_bytes) return AOTCompiledArtifact.deserialize(entry) with concurrent.futures.ThreadPoolExecutor() as executor: entries = list(self.submodule_bytes_store.values()) loaded_entries = list(executor.map(_load_entry, entries)) for i, k in enumerate(self.submodule_bytes_store.keys()): self.loaded_submodule_store[k] = loaded_entries[i] logger.debug("loaded all %s submodules", self.num_artifacts()) def __getstate__(self) -> dict[str, dict[str, str] | dict[str, bytes]]: return { "submodule_bytes": self.submodule_bytes, "submodule_bytes_store": self.submodule_bytes_store, } def __setstate__(self, state: dict[str, dict[str, Any]]) -> None: self.submodule_bytes = state["submodule_bytes"] self.submodule_bytes_store = state["submodule_bytes_store"] self.loaded_submodule_store = {} @contextlib.contextmanager def patch_pytree_map_over_slice(): pytree._private_register_pytree_node( slice, lambda x: ([x.start, x.stop, x.step], None), lambda x, c: slice(*x) ) try: yield finally: pytree._deregister_pytree_node(slice) class VllmSerializableFunction(SerializableCallable): # type: ignore[misc] """ A wrapper around a compiled function by vllm. It will forward the tensor inputs to the compiled function and return the result. It also implements a serialization interface to support PyTorch's precompile with custom backend, so that we can save and load the compiled function on disk. There's no need to wrap around the compiled function if we don't want to serialize them in particular cases. Right now serialization for the custom backend is done via serializing the Dynamo fx graph plus example inputs. """ def __init__( self, graph_module: torch.fx.GraphModule, example_inputs: Sequence[Any], prefix: str, optimized_call: Callable[..., Any], is_encoder: bool = False, vllm_backend: Any | None = None, sym_tensor_indices: list[int] | None = None, ) -> None: assert isinstance(graph_module, torch.fx.GraphModule) self.graph_module = graph_module self.example_inputs = example_inputs self.prefix = prefix self.optimized_call = optimized_call self.is_encoder = is_encoder self.shape_env = None self.vllm_backend = vllm_backend self.sym_tensor_indices = sym_tensor_indices sym_input = next( (i for i in self.example_inputs if isinstance(i, torch.SymInt)), None ) if sym_input is not None: self.shape_env = sym_input.node.shape_env def __call__(self, *args: Any, **kwargs: Any) -> Any: return self.optimized_call(*args, **kwargs) @classmethod def serialize_compile_artifacts( cls, compiled_fn: "VllmSerializableFunction" ) -> bytes: import sympy from torch._subclasses import FakeTensorMode from torch.fx._graph_pickler import GraphPickler, Options state = compiled_fn.__dict__.copy() state.pop("optimized_call") state.pop("shape_env") state.pop("vllm_backend", None) for node in state["graph_module"].graph.nodes: node.meta.pop("source_fn_stack", None) node.meta.pop("nn_module_stack", None) for name, submod in state["graph_module"].named_children(): if hasattr(submod, "graph"): for node in submod.graph.nodes: node.meta.pop("source_fn_stack", None) node.meta.pop("nn_module_stack", None) graph_reducer_override = GraphPickler.reducer_override def _graph_reducer_override( self: GraphPickler, obj: Any ) -> tuple[Callable[..., Any], tuple[Any, ...]] | Any: if ( inspect.isclass(obj) and issubclass(obj, sympy.Function) and hasattr(obj, "_torch_unpickler") ): return obj._torch_unpickler, (obj._torch_handler_name,) if isinstance(obj, FakeTensorMode): return type(None), () return graph_reducer_override(self, obj) if state.get("sym_tensor_indices"): # put tensor inputs on meta device since their data # isn't needed, yet we need the meta for make_copy_and_call state["example_inputs"] = pytree.tree_map_only( torch.Tensor, lambda inp: torch.empty_like(inp, device="meta"), state["example_inputs"], ) else: # mask off all tensor inputs since they are large and not needed. state["example_inputs"] = pytree.tree_map_only( torch.Tensor, lambda inp: torch.empty_like(inp, device="meta"), state["example_inputs"], ) with ( patch.object(GraphPickler, "reducer_override", _graph_reducer_override), patch_pytree_map_over_slice(), ): state["graph_module"] = GraphPickler.dumps( state["graph_module"], Options(ops_filter=None) ) state["example_inputs"] = GraphPickler.dumps(state["example_inputs"]) if compiled_fn.vllm_backend: ( standalone_compile_artifacts, sym_shape_indices_map, returns_tuple_map, ) = compiled_fn.vllm_backend.collect_standalone_compile_artifacts() state["standalone_compile_artifacts"] = standalone_compile_artifacts state["sym_shape_indices_map"] = sym_shape_indices_map state["returns_tuple_map"] = returns_tuple_map return pickle.dumps(state) @classmethod def deserialize_compile_artifacts(cls, data: bytes) -> "VllmSerializableFunction": from torch._guards import TracingContext, tracing from torch._subclasses import FakeTensorMode from torch.fx._graph_pickler import GraphPickler from torch.fx.experimental.symbolic_shapes import ShapeEnv state = pickle.loads(data) fake_mode = FakeTensorMode(shape_env=ShapeEnv()) with patch_pytree_map_over_slice(): state["graph_module"] = GraphPickler.loads(state["graph_module"], fake_mode) state["graph_module"].recompile() state["example_inputs"] = GraphPickler.loads(state["example_inputs"], fake_mode) standalone_compile_artifacts = state.pop("standalone_compile_artifacts", None) sym_shape_indices_map = state.pop("sym_shape_indices_map", {}) returns_tuple_map = state.pop("returns_tuple_map", {}) if envs.VLLM_USE_MEGA_AOT_ARTIFACT: assert standalone_compile_artifacts is not None submod_names = standalone_compile_artifacts.submodule_names() num_submods = len(submod_names) num_artifacts = standalone_compile_artifacts.num_artifacts() logger.info( "reconstructing serializable fn from standalone compile " "artifacts. num_artifacts=%d num_submods=%d", num_artifacts, num_submods, ) fn = reconstruct_serializable_fn_from_mega_artifact( state=state, standalone_compile_artifacts=standalone_compile_artifacts, vllm_config=get_current_vllm_config(), sym_shape_indices_map=sym_shape_indices_map, returns_tuple_map=returns_tuple_map, ) logger.info( "reconstructed serializable fn from standalone compile artifacts" ) return fn # Fall back to standard VllmBackend from vllm.compilation.backends import VllmBackend is_encoder = state.get("is_encoder", False) vllm_backend: VllmBackend = VllmBackend( get_current_vllm_config(), state["prefix"], is_encoder ) def optimized_call(*example_inputs: Any) -> Any: """ On the first run of the optimized call, we rerun the compiler backend which should result in a cache hit. After the backend call returns, we just do a one-time replacement of the optimized call with the compiled function, so that subsequent calls are on the AOT compiled path. """ compile_inputs = [ inp if inp is not None else example_inputs[i] for i, inp in enumerate(fn.example_inputs) ] with tracing(TracingContext(fake_mode)): fn.optimized_call = vllm_backend( state["graph_module"], compile_inputs ).optimized_call return fn.optimized_call(*example_inputs) fn = cls(**state, optimized_call=optimized_call) return fn @property def co_name(self) -> Literal["VllmSerializableFunction"]: """ Used for depyf debugging. """ return "VllmSerializableFunction" def reconstruct_serializable_fn_from_mega_artifact( state: dict[str, Any], standalone_compile_artifacts: "StandaloneCompiledArtifacts", vllm_config: VllmConfig, sym_shape_indices_map: dict[str, list[int]], returns_tuple_map: dict[str, bool], ) -> "VllmSerializableFunction": """Construct a VllmSerializableFunction from cached inductor artifacts. This function reconstructs a callable model from pre-compiled inductor artifacts without re-running the compilation. It: 1. Loads all cached artifacts 2. Builds compiled callables for each submodule/shape 3. Creates PiecewiseBackend instances that dispatch to cached artifacts 4. Wraps with cudagraph if needed 5. Returns the final VllmSerializableFunction Note: This function shares similar logic with PiecewiseCompileInterpreter in backends.py. Both create PiecewiseBackend instances and wrap them with cudagraph. The key difference is: - this function: PiecewiseBackend receives pre-compiled runnables (compiled_runnables is set, graph is None) - PiecewiseCompileInterpreter: PiecewiseBackend receives the FX graph to compile (graph is set, compiled_runnables is None) If modifying the backend creation/wrapping logic, consider updating both. Args: state: Deserialized state dict containing graph_module, example_inputs, prefix, sym_tensor_indices, is_encoder, etc. standalone_compile_artifacts: The StandaloneCompiledArtifacts containing pre-compiled artifacts for each submodule/shape combination. vllm_config: The vLLM configuration. sym_shape_indices_map: Mapping from submod_name to sym_shape_indices. returns_tuple_map: Mapping from submod_name to returns_tuple. Returns: A VllmSerializableFunction that can be called directly. """ from vllm.compilation.backends import ( VllmBackend, make_copy_and_call, wrap_with_cudagraph_if_needed, ) from vllm.compilation.piecewise_backend import PiecewiseBackend prefix = state["prefix"] is_encoder = state.get("is_encoder", False) split_gm = state["graph_module"] compilation_config = vllm_config.compilation_config standalone_compile_artifacts.load_all() submod_names = standalone_compile_artifacts.submodule_names() compiled_callables: dict[str, dict[str, Callable[..., Any]]] = {} for cache_key in standalone_compile_artifacts.submodule_bytes: submod_name, shape_str = cache_key.rsplit("_", 1) compiled_callables.setdefault(submod_name, {})[shape_str] = ( standalone_compile_artifacts.get_loaded(submod_name, shape_str) ) vllm_backend = VllmBackend(vllm_config, prefix, is_encoder) dummy_cache_dir = os.path.join(envs.VLLM_CACHE_ROOT, "dummy_cache") os.makedirs(dummy_cache_dir, exist_ok=True) vllm_backend.compiler_manager.initialize_cache( cache_dir=dummy_cache_dir, disable_cache=True, prefix=prefix, ) # spot check that cached submodules exist in the graph structure graph_children = {name for name, _ in split_gm.named_children()} missing = set(submod_names) - graph_children assert not missing, ( f"artifacts reference submodules not in graph: {missing}. " f"graph has: {sorted(graph_children)}" ) for i, submod_name in enumerate(submod_names): assert submod_name in sym_shape_indices_map and submod_name in returns_tuple_map sym_shape_indices = sym_shape_indices_map[submod_name] returns_tuple = returns_tuple_map[submod_name] runnables = compiled_callables[submod_name] piecewise_backend = PiecewiseBackend( graph=None, # not needed for cached artifacts vllm_config=vllm_config, piecewise_compile_index=i, total_piecewise_compiles=len(submod_names), sym_shape_indices=sym_shape_indices, vllm_backend=vllm_backend, returns_tuple=returns_tuple, compiled_runnables=runnables, ) is_first = i == 0 is_last = i == len(submod_names) - 1 wrapped_backend = wrap_with_cudagraph_if_needed( piecewise_backend, vllm_config, compilation_config, is_first, is_last, ) split_gm.__dict__[submod_name] = wrapped_backend logger.debug( "Replaced submodule %s with piecewise backend from cache", submod_name, ) if compilation_config.cudagraph_copy_inputs: sym_tensor_indices = state["sym_tensor_indices"] input_buffers = [ torch.empty_like( state["example_inputs"][idx], device=vllm_config.device_config.device ) for idx in sym_tensor_indices ] optimized_call = make_copy_and_call(sym_tensor_indices, input_buffers, split_gm) else: optimized_call = split_gm fn = VllmSerializableFunction( **state, optimized_call=optimized_call, vllm_backend=None, ) return fn def aot_compile_hash_factors(vllm_config: VllmConfig) -> list[str]: factors = [] # 0. factors come from the env, for example, The values of # VLLM_PP_LAYER_PARTITION will affect the computation graph. env_hash = hash_factors(envs.compile_factors()) factors.append(env_hash) # 1. factors come from the vllm_config (it mainly summarizes how the # model is created) config_hash = vllm_config.compute_hash() factors.append(config_hash) # 2. inductor factors if applicable if envs.VLLM_USE_MEGA_AOT_ARTIFACT: factors.extend(get_inductor_factors()) return factors def _compute_code_hash_with_content(file_contents: dict[str, str]) -> str: items = list(sorted(file_contents.items(), key=lambda x: x[0])) hash_content = [] for filepath, content in items: hash_content.append(filepath) if filepath == "<string>": # This means the function was dynamically generated, with # e.g. exec(). We can't actually check these. continue hash_content.append(content) result: str = safe_hash( "\n".join(hash_content).encode(), usedforsecurity=False ).hexdigest() return result def _compute_code_hash(files: set[str]) -> str: logger.debug( "Traced files (to be considered for compilation cache):\n%s", "\n".join(files) ) file_contents = {} for filepath in files: # Skip files that don't exist (e.g., <string>, <frozen modules>, etc.) if not os.path.isfile(filepath): file_contents[filepath] = "" else: with open(filepath) as f: file_contents[filepath] = f.read() return _compute_code_hash_with_content(file_contents)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/compilation/caching.py", "license": "Apache License 2.0", "lines": 451, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/qwen3_omni_moe_thinker.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2025 The Qwen team. # Copyright 2023 The vLLM team. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Inference-only Qwen3-Omni-Moe model (thinker part).""" from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from functools import partial from typing import Any, Literal, cast import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from packaging.version import Version from transformers.feature_extraction_utils import BatchFeature from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import ( Qwen3OmniMoeAudioEncoderConfig, Qwen3OmniMoeConfig, Qwen3OmniMoeThinkerConfig, ) from transformers.models.qwen3_omni_moe.processing_qwen3_omni_moe import ( Qwen3OmniMoeProcessor, ) from transformers.models.whisper import WhisperFeatureExtractor # isort: off from transformers import PretrainedConfig from transformers import __version__ as TRANSFORMERS_VERSION # isort: on from vllm.compilation.decorators import support_torch_compile from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size from vllm.inputs.data import PromptType from vllm.logger import init_logger from vllm.model_executor.layers.activation import _ACTIVATION_REGISTRY from vllm.model_executor.layers.attention.mm_encoder_attention import ( MMEncoderAttention, ) from vllm.model_executor.layers.conv import Conv3dLayer from vllm.model_executor.layers.linear import ( ColumnParallelLinear, QKVParallelLinear, RowParallelLinear, ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.quantization import QuantizationConfig from vllm.model_executor.layers.rotary_embedding import get_rope from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead from vllm.model_executor.model_loader.weight_utils import default_weight_loader from vllm.model_executor.models.module_mapping import MultiModelKeys from vllm.model_executor.models.qwen2_audio import Qwen2AudioProcessingInfo from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.inputs import MultiModalFeatureSpec, MultiModalKwargsItems from vllm.multimodal.parse import AudioProcessorItems, MultiModalDataItems from vllm.multimodal.processing.processor import ( MultiModalPromptUpdates, PlaceholderFeaturesInfo, PromptReplacement, PromptUpdate, PromptUpdateDetails, ) from vllm.sequence import IntermediateTensors from vllm.transformers_utils.processor import cached_processor_from_config from vllm.v1.attention.backends.registry import AttentionBackendEnum from .interfaces import ( MultiModalEmbeddings, SupportsMRoPE, SupportsMultiModal, SupportsPP, SupportsTranscription, ) from .qwen2_5_omni_thinker import ( Qwen2_5OmniAudioFeatureInputs, Qwen2_5OmniConditionalGenerationMixin, Qwen2_5OmniThinkerDummyInputsBuilder, Qwen2_5OmniThinkerMultiModalProcessor, check_interleaved_audio_video, merge_interleaved_embeddings, ) from .qwen2_5_vl import ( Qwen2_5_VisionAttention, Qwen2_5_VLProcessingInfo, ) from .qwen3_moe import Qwen3MoeForCausalLM, Qwen3MoeModel from .utils import ( AutoWeightsLoader, WeightsMapper, _merge_multimodal_embeddings, maybe_prefix, ) from .vision import get_vit_attn_backend logger = init_logger(__name__) # Speech input languages supported by Qwen3-Omni # From: https://huggingface.co/Qwen/Qwen3-Omni-30B-A3B-Instruct ISO639_1_SUPPORTED_LANGS = { "en": "English", "zh": "Chinese", "ko": "Korean", "ja": "Japanese", "de": "German", "ru": "Russian", "it": "Italian", "fr": "French", "es": "Spanish", "pt": "Portuguese", "ms": "Malay", "nl": "Dutch", "id": "Indonesian", "tr": "Turkish", "vi": "Vietnamese", "yue": "Cantonese", "ar": "Arabic", "ur": "Urdu", } def _get_feat_extract_output_lengths(input_lengths: torch.Tensor): input_lengths_leave = input_lengths % 100 feat_lengths = (input_lengths_leave - 1) // 2 + 1 output_lengths = ( ((feat_lengths - 1) // 2 + 1 - 1) // 2 + 1 + (input_lengths // 100) * 13 ) return output_lengths # ============= Audio Encoder Components ============= class SinusoidsPositionEmbedding(nn.Module): """Sinusoidal position embedding for audio encoder.""" def __init__(self, length: int, channels: int, max_timescale: int = 10000): super().__init__() self.length = length self.channels = channels self.max_timescale = max_timescale if channels % 2 != 0: raise ValueError("SinusoidsPositionEmbedding needs even channels input") log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1) inv_timescales = torch.exp( -log_timescale_increment * torch.arange(channels // 2).float() ) scaled_time = ( torch.arange(length)[:, np.newaxis] * inv_timescales[np.newaxis, :] ) positional_embedding = torch.cat( [torch.sin(scaled_time), torch.cos(scaled_time)], dim=1 ) self.register_buffer( "positional_embedding", positional_embedding, persistent=False ) def forward(self, seqlen: int) -> torch.Tensor: return self.positional_embedding[:seqlen, :] class Qwen3OmniMoeAudioAttention(nn.Module): """Multi-headed attention for Qwen3-Omni Audio Encoder using MMEncoderAttention.""" def __init__( self, config: Qwen3OmniMoeAudioEncoderConfig, prefix: str = "", ): super().__init__() self.embed_dim = config.d_model self.num_heads = config.encoder_attention_heads self.head_dim = self.embed_dim // self.num_heads tp_size = get_tensor_model_parallel_world_size() self.num_local_heads = self.num_heads // tp_size if (self.head_dim * self.num_heads) != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: " f"{self.embed_dim} and `num_heads`: {self.num_heads})." ) self.scaling = self.head_dim**-0.5 self.qkv = QKVParallelLinear( hidden_size=self.embed_dim, head_size=self.head_dim, total_num_heads=self.num_heads, total_num_kv_heads=self.num_heads, bias=True, prefix=f"{prefix}.qkv", ) self.out_proj = RowParallelLinear( input_size=self.embed_dim, output_size=self.embed_dim, bias=True, prefix=f"{prefix}.out_proj", ) self.attn = MMEncoderAttention( num_heads=self.num_local_heads, head_size=self.head_dim, scale=self.scaling, prefix=f"{prefix}.attn", ) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: torch.Tensor | None, ) -> torch.Tensor: seq_length, _ = hidden_states.size() qkv, _ = self.qkv(hidden_states) q, k, v = qkv.chunk(3, dim=-1) q = q.view(1, seq_length, -1, self.head_dim) k = k.view(1, seq_length, -1, self.head_dim) v = v.view(1, seq_length, -1, self.head_dim) attn_output = self.attn( query=q, key=k, value=v, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, ) attn_output = attn_output.view(seq_length, -1) output, _ = self.out_proj(attn_output) return output class Qwen3OmniMoeAudioEncoderLayer(nn.Module): """Transformer encoder layer for Qwen3-Omni Audio Encoder.""" def __init__( self, config: Qwen3OmniMoeAudioEncoderConfig, prefix: str = "", ): super().__init__() self.embed_dim = config.d_model self.self_attn = Qwen3OmniMoeAudioAttention( config, prefix=f"{prefix}.self_attn" ) self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.activation_fn = _ACTIVATION_REGISTRY[config.activation_function] self.fc1 = ColumnParallelLinear( self.embed_dim, config.encoder_ffn_dim, bias=True, prefix=f"{prefix}.fc1", ) self.fc2 = RowParallelLinear( config.encoder_ffn_dim, self.embed_dim, bias=True, prefix=f"{prefix}.fc2", ) self.final_layer_norm = nn.LayerNorm(self.embed_dim) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: torch.Tensor | None, ) -> torch.Tensor: """ Args: hidden_states: Input tensor of shape (seq_len, hidden_size) cu_seqlens: Cumulative sequence lengths max_seqlen: Maximum sequence length in the batch """ residual = hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) hidden_states = self.self_attn( hidden_states=hidden_states, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, ) hidden_states = residual + hidden_states residual = hidden_states hidden_states = self.final_layer_norm(hidden_states) hidden_states, _ = self.fc1(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states, _ = self.fc2(hidden_states) hidden_states = residual + hidden_states # Clamp for numerical stability with fp16 if hidden_states.dtype == torch.float16: clamp_value = torch.finfo(hidden_states.dtype).max - 1000 hidden_states = torch.clamp( hidden_states, min=-clamp_value, max=clamp_value ) return hidden_states class Qwen3OmniMoeAudioEncoder(nn.Module): """vLLM-native Qwen3-Omni Audio Encoder.""" def __init__( self, config: Qwen3OmniMoeAudioEncoderConfig, prefix: str = "", ): super().__init__() embed_dim = config.d_model self.num_mel_bins = config.num_mel_bins self.max_source_positions = config.max_source_positions self.n_window = config.n_window self.n_window_infer = config.n_window_infer self.conv_chunksize = config.conv_chunksize # Position embedding self.positional_embedding = SinusoidsPositionEmbedding( self.max_source_positions, embed_dim ) # Convolutional layers for mel-spectrogram processing self.conv2d1 = nn.Conv2d(1, config.downsample_hidden_size, 3, 2, padding=1) self.conv2d2 = nn.Conv2d( config.downsample_hidden_size, config.downsample_hidden_size, 3, 2, padding=1, ) self.conv2d3 = nn.Conv2d( config.downsample_hidden_size, config.downsample_hidden_size, 3, 2, padding=1, ) conv_out_dim = config.downsample_hidden_size * ( (((config.num_mel_bins + 1) // 2 + 1) // 2 + 1) // 2 ) self.conv_out = nn.Linear(conv_out_dim, config.d_model, bias=False) # Transformer encoder layers self.layers = nn.ModuleList( [ Qwen3OmniMoeAudioEncoderLayer( config, prefix=f"{prefix}.layers.{i}", ) for i in range(config.encoder_layers) ] ) # Output layers self.ln_post = nn.LayerNorm(config.d_model) self.proj1 = nn.Linear(config.d_model, config.d_model) self.act = _ACTIVATION_REGISTRY[config.activation_function] self.proj2 = nn.Linear(config.d_model, config.output_dim) # Get attention backend self.attn_backend = get_vit_attn_backend( head_size=config.d_model // config.encoder_attention_heads, dtype=torch.get_default_dtype(), ) def compute_attn_mask_seqlen(self, cu_seqlens: torch.Tensor) -> torch.Tensor | None: """Compute max_seqlen only for flash attention backends.""" max_seqlen = None if self.attn_backend in { AttentionBackendEnum.FLASH_ATTN, AttentionBackendEnum.ROCM_AITER_FA, AttentionBackendEnum.TRITON_ATTN, }: max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max() return max_seqlen @property def dtype(self) -> torch.dtype: return self.conv2d1.weight.dtype @property def device(self) -> torch.device: return self.conv2d1.weight.device def forward( self, input_features: torch.Tensor, feature_lens: torch.Tensor, aftercnn_lens: torch.Tensor, ): # Compute chunk information chunk_num = torch.ceil(feature_lens / (self.n_window * 2)).long() chunk_lengths = torch.tensor( [self.n_window * 2] * chunk_num.sum(), dtype=torch.long, device=feature_lens.device, ) tail_chunk_index = F.pad(chunk_num, (1, 0), value=-1).cumsum(0)[1:] chunk_lengths[tail_chunk_index] = feature_lens % (self.n_window * 2) chunk_lengths[chunk_lengths == 0] = self.n_window * 2 # Split input features into chunks and pad chunk_list = input_features.T.split(chunk_lengths.tolist(), dim=0) padded_feature = nn.utils.rnn.pad_sequence( chunk_list, batch_first=True ).transpose(1, 2) # Compute feature lengths after CNN feature_lens_after_cnn = self._get_cnn_output_lengths(chunk_lengths) # Vectorized mask creation: avoid creating many small tensors max_len_after_cnn = feature_lens_after_cnn.max().item() indices = torch.arange(max_len_after_cnn, device=padded_feature.device) padded_mask_after_cnn = indices.unsqueeze(0) < feature_lens_after_cnn.unsqueeze( 1 ) # Add channel dimension for conv2d padded_feature = padded_feature.unsqueeze(1) # Apply convolutional layers (chunk if needed to avoid OOM) if padded_feature.size(0) <= self.conv_chunksize: # Fast path: no chunking needed padded_embed = F.gelu(self.conv2d1(padded_feature)) padded_embed = F.gelu(self.conv2d2(padded_embed)) padded_embed = F.gelu(self.conv2d3(padded_embed)) else: # Chunked processing to avoid OOM padded_embeds = [] for chunk in padded_feature.split(self.conv_chunksize, dim=0): padded_embed = F.gelu(self.conv2d1(chunk)) padded_embed = F.gelu(self.conv2d2(padded_embed)) padded_embed = F.gelu(self.conv2d3(padded_embed)) padded_embeds.append(padded_embed) padded_embed = torch.cat(padded_embeds, dim=0) # (batch, channels, freq, time) -> (batch, time, channels*freq) b, c, f, t = padded_embed.size() padded_embed = self.conv_out( padded_embed.permute(0, 3, 1, 2).contiguous().view(b, t, c * f) ) # Add positional embedding positional_embedding = ( self.positional_embedding.positional_embedding[: padded_embed.shape[1], :] .unsqueeze(0) .to(padded_embed.dtype) ) padded_embed = padded_embed + positional_embedding # Extract valid hidden states and compute cu_seqlens hidden_states = padded_embed[padded_mask_after_cnn] # Compute cumulative sequence lengths for chunked attention cu_chunk_lens = [0] window_aftercnn = padded_mask_after_cnn.shape[-1] * ( self.n_window_infer // (self.n_window * 2) ) # Use tolist() for efficient batch conversion from tensor to Python for cnn_len in aftercnn_lens.tolist(): num_full_chunks = cnn_len // window_aftercnn remainder = cnn_len % window_aftercnn cu_chunk_lens.extend([window_aftercnn] * num_full_chunks) if remainder: cu_chunk_lens.append(remainder) cu_seqlens = torch.tensor(cu_chunk_lens, device=aftercnn_lens.device).cumsum( -1, dtype=torch.int32 ) max_seqlen = self.compute_attn_mask_seqlen(cu_seqlens) # Apply transformer layers for encoder_layer in self.layers: hidden_states = encoder_layer( hidden_states, cu_seqlens, max_seqlen, ) # Apply output layers hidden_states = self.ln_post(hidden_states) hidden_states = self.proj1(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.proj2(hidden_states) return hidden_states def _get_cnn_output_lengths(self, input_lengths: torch.Tensor) -> torch.Tensor: """Compute output lengths after the three conv2d layers.""" lengths = input_lengths for _ in range(3): lengths = (lengths - 1) // 2 + 1 return lengths def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: """Load weights with mapping from HuggingFace format.""" stacked_params_mapping = [ # (param_name, shard_name, shard_id) ("self_attn.qkv.", "self_attn.q_proj.", "q"), ("self_attn.qkv.", "self_attn.k_proj.", "k"), ("self_attn.qkv.", "self_attn.v_proj.", "v"), ] params_dict = dict(self.named_parameters(remove_duplicate=False)) loaded_params: set[str] = set() for name, loaded_weight in weights: for param_name, weight_name, shard_id in stacked_params_mapping: if weight_name not in name: continue name = name.replace(weight_name, param_name) param = params_dict[name] weight_loader = param.weight_loader weight_loader(param, loaded_weight, shard_id) break else: param = params_dict.get(name) if param is not None: weight_loader = getattr( param, "weight_loader", default_weight_loader ) weight_loader(param, loaded_weight) loaded_params.add(name) return loaded_params class Qwen3_VisionPatchEmbed(nn.Module): def __init__( self, patch_size: int = 14, temporal_patch_size: int = 2, in_channels: int = 3, hidden_size: int = 1152, ) -> None: super().__init__() self.patch_size = patch_size self.temporal_patch_size = temporal_patch_size self.hidden_size = hidden_size kernel_size = (temporal_patch_size, patch_size, patch_size) self.proj = Conv3dLayer( in_channels, hidden_size, kernel_size=kernel_size, stride=kernel_size, bias=True, ) def forward(self, x: torch.Tensor) -> torch.Tensor: L, _ = x.shape x = x.view(L, -1, self.temporal_patch_size, self.patch_size, self.patch_size) x = self.proj(x).view(L, self.hidden_size) return x class Qwen3_VisionMLP(nn.Module): def __init__( self, in_features: int, hidden_features: int, bias: bool = False, act_fn: Callable[[torch.Tensor], torch.Tensor] = F.silu, quant_config: QuantizationConfig | None = None, prefix: str = "", ): super().__init__() self.linear_fc1 = ColumnParallelLinear( in_features, hidden_features, bias=bias, quant_config=quant_config, return_bias=False, prefix=f"{prefix}.linear_fc1", ) self.linear_fc2 = RowParallelLinear( hidden_features, in_features, bias=bias, quant_config=quant_config, return_bias=False, prefix=f"{prefix}.linear_fc2", ) self.act_fn = act_fn def forward(self, x: torch.Tensor): mlp_output = self.linear_fc2(self.act_fn(self.linear_fc1(x))) return mlp_output class Qwen3_VisionBlock(nn.Module): def __init__( self, dim: int, num_heads: int, mlp_hidden_dim: int, act_fn: Callable[[torch.Tensor], torch.Tensor] = F.silu, norm_layer: Callable[[int], nn.Module] | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() if norm_layer is None: norm_layer = partial(nn.LayerNorm, eps=1e-6) self.norm1 = norm_layer(dim) self.norm2 = norm_layer(dim) self.attn = Qwen2_5_VisionAttention( embed_dim=dim, num_heads=num_heads, projection_size=dim, quant_config=quant_config, prefix=f"{prefix}.attn", ) self.mlp = Qwen3_VisionMLP( dim, mlp_hidden_dim, act_fn=act_fn, bias=True, quant_config=quant_config, prefix=f"{prefix}.mlp", ) def forward( self, x: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb_cos: torch.Tensor, rotary_pos_emb_sin: torch.Tensor, max_seqlen: torch.Tensor | None, # Only used for Flash Attention ) -> torch.Tensor: x = x + self.attn( self.norm1(x), cu_seqlens=cu_seqlens, rotary_pos_emb_cos=rotary_pos_emb_cos, rotary_pos_emb_sin=rotary_pos_emb_sin, max_seqlen=max_seqlen, ) x = x + self.mlp(self.norm2(x)) return x class Qwen3_VisionPatchMerger(nn.Module): def __init__( self, d_model: int, context_dim: int, norm_layer: Callable[[int], nn.Module] | None = None, spatial_merge_size: int = 2, use_postshuffle_norm: bool = False, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.hidden_size = context_dim * (spatial_merge_size**2) self.use_postshuffle_norm = use_postshuffle_norm if self.use_postshuffle_norm: context_dim = self.hidden_size if norm_layer is None: norm_layer = partial(nn.LayerNorm, eps=1e-6) self.use_postshuffle_norm = use_postshuffle_norm self.ln_q = norm_layer( self.hidden_size if use_postshuffle_norm else context_dim ) self.mlp = nn.ModuleList( [ ColumnParallelLinear( self.hidden_size, self.hidden_size, bias=True, quant_config=quant_config, prefix=f"{prefix}.mlp.0", ), nn.GELU(), RowParallelLinear( self.hidden_size, d_model, bias=True, quant_config=quant_config, prefix=f"{prefix}.mlp.2", ), ] ) def forward(self, x: torch.Tensor) -> torch.Tensor: if self.use_postshuffle_norm: x = self.ln_q(x.view(-1, self.hidden_size)) else: x = self.ln_q(x).view(-1, self.hidden_size) mlp_fc1, mlp_act, mlp_fc2 = self.mlp x_parallel, _ = mlp_fc1(x) x_parallel = mlp_act(x_parallel) out, _ = mlp_fc2(x_parallel) return out class Qwen3Omni_VisionTransformer(nn.Module): def __init__( self, vision_config, norm_eps: float = 1e-6, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.hidden_size = vision_config.hidden_size self.num_heads = vision_config.num_heads self.image_size = vision_config.image_size self.patch_size = vision_config.patch_size self.spatial_merge_size = vision_config.spatial_merge_size self.spatial_merge_unit = self.spatial_merge_size**2 self.temporal_patch_size = vision_config.temporal_patch_size self.num_grid_per_side = self.image_size // self.patch_size self.apply_vit_abs_pos_embed = vision_config.apply_vit_abs_pos_embed self.deepstack_visual_indexes = vision_config.deepstack_visual_indexes self.patch_embed = Qwen3_VisionPatchEmbed( patch_size=self.patch_size, temporal_patch_size=self.temporal_patch_size, in_channels=vision_config.in_channels, hidden_size=self.hidden_size, ) # vit pos embedding, TODO: spatial_patch_size vs patch_size if self.apply_vit_abs_pos_embed: self.pos_embed = nn.Embedding(self.num_grid_per_side**2, self.hidden_size) else: self.pos_embed = nn.Parameter( torch.empty([1, self.num_grid_per_side**2, self.hidden_size]) ) norm_layer = partial(nn.LayerNorm, eps=norm_eps) head_dim = self.hidden_size // self.num_heads self.rotary_pos_emb = get_rope( head_size=head_dim, max_position=8192, is_neox_style=True, rope_parameters={"partial_rotary_factor": 0.5}, ) self.blocks = nn.ModuleList( [ Qwen3_VisionBlock( dim=self.hidden_size, num_heads=self.num_heads, mlp_hidden_dim=vision_config.intermediate_size, act_fn=_ACTIVATION_REGISTRY[vision_config.hidden_act], norm_layer=norm_layer, quant_config=quant_config, prefix=f"{prefix}.blocks.{layer_idx}", ) for layer_idx in range(vision_config.depth) ] ) self.merger = Qwen3_VisionPatchMerger( d_model=vision_config.out_hidden_size, context_dim=self.hidden_size, norm_layer=norm_layer, spatial_merge_size=self.spatial_merge_size, quant_config=quant_config, prefix=f"{prefix}.merger", ) if self.deepstack_visual_indexes is not None: self.merger_list = nn.ModuleList( [ Qwen3_VisionPatchMerger( d_model=vision_config.out_hidden_size, context_dim=self.hidden_size, spatial_merge_size=self.spatial_merge_size, use_postshuffle_norm=True, norm_layer=norm_layer, quant_config=quant_config, prefix=f"{prefix}.merger_list.{layer_idx}", ) for layer_idx in range(len(self.deepstack_visual_indexes)) ] ) self.attn_backend = get_vit_attn_backend( head_size=head_dim, dtype=torch.get_default_dtype(), ) @property def dtype(self) -> torch.dtype: return self.patch_embed.proj.weight.dtype @property def device(self) -> torch.device: return self.patch_embed.proj.weight.device def rot_pos_emb(self, grid_thw): pos_ids = [] for t, h, w in grid_thw: hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) hpos_ids = hpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) hpos_ids = hpos_ids.permute(0, 2, 1, 3) hpos_ids = hpos_ids.flatten() wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) wpos_ids = wpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) wpos_ids = wpos_ids.permute(0, 2, 1, 3) wpos_ids = wpos_ids.flatten() pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)) pos_ids = torch.cat(pos_ids, dim=0) max_grid_size = grid_thw[:, 1:].max() # Use pre-computed cos_sin_cache from RotaryEmbedding cos, sin = self.rotary_pos_emb.get_cos_sin(max_grid_size) cos_combined = cos[pos_ids].flatten(1) sin_combined = sin[pos_ids].flatten(1) return cos_combined, sin_combined def fast_pos_embed_interpolate(self, grid_thw: list[list[int]]) -> torch.Tensor: num_grid_per_side = self.num_grid_per_side m_size = self.spatial_merge_size hidden_dim = self.pos_embed.embedding_dim outputs = [] for t, h, w in grid_thw: h_idxs = torch.linspace( 0, num_grid_per_side - 1, h, dtype=torch.float32, device=self.device ) w_idxs = torch.linspace( 0, num_grid_per_side - 1, w, dtype=torch.float32, device=self.device ) h_floor = h_idxs.to(torch.long) w_floor = w_idxs.to(torch.long) h_ceil = torch.clamp(h_floor + 1, max=num_grid_per_side - 1) w_ceil = torch.clamp(w_floor + 1, max=num_grid_per_side - 1) dh = h_idxs - h_floor dw = w_idxs - w_floor # Create meshgrid view for all h, w vars dh_grid, dw_grid = torch.meshgrid(dh, dw, indexing="ij") h_floor_grid, w_floor_grid = torch.meshgrid(h_floor, w_floor, indexing="ij") h_ceil_grid, w_ceil_grid = torch.meshgrid(h_ceil, w_ceil, indexing="ij") h_floor_grid_idx = h_floor_grid * num_grid_per_side h_ceil_grid_idx = h_ceil_grid * num_grid_per_side # original computation of weights # w00 = (1 - dh_grid) * (1 - dw_grid) # w01 = (1 - dh_grid) * dw_grid # w10 = dh_grid * (1 - dw_grid) # w11 = dh_grid * dw_grid # we reuse w11 here to avoid duplicate # dh_grid * dw_grid computation w11 = dh_grid * dw_grid w10 = dh_grid - w11 w01 = dw_grid - w11 w00 = 1 - dh_grid - dw_grid + w11 idx00 = h_floor_grid_idx + w_floor_grid idx01 = h_floor_grid_idx + w_ceil_grid idx10 = h_ceil_grid_idx + w_floor_grid idx11 = h_ceil_grid_idx + w_ceil_grid indices = torch.stack([idx00, idx01, idx10, idx11], dim=0).reshape(4, -1) weights = torch.stack([w00, w01, w10, w11], dim=0).reshape(4, -1, 1) weights = weights.to(dtype=self.dtype, device=self.device) embeds = self.pos_embed(indices) weighted_embeds = embeds * weights p0, p1, p2, p3 = weighted_embeds.unbind(dim=0) combined = p0 + p1 + p2 + p3 combined = combined.view(h * w, hidden_dim) repeated = combined.unsqueeze(0).expand(t, -1, -1).contiguous() repeated = repeated.view( t, h // m_size, m_size, w // m_size, m_size, hidden_dim ) repeated = repeated.permute(0, 1, 3, 2, 4, 5).reshape(-1, hidden_dim) outputs.append(repeated) return torch.cat(outputs, dim=0) def compute_attn_mask_seqlen( self, cu_seqlens: torch.Tensor, ) -> torch.Tensor: max_seqlen = torch.zeros([], device=cu_seqlens.device) if self.attn_backend in { AttentionBackendEnum.FLASH_ATTN, AttentionBackendEnum.ROCM_AITER_FA, AttentionBackendEnum.TRITON_ATTN, }: max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max() return max_seqlen def forward( self, x: torch.Tensor, grid_thw: list[list[int]], ) -> torch.Tensor: hidden_states = x.to(device=self.device, dtype=self.dtype) hidden_states = self.patch_embed(hidden_states) if self.apply_vit_abs_pos_embed: pos_embeds = self.fast_pos_embed_interpolate(grid_thw) hidden_states = hidden_states + pos_embeds rotary_pos_emb_cos, rotary_pos_emb_sin = self.rot_pos_emb(grid_thw) # RDNA3 (gfx11) specific bug workaround: torch.repeat_interleave triggers # kernel crashes. We attempt the operation and catch the RuntimeError # to switch to a vectorized cumsum + searchsorted approach. try: cu_seqlens = torch.repeat_interleave( grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0] ).cumsum( dim=0, dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, ) cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0) except RuntimeError: logger.warning( "torch.repeat_interleave not executable, " "switching to vectorized searchsorted implementation." ) repeat_counts = grid_thw[:, 0] values = grid_thw[:, 1] * grid_thw[:, 2] repeat_cumsum = repeat_counts.cumsum(0) total_items = repeat_cumsum[-1].item() indices = torch.searchsorted( repeat_cumsum, torch.arange(total_items, device=grid_thw.device), right=True, ) cu_seqlens = values[indices].cumsum( dim=0, dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, ) cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0) hidden_states = hidden_states.unsqueeze(1) rotary_pos_emb_cos = rotary_pos_emb_cos.to(hidden_states.device) rotary_pos_emb_sin = rotary_pos_emb_sin.to(hidden_states.device) max_seqlen = self.compute_attn_mask_seqlen(cu_seqlens) hidden_states_list = [] deepstack_visual_indexes = self.deepstack_visual_indexes for layer_num, blk in enumerate(self.blocks): hidden_states = blk( hidden_states, cu_seqlens=cu_seqlens, rotary_pos_emb_cos=rotary_pos_emb_cos, rotary_pos_emb_sin=rotary_pos_emb_sin, max_seqlen=max_seqlen, ) if ( deepstack_visual_indexes is not None and layer_num in deepstack_visual_indexes ): hidden_states_list.append(hidden_states) hidden_states = self.merger(hidden_states) # processing deepstack if deepstack_visual_indexes is not None: processed_hidden_states_list = [hidden_states] for idx, x in enumerate(hidden_states_list): x = self.merger_list[idx](x) processed_hidden_states_list.append(x) # we cat the original visual features and deepstack features # along the feature dim hidden_states = torch.cat( processed_hidden_states_list, dim=1 ) # [seq_len, hidden_size * (1 + depth_of_deepstack)] return hidden_states def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: stacked_params_mapping = [ # (param_name, shard_name, shard_id) ("attn.qkv.", "attn.q.", "q"), ("attn.qkv.", "attn.k.", "k"), ("attn.qkv.", "attn.v.", "v"), ] params_dict = dict(self.named_parameters(remove_duplicate=False)) loaded_params: set[str] = set() for name, loaded_weight in weights: for param_name, weight_name, shard_id in stacked_params_mapping: if weight_name not in name: continue name = name.replace(weight_name, param_name) param = params_dict[name] weight_loader = param.weight_loader weight_loader(param, loaded_weight, shard_id) break else: param = params_dict[name] weight_loader = getattr(param, "weight_loader", default_weight_loader) weight_loader(param, loaded_weight) loaded_params.add(name) return loaded_params @support_torch_compile( dynamic_arg_dims={ "input_ids": 0, "positions": -1, "intermediate_tensors": 0, "inputs_embeds": 0, "deepstack_input_embeds": 0, } ) class Qwen3MoeLLMModel(Qwen3MoeModel): def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__(vllm_config=vllm_config, prefix=prefix) self.deepstack_multiscale_layer_start = 1 def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, deepstack_input_embeds: IntermediateTensors | None = None, ) -> torch.Tensor | IntermediateTensors: if get_pp_group().is_first_rank: if inputs_embeds is not None: hidden_states = inputs_embeds else: hidden_states = self.embed_input_ids(input_ids) residual = None else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] residual = intermediate_tensors["residual"] for layer_idx, layer in enumerate( self.layers[self.start_layer : self.end_layer] ): layer_idx = layer_idx + self.start_layer hidden_states, residual = layer( positions, hidden_states, residual, ) if deepstack_input_embeds is not None and layer_idx in range( 0, len(deepstack_input_embeds) ): hidden_states = ( hidden_states + deepstack_input_embeds[f"deepstack_input_embeds_{layer_idx}"] ) if not get_pp_group().is_last_rank: return IntermediateTensors( {"hidden_states": hidden_states, "residual": residual} ) hidden_states, _ = self.norm(hidden_states, residual) return hidden_states class Qwen3MoeLLMForCausalLM(Qwen3MoeForCausalLM): def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super(Qwen3MoeForCausalLM, self).__init__() config = vllm_config.model_config.hf_config quant_config = vllm_config.quant_config self.config = config self.quant_config = quant_config self.model = Qwen3MoeLLMModel( vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") ) self.lm_head = ParallelLMHead( config.vocab_size, config.hidden_size, quant_config=quant_config ) if self.config.tie_word_embeddings: self.lm_head.weight = self.model.embed_tokens.weight self.logits_processor = LogitsProcessor(config.vocab_size) self.make_empty_intermediate_tensors = ( self.model.make_empty_intermediate_tensors ) class Qwen3OmniMoeThinkerProcessingInfo( Qwen2AudioProcessingInfo, Qwen2_5_VLProcessingInfo ): def get_hf_config(self): return self.ctx.get_hf_config(Qwen3OmniMoeConfig).thinker_config def get_hf_processor(self, **kwargs: object) -> Qwen3OmniMoeProcessor: processor = self.ctx.get_hf_processor( Qwen3OmniMoeProcessor, use_fast=kwargs.pop("use_fast", True), **kwargs, ) if not hasattr(processor, "audio_token"): processor.audio_token = "<|audio_pad|>" if not hasattr(processor, "image_token"): processor.image_token = "<|image_pad|>" if not hasattr(processor, "video_token"): processor.video_token = "<|video_pad|>" return processor def get_feature_extractor(self, **kwargs: object): hf_processor = self.get_hf_processor(**kwargs) feature_extractor = hf_processor.feature_extractor # type: ignore assert isinstance(feature_extractor, WhisperFeatureExtractor) return feature_extractor def get_supported_mm_limits(self) -> Mapping[str, int | None]: return {"audio": None, "image": None, "video": None} Qwen3OmniMoeThinkerDummyInputsBuilder = Qwen2_5OmniThinkerDummyInputsBuilder class Qwen3OmniMoeThinkerMultiModalProcessor( Qwen2_5OmniThinkerMultiModalProcessor, ): def _call_hf_processor( self, prompt: str, mm_data: Mapping[str, object], mm_kwargs: Mapping[str, object], tok_kwargs: Mapping[str, object], ) -> BatchFeature: mm_data = dict(mm_data) audios = mm_data.pop("audios", []) def pad_to_hop_length(x: np.ndarray, hop_length: int) -> np.ndarray: length = x.shape[-1] if length % hop_length != 0: pad_length = hop_length - (length % hop_length) x = np.pad(x, (0, pad_length), mode="constant", constant_values=0) return x # NOTE: WhisperFeatureExtractor cannot handle empty list of audios feature_extractor = self.info.get_feature_extractor(**mm_kwargs) hop_length = feature_extractor.hop_length if audios: # NOTE: Qwen3-Omni processor accept "audio" # To make sure the cache works with padding=True, we pre-padded # the audio to multiple of hop_length. mm_data["audio"] = [ pad_to_hop_length(audio, hop_length) if isinstance(audio, np.ndarray) else (pad_to_hop_length(audio[0], hop_length), audio[1]) for audio in audios ] # TODO(Isotr0py): Remove this patch after upstream fix PR # released and Transformers version update: # https://github.com/huggingface/transformers/pull/41473 mm_kwargs = dict(mm_kwargs) tok_kwargs = dict(tok_kwargs) mm_kwargs["audio_kwargs"] = dict(mm_kwargs.get("audio_kwargs") or {}) mm_kwargs["text_kwargs"] = dict(mm_kwargs.get("text_kwargs") or {}) if Version(TRANSFORMERS_VERSION) < Version("4.58.0"): # Extract audio_sample_rate before restructuring audio_sample_rate = mm_kwargs.pop("audio_sample_rate", None) # move truncation to audio_kwargs level to avoid conflict # with tok_kwargs mm_kwargs["audio_kwargs"].setdefault( "truncation", mm_kwargs.pop("truncation", False) ) mm_kwargs["text_kwargs"].setdefault( "truncation", tok_kwargs.pop("truncation", False) ) # Validate and conditionally pass audio_sample_rate # WhisperFeatureExtractor has a fixed sampling rate, and vLLM's # audio loader already resamples audio to the target rate. # Only pass the value if it matches to avoid unexpected behavior. if audio_sample_rate is not None: expected_sr = feature_extractor.sampling_rate if audio_sample_rate != expected_sr: logger.warning( "[%s] audio_sample_rate mismatch: user provided %dHz " "but model expects %dHz. Ignoring user value. " "vLLM's audio loader already resampled to %dHz.", self.__class__.__name__, audio_sample_rate, expected_sr, expected_sr, ) else: # Sample rate matches, safe to pass mm_kwargs["audio_kwargs"]["audio_sample_rate"] = ( audio_sample_rate ) hf_inputs = super()._call_hf_processor( prompt=prompt, mm_data=mm_data, mm_kwargs=mm_kwargs, tok_kwargs=tok_kwargs, ) if ( "audio_feature_lengths" in hf_inputs and "feature_attention_mask" in hf_inputs and (audios := mm_data.get("audio", [])) ): audio_num_frames = [] for _, audio in enumerate(audios): audio_length = len(audio[0]) if isinstance(audio, tuple) else len(audio) num_frame = ( (audio_length // hop_length) if audio_length % hop_length == 0 else (audio_length // hop_length - 1) ) if mm_kwargs.get("truncation", False): num_frame = min( num_frame, feature_extractor.n_samples // hop_length ) audio_num_frames.append(num_frame) hf_inputs["feature_attention_mask"] = [ torch.ones(num_frame) for num_frame in audio_num_frames ] hf_inputs["audio_feature_lengths"] = torch.tensor(audio_num_frames) return hf_inputs def _maybe_apply_prompt_updates( self, mm_items: MultiModalDataItems, prompt_ids: list[int], mm_kwargs: MultiModalKwargsItems, mm_prompt_updates: MultiModalPromptUpdates, is_update_applied: bool, ) -> tuple[list[int], str, Mapping[str, list[PlaceholderFeaturesInfo]]]: """ Qwen3-Omni reimplements this function to handle `use_audio_in_video`. """ mm_item_counts = mm_items.get_all_counts() self._validate_mm_kwargs(mm_kwargs, mm_item_counts) use_audio_in_video = False if "video" in mm_kwargs: for item in mm_kwargs["video"]: if item and item["use_audio_in_video"].data: use_audio_in_video = True else: use_audio_in_video = False # normal case with `use_audio_in_video=False` if is_update_applied: mm_placeholders = self._find_mm_placeholders( prompt_ids, mm_prompt_updates, ) self._validate_mm_placeholders( mm_placeholders, mm_item_counts, ) else: if use_audio_in_video and "audio" in mm_prompt_updates: filtered_updates = { k: v for k, v in mm_prompt_updates.items() if k != "audio" } prompt_ids, mm_placeholders = self._apply_prompt_updates( prompt_ids, filtered_updates, ) # Derive audio placeholders from video placeholders mm_placeholders = self._derive_audio_from_video_placeholders( mm_placeholders, mm_prompt_updates ) else: prompt_ids, mm_placeholders = self._apply_prompt_updates( prompt_ids, mm_prompt_updates, ) self._validate_mm_placeholders( mm_placeholders, mm_item_counts, ) return prompt_ids, mm_placeholders def get_updates_use_audio_in_video( self, thinker_config: PretrainedConfig, audio_len: int, video_grid_thw: list[int] | torch.Tensor, video_second_per_grid_t: float, ) -> list[int]: shift = 0 audio_token_id = thinker_config.audio_token_id video_token_id = thinker_config.video_token_id audio_start_token_id = thinker_config.audio_start_token_id audio_end_token_id = thinker_config.audio_end_token_id spatial_merge_size = thinker_config.vision_config.spatial_merge_size position_id_per_seconds = thinker_config.position_id_per_seconds audio_token_indices = np.arange(next(iter([audio_len]))) curr_video_grid_thw = next(iter([video_grid_thw])) height = curr_video_grid_thw[1] // spatial_merge_size width = curr_video_grid_thw[2] // spatial_merge_size video_token_indices = np.arange(curr_video_grid_thw[0]).reshape(-1, 1, 1) video_token_indices = np.broadcast_to( video_token_indices, (video_token_indices.shape[0], height, width) ).reshape(-1) video_token_indices = ( (video_token_indices + shift) * next(iter([video_second_per_grid_t])) * position_id_per_seconds ) video_data_index, audio_data_index = 0, 0 updates = [audio_start_token_id] while video_data_index < len(video_token_indices) and audio_data_index < len( audio_token_indices ): if ( video_token_indices[video_data_index] <= audio_token_indices[audio_data_index] ): updates += [video_token_id] video_data_index += 1 else: updates += [audio_token_id] audio_data_index += 1 if video_data_index < len(video_token_indices): updates += [video_token_id] * (len(video_token_indices) - video_data_index) if audio_data_index < len(audio_token_indices): updates += [audio_token_id] * (len(audio_token_indices) - audio_data_index) updates += [audio_end_token_id] return updates def _get_prompt_updates( self, mm_items: MultiModalDataItems, hf_processor_mm_kwargs: Mapping[str, Any], out_mm_kwargs: MultiModalKwargsItems, ) -> Sequence[PromptUpdate]: processor = self.info.get_hf_processor(**hf_processor_mm_kwargs) tokenizer = self.info.get_tokenizer() image_processor = self.info.get_image_processor(**hf_processor_mm_kwargs) vocab = tokenizer.get_vocab() audio_token = processor.audio_token image_token = processor.image_token video_token = processor.video_token audio_token_id = vocab[audio_token] image_token_id = vocab[image_token] video_token_id = vocab[video_token] out_mm_data = out_mm_kwargs.get_data() audio_feature_lengths = out_mm_data.get("audio_feature_lengths") feature_attention_mask = out_mm_data.get("feature_attention_mask") if audio_feature_lengths is None and feature_attention_mask is None: audio_output_lengths = [] elif audio_feature_lengths is not None: audio_output_lens = _get_feat_extract_output_lengths(audio_feature_lengths) audio_output_lengths = audio_output_lens.tolist() elif feature_attention_mask is not None: assert isinstance(feature_attention_mask, torch.Tensor) audio_output_lens = _get_feat_extract_output_lengths( feature_attention_mask.sum(-1) ) audio_output_lengths = audio_output_lens.tolist() # number of audios read from video. audio_in_video_item_idx = 0 audio_item_idx = 0 def get_replacement_qwen2_audio(item_idx: int): nonlocal audio_item_idx item_idx += audio_in_video_item_idx audio_item_idx += 1 num_features = audio_output_lengths[item_idx] if num_features == 0: audios = mm_items.get_items("audio", AudioProcessorItems) audio = audios.get(item_idx) raise ValueError( f"The audio {audio} (len={len(audio)}) is too short " "to be represented inside the model" ) return [audio_token_id] * num_features def get_replacement_qwen2_vision(item_idx: int, modality: str): grid_thw = out_mm_data[f"{modality}_grid_thw"][item_idx] assert isinstance(grid_thw, torch.Tensor) merge_length = image_processor.merge_size**2 token_id = image_token_id if modality == "image" else video_token_id return [token_id] * (int(grid_thw.prod()) // merge_length) use_audio_in_video = hf_processor_mm_kwargs.get("use_audio_in_video", False) thinker_config = self.info.get_hf_config() def get_replacement_qwen2_use_audio_in_video(item_idx: int): nonlocal audio_in_video_item_idx audio_num_features = audio_output_lengths[ audio_in_video_item_idx + item_idx ] video_grid_thw = out_mm_data["video_grid_thw"][item_idx] audio_in_video_item_idx += 1 second_per_grid_ts = hf_processor_mm_kwargs.get("second_per_grid_ts", None) if second_per_grid_ts: video_second_per_grid_t = second_per_grid_ts[item_idx] else: video_second_per_grid_t = 2.0 placeholder = self.get_updates_use_audio_in_video( thinker_config=thinker_config, audio_len=audio_num_features, video_grid_thw=video_grid_thw, video_second_per_grid_t=video_second_per_grid_t, ) return PromptUpdateDetails.select_token_id( placeholder, embed_token_id=video_token_id ) video_replacement_fn = ( get_replacement_qwen2_use_audio_in_video if use_audio_in_video else partial(get_replacement_qwen2_vision, modality="video") ) return [ PromptReplacement( modality="audio", target=audio_token, replacement=get_replacement_qwen2_audio, ), PromptReplacement( modality="image", target=image_token, replacement=partial(get_replacement_qwen2_vision, modality="image"), ), PromptReplacement( modality="video", target=video_token, replacement=video_replacement_fn, ), ] def _derive_audio_from_video_placeholders( self, placeholders: Mapping[str, list[PlaceholderFeaturesInfo]], mm_prompt_updates: MultiModalPromptUpdates, ) -> Mapping[str, list[PlaceholderFeaturesInfo]]: """ Helper to derive audio placeholders from video placeholders when use_audio_in_video=True. """ if "video" not in placeholders: return placeholders # Validate audio and video counts match num_videos = len(placeholders["video"]) num_audios = len(mm_prompt_updates.get("audio", [])) if num_audios != num_videos: raise ValueError( f"use_audio_in_video requires equal number of audio and video items, " f"got {num_audios=}, {num_videos=}" ) tokenizer = self.info.get_tokenizer() processor = self.info.get_hf_processor() audio_token_id = tokenizer.get_vocab()[processor.audio_token] result_placeholders = dict(placeholders) audio_placeholders = [] # Each video is paired with one audio for video_idx, video_placeholder in enumerate(placeholders["video"]): # Create is_embed mask selecting only audio tokens audio_is_embed = torch.tensor(video_placeholder.tokens) == audio_token_id audio_placeholder = PlaceholderFeaturesInfo( modality="audio", item_idx=video_idx, start_idx=video_placeholder.start_idx, tokens=video_placeholder.tokens, is_embed=audio_is_embed, ) audio_placeholders.append(audio_placeholder) result_placeholders["audio"] = audio_placeholders return result_placeholders def _get_raw_input_ids( self, token_ids: list[int], use_audio_in_video: bool = False, ) -> list[int]: tokenizer = self.info.get_tokenizer() vision_bos_token = tokenizer.encode(tokenizer.vision_bos_token)[0] vision_eos_token = tokenizer.encode(tokenizer.vision_eos_token)[0] audio_bos_token = tokenizer.encode(tokenizer.audio_bos_token)[0] audio_eos_token = tokenizer.encode(tokenizer.audio_eos_token)[0] audio_token = tokenizer.encode("<|audio_pad|>")[0] image_token = tokenizer.encode("<|image_pad|>")[0] video_token = tokenizer.encode("<|video_pad|>")[0] result = token_ids[:] if use_audio_in_video: while True: start = None for i in range(len(result) - 1): if result[i : i + 2] == [vision_bos_token, audio_bos_token]: start = i break if start is not None: end = None for i in range(start + 2, len(result) - 1): if result[i : i + 2] == [audio_eos_token, vision_eos_token]: end = i break if end is not None: result = ( result[:start] + [vision_bos_token, video_token, vision_eos_token] + result[end + 2 :] ) else: break for mm_token in [audio_token, image_token, video_token]: compressed = [] for x in result: if x != mm_token or (not compressed or compressed[-1] != mm_token): compressed.append(x) result = compressed return result class Qwen3OmniMoeConditionalGenerationMixin(Qwen2_5OmniConditionalGenerationMixin): def _process_audio_input( self, audio_input: Qwen2_5OmniAudioFeatureInputs, audio_hashes: list[str] | None = None, cached_audio_features: torch.Tensor | None = None, ) -> tuple[torch.Tensor, ...]: input_features = audio_input["input_features"] audio_feature_lengths = audio_input["audio_feature_lengths"] audio_output_lengths = _get_feat_extract_output_lengths(audio_feature_lengths) audio_features = self.audio_tower( input_features.to(self.audio_tower.dtype), feature_lens=audio_feature_lengths, aftercnn_lens=audio_output_lengths, ) return audio_features.split(audio_output_lengths.tolist()) @MULTIMODAL_REGISTRY.register_processor( Qwen3OmniMoeThinkerMultiModalProcessor, info=Qwen3OmniMoeThinkerProcessingInfo, dummy_inputs=Qwen3OmniMoeThinkerDummyInputsBuilder, ) class Qwen3OmniMoeThinkerForConditionalGeneration( nn.Module, SupportsMultiModal, SupportsPP, SupportsMRoPE, Qwen3OmniMoeConditionalGenerationMixin, SupportsTranscription, ): hf_to_vllm_mapper = WeightsMapper( orig_to_new_prefix={ "thinker.lm_head.": "language_model.lm_head.", "thinker.model.": "language_model.model.", "thinker.": "", } ) packed_modules_mapping = { "qkv_proj": [ "q_proj", "k_proj", "v_proj", ], "gate_up_proj": [ "gate_proj", "up_proj", ], } supported_languages = ISO639_1_SUPPORTED_LANGS @classmethod def get_placeholder_str(cls, modality: str, i: int) -> str | None: if modality.startswith("image"): return "<|vision_start|><|image_pad|><|vision_end|>" if modality.startswith("video"): return "<|vision_start|><|video_pad|><|vision_end|>" if modality.startswith("audio"): return "<|audio_start|><|audio_pad|><|audio_end|>" raise ValueError("Only image, video or audio modality is supported") def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() self.vllm_config = vllm_config # needed for torch compile forward context thinker_config: Qwen3OmniMoeThinkerConfig = ( vllm_config.model_config.hf_config.thinker_config ) quant_config = vllm_config.quant_config multimodal_config = vllm_config.model_config.multimodal_config self.config = thinker_config self.multimodal_config = multimodal_config self.quant_config = quant_config with self._mark_tower_model(vllm_config, "audio"): self.audio_tower = Qwen3OmniMoeAudioEncoder( thinker_config.audio_config, prefix=maybe_prefix(prefix, "audio_tower"), ) self.use_deepstack = hasattr( thinker_config.vision_config, "deepstack_visual_indexes" ) self.deepstack_num_level = ( len(thinker_config.vision_config.deepstack_visual_indexes) if self.use_deepstack else 0 ) self.visual_dim = thinker_config.vision_config.out_hidden_size self.multiscale_dim = self.visual_dim * self.deepstack_num_level with self._mark_tower_model(vllm_config, {"image", "video"}): self.visual = Qwen3Omni_VisionTransformer( vision_config=thinker_config.vision_config, norm_eps=getattr(thinker_config.text_config, "rms_norm_eps", 1e-6), quant_config=quant_config, prefix=maybe_prefix(prefix, "visual"), ) # register buffer for deepstack if self.use_deepstack: self.deepstack_input_embeds = [ torch.zeros( vllm_config.scheduler_config.max_num_batched_tokens, thinker_config.text_config.hidden_size, ) for _ in range(self.deepstack_num_level) ] with self._mark_language_model(vllm_config): self.language_model = Qwen3MoeLLMForCausalLM( vllm_config=vllm_config.with_hf_config( thinker_config.text_config, architectures=["Qwen3MoeForCausalLM"], ), prefix=maybe_prefix(prefix, "language_model"), ) self.make_empty_intermediate_tensors = ( self.language_model.make_empty_intermediate_tensors ) def _get_deepstack_input_embeds( self, num_tokens: int, ) -> IntermediateTensors | None: if not getattr(self, "deepstack_input_embeds", None): return None # If vision tower is skipped # get deepstack_input_embeds from buffer, and clear the buffer return IntermediateTensors( { f"deepstack_input_embeds_{idx}": self.deepstack_input_embeds[idx][ :num_tokens ] for idx in range(self.deepstack_num_level) } ) def _set_deepstack_input_embeds(self, deepstack_input_embeds: torch.Tensor) -> None: if not getattr(self, "deepstack_input_embeds", None): return # set deepstack_input_embeds to buffer num_tokens = deepstack_input_embeds.size(1) if num_tokens > self.deepstack_input_embeds[0].size(0): self.deepstack_input_embeds = [ torch.zeros( num_tokens, self.config.text_config.hidden_size, device=self.deepstack_input_embeds[0].device, dtype=self.deepstack_input_embeds[0].dtype, ) for _ in range(self.deepstack_num_level) ] for idx in range(self.deepstack_num_level): self.deepstack_input_embeds[idx][:num_tokens].copy_( deepstack_input_embeds[idx] ) def _clear_deepstack_input_embeds(self, num_tokens: int) -> None: if not getattr(self, "deepstack_input_embeds", None): return # clear deepstack_input_embeds in buffer if num_tokens > 0: for idx in range(self.deepstack_num_level): self.deepstack_input_embeds[idx][:num_tokens].zero_() def _parse_and_validate_multimodal_inputs(self, **kwargs: object) -> dict: mm_input_by_modality = {} # Preserve the order of modalities if there are multiple of them # from the order of kwargs. for input_key in kwargs: if ( input_key in ("pixel_values", "image_embeds") and "image" not in mm_input_by_modality ): mm_input_by_modality["image"] = self._parse_and_validate_image_input( **kwargs ) if ( input_key in ("pixel_values_videos", "video_embeds") and "video" not in mm_input_by_modality ): mm_input_by_modality["video"] = self._parse_and_validate_video_input( **kwargs ) if ( input_key in ("input_audio_features") and "audio" not in mm_input_by_modality ): mm_input_by_modality["audio"] = self._parse_and_validate_audio_input( **kwargs ) return mm_input_by_modality def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings | None: mm_input_by_modality = self._parse_and_validate_multimodal_inputs(**kwargs) if not mm_input_by_modality: return [] # The result multimodal_embeddings is tuple of tensors, with each # tensor correspoending to a multimodal data item (image or video). multimodal_embeddings: tuple[torch.Tensor, ...] = () # NOTE: It is important to iterate over the keys in this dictionary # to preserve the order of the modalities. for modality in mm_input_by_modality: multimodal_input = mm_input_by_modality[modality] if modality == "image": image_embeddings = self._process_image_input(multimodal_input) multimodal_embeddings += tuple(image_embeddings) if modality == "video": video_embeddings = self._process_video_input(multimodal_input) multimodal_embeddings += tuple(video_embeddings) if modality == "audio": audio_embeddings = self._process_audio_input(multimodal_input) multimodal_embeddings += tuple(audio_embeddings) return multimodal_embeddings def embed_input_ids( self, input_ids: torch.Tensor, multimodal_embeddings: MultiModalEmbeddings | None = None, *, is_multimodal: torch.Tensor | None = None, handle_oov_mm_token: bool = False, ) -> torch.Tensor: inputs_embeds = self._embed_text_input_ids( input_ids, self.language_model.embed_input_ids, is_multimodal=is_multimodal, handle_oov_mm_token=handle_oov_mm_token, ) if multimodal_embeddings is None or len(multimodal_embeddings) == 0: return inputs_embeds # Detect interleaved audio-in-video early, since it affects # both the deepstack path and the final embedding merge. video_token_id = self.config.video_token_id audio_token_id = self.config.audio_token_id is_video = is_multimodal & (input_ids == video_token_id) is_audio = is_multimodal & (input_ids == audio_token_id) num_video = is_video.sum().item() num_audio = is_audio.sum().item() is_interleaved = check_interleaved_audio_video( is_video, is_audio, num_video, num_audio ) deepstack_input_embeds = None # split the feat dim to obtain multi-scale visual feature has_vision_embeddings = [ embeddings.shape[-1] != self.config.text_config.hidden_size for embeddings in multimodal_embeddings ] if self.visual.deepstack_visual_indexes is not None and any( has_vision_embeddings ): multiscale_len = len(self.visual.deepstack_visual_indexes) multimodal_embeddings_multiscale = [] if is_interleaved: # Use input_ids-based mask for correct vision positions # when audio and video tokens are interleaved. is_vision = is_video.clone() else: is_vision = torch.zeros_like(is_multimodal) mm_positions = torch.nonzero(is_multimodal, as_tuple=True)[0] mm_position_idx = 0 for index, embeddings in enumerate(multimodal_embeddings): num_tokens = embeddings.shape[0] # Vision embeddings if embeddings.shape[-1] != self.config.text_config.hidden_size: visual_dim = embeddings.shape[-1] // (multiscale_len + 1) multi_dim = visual_dim * multiscale_len embeddings_main, embeddings_multiscale = torch.split( embeddings, [visual_dim, multi_dim], dim=-1 ) multimodal_embeddings[index] = embeddings_main multimodal_embeddings_multiscale.append(embeddings_multiscale) if not is_interleaved: current_positions = mm_positions[ mm_position_idx : mm_position_idx + num_tokens ] is_vision[current_positions] = True # Audio embeddings else: if not is_interleaved: current_positions = mm_positions[ mm_position_idx : mm_position_idx + num_tokens ] is_vision[current_positions] = False if not is_interleaved: mm_position_idx += num_tokens deepstack_input_embeds = inputs_embeds.new_zeros( inputs_embeds.size(0), multiscale_len * inputs_embeds.size(1) ) deepstack_input_embeds = _merge_multimodal_embeddings( inputs_embeds=deepstack_input_embeds, multimodal_embeddings=multimodal_embeddings_multiscale, is_multimodal=is_vision, ) deepstack_input_embeds = ( deepstack_input_embeds.view( inputs_embeds.shape[0], multiscale_len, visual_dim ) .permute(1, 0, 2) .contiguous() ) self._set_deepstack_input_embeds(deepstack_input_embeds) if is_interleaved: return merge_interleaved_embeddings( inputs_embeds, multimodal_embeddings, is_video, is_audio, is_multimodal, num_video, num_audio, ) # Default: standard merge (no interleaving), same as parent class. # multimodal_embeddings may have been updated above (deepstack # main-scale). Use super() to stay consistent with the parent # implementation and avoid issues seen in Qwen2.5-Omni (#34506). return super().embed_input_ids( input_ids, multimodal_embeddings=multimodal_embeddings, is_multimodal=is_multimodal, handle_oov_mm_token=handle_oov_mm_token, ) def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, **kwargs: object, ) -> torch.Tensor | IntermediateTensors: if intermediate_tensors is not None: inputs_embeds = None if inputs_embeds is not None and get_pp_group().is_first_rank: deepstack_input_embeds = self._get_deepstack_input_embeds( inputs_embeds.size(0) ) else: deepstack_input_embeds = None hidden_states = self.language_model.model( input_ids, positions, intermediate_tensors, inputs_embeds=inputs_embeds, # args for deepstack deepstack_input_embeds=deepstack_input_embeds, ) if inputs_embeds is not None and get_pp_group().is_first_rank: self._clear_deepstack_input_embeds(inputs_embeds.size(0)) return hidden_states def compute_logits( self, hidden_states: torch.Tensor, ) -> torch.Tensor | None: return self.language_model.compute_logits(hidden_states) def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: loader = AutoWeightsLoader( self, skip_prefixes=["talker.", "code2wav."], ) loaded_weights = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) return loaded_weights def _compute_audio_token_count(self, audio_feature_length: int) -> int: """Compute audio tokens from feature length using Qwen3-Omni formula.""" return _get_feat_extract_output_lengths( torch.tensor([audio_feature_length]) ).item() def _get_audio_for_video_mapping( self, mm_features: list[MultiModalFeatureSpec] ) -> tuple[dict[int, int], set[int]]: """ Map video offset -> paired audio_feature_length for use_audio_in_video. When use_audio_in_video=True, audio is interleaved within video. The pairing is based on feature order in mm_features. Returns: Tuple of (video_offset -> audio_feature_length mapping, set of paired audio offsets to skip) """ videos_with_audio = [ f for f in mm_features if f.modality == "video" and f.data.get("use_audio_in_video") and f.data["use_audio_in_video"].data.item() ] audios = [f for f in mm_features if f.modality == "audio"] mapping: dict[int, int] = {} paired_audio_offsets: set[int] = set() for i, video_f in enumerate(videos_with_audio): if i < len(audios): audio_len = audios[i].data["audio_feature_lengths"].data.item() mapping[video_f.mm_position.offset] = audio_len paired_audio_offsets.add(audios[i].mm_position.offset) return mapping, paired_audio_offsets def iter_mm_features( self, mm_features: list[MultiModalFeatureSpec] ) -> Iterator[tuple[int, str, dict[str, Any]]]: """ Iterate over multimodal features sorted by position offset. Yields: (offset, modality, feature_data) where feature_data contains: - image: {"grid_t", "grid_h", "grid_w", "t_factor"} - video: {"grid_t", "grid_h", "grid_w", "t_factor", "use_audio_in_video", "audio_feature_length"} - audio: {"audio_feature_length"} """ config = self.config spatial_merge_size = config.vision_config.spatial_merge_size position_id_per_seconds = config.position_id_per_seconds sorted_features = sorted(mm_features, key=lambda f: f.mm_position.offset) audio_for_video, paired_audio_offsets = self._get_audio_for_video_mapping( sorted_features ) for mm_feature in sorted_features: offset = mm_feature.mm_position.offset modality = mm_feature.modality if modality == "image": t, h, w = mm_feature.data["image_grid_thw"].data.tolist() yield ( offset, "image", { "grid_t": t, "grid_h": h // spatial_merge_size, "grid_w": w // spatial_merge_size, "t_factor": position_id_per_seconds, }, ) elif modality == "video": t, h, w = mm_feature.data["video_grid_thw"].data.tolist() second_per_grid_ts = 2.0 if mm_feature.data.get("second_per_grid_ts"): second_per_grid_ts = mm_feature.data[ "second_per_grid_ts" ].data.item() use_audio_in_video = bool( mm_feature.data.get("use_audio_in_video") and mm_feature.data["use_audio_in_video"].data.item() ) yield ( offset, "video", { "grid_t": t, "grid_h": h // spatial_merge_size, "grid_w": w // spatial_merge_size, "t_factor": second_per_grid_ts * position_id_per_seconds, "use_audio_in_video": use_audio_in_video, "audio_feature_length": audio_for_video.get(offset), }, ) elif modality == "audio": if offset not in paired_audio_offsets: audio_len = mm_feature.data["audio_feature_lengths"].data.item() yield offset, "audio", {"audio_feature_length": audio_len} def _compute_interleaved_positions( self, start_idx: int, data: dict[str, Any] ) -> tuple[np.ndarray, int]: """ Compute positions for interleaved video+audio using Qwen3 token-by-token interleaving logic. Returns: (position_ids [3, N], total_token_count) """ grid_t = data["grid_t"] grid_h = data["grid_h"] grid_w = data["grid_w"] t_factor = data["t_factor"] audio_feature_length = data["audio_feature_length"] audio_len = self._compute_audio_token_count(audio_feature_length) h_index = np.tile( np.arange(grid_h).reshape(1, -1, 1), (grid_t, 1, grid_w) ).flatten() w_index = np.tile( np.arange(grid_w).reshape(1, 1, -1), (grid_t, grid_h, 1) ).flatten() t_index_raw = np.arange(grid_t) t_index_scaled = (t_index_raw * t_factor).astype(np.int64) t_index = np.repeat(t_index_scaled, grid_h * grid_w) video_pos = np.stack([t_index, h_index, w_index]) + start_idx audio_pos = np.broadcast_to(np.arange(audio_len), (3, audio_len)) + start_idx video_t_values = video_pos[0] audio_t_values = audio_pos[0] pos_ids_list: list[np.ndarray] = [] video_idx, audio_idx = 0, 0 num_video = grid_t * grid_h * grid_w while video_idx < num_video and audio_idx < audio_len: if video_t_values[video_idx] <= audio_t_values[audio_idx]: pos_ids_list.append(video_pos[:, video_idx : video_idx + 1]) video_idx += 1 else: pos_ids_list.append(audio_pos[:, audio_idx : audio_idx + 1]) audio_idx += 1 if video_idx < num_video: pos_ids_list.append(video_pos[:, video_idx:]) if audio_idx < audio_len: pos_ids_list.append(audio_pos[:, audio_idx:]) total_tokens = num_video + audio_len return np.concatenate(pos_ids_list, axis=1), total_tokens @classmethod def get_speech_to_text_config( cls, model_config: ModelConfig, task_type: str ) -> SpeechToTextConfig: processor = cached_processor_from_config( model_config, processor_cls=Qwen3OmniMoeProcessor ) return SpeechToTextConfig( max_audio_clip_s=processor.feature_extractor.chunk_length, sample_rate=processor.feature_extractor.sampling_rate, min_energy_split_window_size=None, ) @classmethod def get_generation_prompt( cls, audio: np.ndarray, stt_config: SpeechToTextConfig, model_config: ModelConfig, language: str | None, task_type: Literal["transcribe", "translate"], request_prompt: str, to_language: str | None, ) -> PromptType: """ Construct a transcription/translation prompt for Qwen3-Omni. """ # Transcribe this audio [into <language>] | for transcription # Translate this audio [from <language> into <to_language>] | for translation instruction = "Transcribe" if task_type == "transcribe" else "Translate" instruction += " this audio" # Default to_language to English for translation if task_type == "translate" and to_language is None: to_language = "en" # Get full language names from supported_languages mapping full_lang_name = cls.supported_languages.get(language, "") full_lang_name_to = cls.supported_languages.get(to_language, "") if task_type == "transcribe" and full_lang_name: instruction += f" into {full_lang_name}" elif task_type == "translate": if full_lang_name: instruction += f" from {full_lang_name}" if full_lang_name_to: instruction += f" into {full_lang_name_to}" instruction += "." if request_prompt: instruction += f" {request_prompt}" processor = cached_processor_from_config( model_config, processor_cls=Qwen3OmniMoeProcessor ) # Audio placeholder format: <|audio_start|><|audio_pad|><|audio_end|> audio_placeholder = "<|audio_start|><|audio_pad|><|audio_end|>" user_content = f"{audio_placeholder}{instruction}" messages = [{"role": "user", "content": user_content}] prompt = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, ) audio_data = (audio, stt_config.sample_rate) prompts_dict = {"multi_modal_data": {"audio": audio_data}, "prompt": prompt} return cast(PromptType, prompts_dict) def get_mrope_input_positions( self, input_tokens: list[int], mm_features: list[MultiModalFeatureSpec], ) -> tuple[torch.Tensor, int]: """Compute M-RoPE input positions using mm_features directly.""" seq_len = len(input_tokens) llm_pos_ids_list: list[np.ndarray] = [] st = 0 for offset, modality, data in self.iter_mm_features(mm_features): text_len = offset - st st_idx = int(llm_pos_ids_list[-1].max()) + 1 if llm_pos_ids_list else 0 if text_len > 0: llm_pos_ids_list.append( np.broadcast_to(np.arange(text_len), (3, text_len)) + st_idx ) st_idx += text_len bos_pos = np.broadcast_to(np.array([st_idx]), (3, 1)) llm_pos_ids_list.append(bos_pos) st_idx += 1 if modality == "audio": audio_tokens = self._compute_audio_token_count( data["audio_feature_length"] ) audio_pos = ( np.broadcast_to(np.arange(audio_tokens), (3, audio_tokens)) + st_idx ) llm_pos_ids_list.append(audio_pos) st_idx = int(audio_pos.max()) + 1 eos_pos = np.broadcast_to(np.array([st_idx]), (3, 1)) llm_pos_ids_list.append(eos_pos) st = offset + 1 + audio_tokens + 1 elif modality == "image": grid_t = data["grid_t"] grid_h = data["grid_h"] grid_w = data["grid_w"] t_factor = data["t_factor"] grid_indices = np.indices((grid_t, grid_h, grid_w)) if t_factor != 1.0: grid_indices[0] = (grid_indices[0] * t_factor).astype(np.int64) llm_pos_ids_list.append(grid_indices.reshape(3, -1) + st_idx) image_len = grid_t * grid_h * grid_w st_idx = int(llm_pos_ids_list[-1].max()) + 1 eos_pos = np.broadcast_to(np.array([st_idx]), (3, 1)) llm_pos_ids_list.append(eos_pos) st = offset + 1 + image_len + 1 elif modality == "video": grid_t = data["grid_t"] grid_h = data["grid_h"] grid_w = data["grid_w"] t_factor = data["t_factor"] if not data["use_audio_in_video"]: grid_indices = np.indices((grid_t, grid_h, grid_w)) if t_factor != 1.0: grid_indices[0] = (grid_indices[0] * t_factor).astype(np.int64) llm_pos_ids_list.append(grid_indices.reshape(3, -1) + st_idx) video_len = grid_t * grid_h * grid_w st_idx = int(llm_pos_ids_list[-1].max()) + 1 eos_pos = np.broadcast_to(np.array([st_idx]), (3, 1)) llm_pos_ids_list.append(eos_pos) st = offset + 1 + video_len + 1 else: audio_bos_pos = np.broadcast_to(np.array([st_idx - 1]), (3, 1)) llm_pos_ids_list.append(audio_bos_pos) pos_ids, _ = self._compute_interleaved_positions(st_idx, data) llm_pos_ids_list.append(pos_ids) st_idx = int(pos_ids.max()) + 1 eos_pos = np.broadcast_to(np.array([st_idx]), (3, 1)) llm_pos_ids_list.append(eos_pos) llm_pos_ids_list.append(eos_pos) video_len = grid_t * grid_h * grid_w audio_len = self._compute_audio_token_count( data["audio_feature_length"] ) st = offset + 2 + video_len + audio_len + 2 if st < seq_len: st_idx = int(llm_pos_ids_list[-1].max()) + 1 if llm_pos_ids_list else 0 text_len = seq_len - st llm_pos_ids_list.append( np.broadcast_to(np.arange(text_len), (3, text_len)) + st_idx ) llm_positions = np.concatenate(llm_pos_ids_list, axis=1).reshape(3, -1) if llm_positions.shape[1] != seq_len: raise RuntimeError("Position ids length mismatch with input ids length") mrope_position_delta = int(llm_positions.max()) + 1 - seq_len return torch.from_numpy(llm_positions), mrope_position_delta def get_mm_mapping(self) -> MultiModelKeys: """ Get the module prefix in multimodal models """ return MultiModelKeys.from_string_field( language_model="language_model", connector="visual.merger", tower_model=["visual.", "audio_tower."], )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/qwen3_omni_moe_thinker.py", "license": "Apache License 2.0", "lines": 2024, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/kernels/quantization/test_mxfp4_qutlass.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # # Copyright (C) 2025 Roberto L. Castro (Roberto.LopezCastro@ist.ac.at). # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np import pytest import torch from compressed_tensors.transform.utils.hadamard import deterministic_hadamard_matrix from vllm._custom_ops import fusedQuantizeMx, matmul_mxf4_bf16_tn from vllm.model_executor.layers.quantization.qutlass_utils import to_blocked from vllm.platforms import current_platform from vllm.utils.torch_utils import set_random_seed if not torch.cuda.is_available(): pytest.skip("CUDA required for these tests.", allow_module_level=True) if not ( current_platform.has_device_capability(100) or current_platform.has_device_capability(120) ): pytest.skip( reason="Tests require compute capability 10.0 (100) or 12.0 (120).", allow_module_level=True, ) # ----- Helpers ----- def get_hadamard_matrix(group_size: int, dtype: torch.dtype, device: torch.device): return ( deterministic_hadamard_matrix(group_size, dtype=dtype, device=device) * group_size**-0.5 ) def _rtne_fp4(x: torch.Tensor): device = x.device grid = torch.tensor( [ -6.0, -4.0, -3.0, -2.0, -1.5, -1.0, -0.5, -0.0, 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, ], dtype=x.dtype, device=x.device, ) grid_int = torch.tensor( [-1, -2, -3, -4, -5, -6, -7, -8, 0, 1, 2, 3, 4, 5, 6, 7], dtype=torch.uint8, device=device, ) inds = torch.bucketize(x, grid) lo, hi = (inds - 1).clamp(min=0, max=15), inds.clamp(min=0, max=15) g_lo, g_hi = grid[lo], grid[hi] pick_hi = (g_hi - x < x - g_lo) | (g_hi - x == x - g_lo) & (grid_int[hi] % 2 == 0) y = torch.where(pick_hi, g_hi, g_lo) y_int = torch.where(pick_hi, grid_int[hi], grid_int[lo]) y_int_packed = (y_int[..., 1::2] & 0xF) << 4 | y_int[..., ::2] & 0xF return y, y_int_packed def _dq_fp4(x_e2m1: torch.Tensor, x_e8m0: torch.Tensor, alpha: float): device = x_e2m1.device x_e2m1_i32 = x_e2m1.view(dtype=torch.uint8).to(dtype=torch.int32) x_e2m1_unpacked = torch.stack( [x_e2m1_i32 & 0xF, (x_e2m1_i32 >> 4) & 0xF], dim=-1 ).flatten(start_dim=-2) grid_dq = torch.tensor( [ 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0, ], dtype=torch.float64, device=device, ) x_fp4_dq = grid_dq[x_e2m1_unpacked] scales_dq = x_e8m0.to(torch.float64) x_dq = (x_fp4_dq.unflatten(dim=-1, sizes=(-1, 32)) * scales_dq[..., None]).flatten( start_dim=-2 ) / alpha return x_dq, x_fp4_dq, scales_dq def _unpack_mask(clip_mask: torch.Tensor) -> torch.Tensor: clip_mask_unpacked_dq = torch.zeros( *clip_mask.shape[:-1], clip_mask.size(-1) * 8, dtype=torch.bool, device=clip_mask.device, ) for i in range(8): clip_mask_unpacked_dq[..., i::8] = (clip_mask >> i) & 1 return clip_mask_unpacked_dq def _forward_quantize_ref( x: torch.Tensor, h: torch.Tensor, rot_size: int, quest: bool = True ): device = x.device xh_ref64 = ( x.unflatten(dim=-1, sizes=(-1, rot_size)).to(dtype=torch.float64) @ h.reshape(rot_size, rot_size).to(dtype=torch.float64) ).flatten(start_dim=-2) if quest: scales_ref64_ = ( xh_ref64.unflatten(dim=-1, sizes=(-1, 32)).std(dim=-1, correction=0) * (2.92247856 / 6.0) + 1e-8 ) else: abs_max = xh_ref64.unflatten(dim=-1, sizes=(-1, 32)).abs().amax(dim=-1) scales_ref64_ = abs_max + 1e-8 xh_e8m0_ref = scales_ref64_.log2().floor().exp2().to(dtype=torch.float8_e8m0fnu) scales_ref64 = xh_e8m0_ref.to(dtype=torch.float64) xh_scaled_ref64 = ( xh_ref64.unflatten(dim=-1, sizes=(-1, 32)) / scales_ref64[..., None] ).flatten(start_dim=-2) if not quest: xh_scaled_ref64 *= 3 clip_mask_unpacked_ref = xh_scaled_ref64.abs() < 6.0 clip_mask_ref = torch.zeros( *x.shape[:-1], x.size(-1) // 8, dtype=torch.uint8, device=device ) for i in range(8): clip_mask_ref |= clip_mask_unpacked_ref[..., i::8].to(dtype=torch.uint8) << i xh_fp4_ref, xh_e2m1_ref = _rtne_fp4(xh_scaled_ref64) xh_dq, xh_fp4_dq, scales_dq = _dq_fp4( xh_e2m1_ref, xh_e8m0_ref, alpha=1.0 if quest else 3.0 ) clip_mask_unpacked_dq = _unpack_mask(clip_mask_ref) assert xh_fp4_dq.equal(xh_fp4_ref) assert scales_dq.equal(scales_ref64) assert clip_mask_unpacked_dq.equal(clip_mask_unpacked_ref) return ( xh_dq, clip_mask_unpacked_ref, (xh_e2m1_ref, xh_e8m0_ref, clip_mask_ref), ) DTYPE = torch.bfloat16 DEVICE = torch.device("cuda:0") ROT_SIZES = [32, 64, 128] SEEDS = [0] BATCHES = [1, 16] LLAMA_MODELS = { "7B": [(4096, 3 * 4096), (4096, 4096), (4096, 2 * 10752), (10752, 4096)], "13B": [(5120, 3 * 5120), (5120, 5120), (5120, 2 * 13568), (13568, 5120)], "33B": [(6656, 3 * 6656), (6656, 6656), (6656, 2 * 17664), (17664, 6656)], "70B": [(8192, 3 * 8192), (8192, 8192), (8192, 2 * 21760), (21760, 8192)], } @pytest.fixture(autouse=True) def _seed_each_test(): set_random_seed(0) np.random.seed(0) torch.random.manual_seed(0) @pytest.mark.parametrize("rot_size", ROT_SIZES) @torch.inference_mode() def test_fused_quantization_absmax(rot_size: int): dtype, device = DTYPE, DEVICE h = get_hadamard_matrix(rot_size, dtype, device) x = torch.randn(2, 4096, 4096, dtype=dtype, device=device) * 25.0 xh_dq_ref, _, _ = _forward_quantize_ref(x, h, rot_size, quest=False) xh_e2m1, xh_e8m0 = fusedQuantizeMx(x, h, method="abs_max") xh_e8m0 = xh_e8m0.reshape(2, 4096, 4096 // 32) xh_dq, *_ = _dq_fp4(xh_e2m1, xh_e8m0, alpha=3.0) torch.testing.assert_close(xh_dq, xh_dq_ref, rtol=0.34, atol=100) assert (xh_dq != xh_dq_ref).float().mean() <= 1e-4 m, n, k = 1, 504, 4096 a = torch.randn(m, k, dtype=dtype, device=device) * 25.0 b = torch.randn(n, k, dtype=dtype, device=device) * 25.0 a_e2m1, a_e8m0 = fusedQuantizeMx(a, h, method="abs_max") b_e2m1, b_e8m0 = fusedQuantizeMx(b, h, method="abs_max") a_dq, *_ = _dq_fp4(a_e2m1, a_e8m0[:m, :k], alpha=1.0) b_dq, *_ = _dq_fp4(b_e2m1, b_e8m0[:n, :k], alpha=1.0) out_ref = a_dq @ b_dq.transpose(-2, -1) a_scale_block = to_blocked(a_e8m0, backend="triton") b_scale_block = to_blocked(b_e8m0, backend="triton") alpha = torch.tensor([1.0], device=device) out = matmul_mxf4_bf16_tn(a_e2m1, b_e2m1, a_scale_block, b_scale_block, alpha) assert out.equal(out_ref.to(dtype=out.dtype)) @pytest.mark.parametrize("rot_size", ROT_SIZES) @torch.inference_mode() def test_fused_quantization_quest(rot_size: int): dtype, device = DTYPE, DEVICE h = get_hadamard_matrix(rot_size, dtype, device) x = torch.randn(2, 4096, 4096, dtype=dtype, device=device) * 25.0 xh_dq_ref, _, _ = _forward_quantize_ref(x, h, rot_size, quest=True) xh_e2m1, xh_e8m0 = fusedQuantizeMx(x, h, method="quest") xh_e8m0 = xh_e8m0.reshape(2, 4096, 4096 // 32) xh_dq, *_ = _dq_fp4(xh_e2m1, xh_e8m0, alpha=1.0) torch.testing.assert_close(xh_dq, xh_dq_ref, rtol=0.34, atol=100) assert (xh_dq != xh_dq_ref).float().mean() <= 1e-4 m, n, k = 504, 504, 2048 a = torch.randn(m, k, dtype=dtype, device=device) * 25.0 b = torch.randn(n, k, dtype=dtype, device=device) * 25.0 a_e2m1, a_e8m0 = fusedQuantizeMx(a, h, method="quest") b_e2m1, b_e8m0 = fusedQuantizeMx(b, h, method="quest") a_dq, *_ = _dq_fp4(a_e2m1, a_e8m0[:m, :k], alpha=1.0) b_dq, *_ = _dq_fp4(b_e2m1, b_e8m0[:n, :k], alpha=1.0) out_ref = a_dq @ b_dq.transpose(-2, -1) a_scale_block = to_blocked(a_e8m0, backend="triton") b_scale_block = to_blocked(b_e8m0, backend="triton") alpha = torch.tensor([1.0], device=device) out = matmul_mxf4_bf16_tn(a_e2m1, b_e2m1, a_scale_block, b_scale_block, alpha) assert out.equal(out_ref.to(dtype=out.dtype)) @pytest.mark.parametrize("model", list(LLAMA_MODELS.keys())) @pytest.mark.parametrize("layer_idx", [0, 1, 2, 3]) @pytest.mark.parametrize("batch", [1, 16]) @pytest.mark.parametrize("had_size", ROT_SIZES) @torch.inference_mode() def test_llama_shapes(model: str, layer_idx: int, batch: int, had_size: int): dtype, device = DTYPE, DEVICE m = batch k, n = LLAMA_MODELS[model][layer_idx] h = get_hadamard_matrix(had_size, dtype, device) a = torch.rand(m, k, dtype=dtype, device=device) * 25.0 b = torch.rand(n, k, dtype=dtype, device=device) * 25.0 a_e2m1, a_e8m0 = fusedQuantizeMx(a, h, method="quest") b_e2m1, b_e8m0 = fusedQuantizeMx(b, h, method="quest") a_dq, *_ = _dq_fp4(a_e2m1, a_e8m0[:m, :k], alpha=1.0) b_dq, *_ = _dq_fp4(b_e2m1, b_e8m0[:n, :k], alpha=1.0) out_ref = a_dq @ b_dq.transpose(-2, -1) a_scale_block = to_blocked(a_e8m0, backend="triton") b_scale_block = to_blocked(b_e8m0, backend="triton") alpha = torch.tensor([1.0], device=device) out = matmul_mxf4_bf16_tn(a_e2m1, b_e2m1, a_scale_block, b_scale_block, alpha) assert out.equal(out_ref.to(dtype=out.dtype))
{ "repo_id": "vllm-project/vllm", "file_path": "tests/kernels/quantization/test_mxfp4_qutlass.py", "license": "Apache License 2.0", "lines": 254, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/kernels/quantization/test_nvfp4_qutlass.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # # Copyright (C) 2025 Roberto L. Castro (Roberto.LopezCastro@ist.ac.at). # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np import pytest import torch from compressed_tensors.transform.utils.hadamard import deterministic_hadamard_matrix from vllm import _custom_ops as ops # use existing nvfp4 gemm in vllm from vllm._custom_ops import fusedQuantizeNv from vllm.model_executor.layers.quantization.qutlass_utils import to_blocked from vllm.platforms import current_platform from vllm.utils.torch_utils import set_random_seed if not torch.cuda.is_available(): pytest.skip("CUDA required for these tests.", allow_module_level=True) if not ( current_platform.has_device_capability(100) or current_platform.has_device_capability(120) ): pytest.skip( reason="Tests require compute capability 10.0 (100) or 12.0 (120).", allow_module_level=True, ) # ----- Helpers ----- def get_hadamard_matrix(group_size: int, dtype: torch.dtype, device: torch.device): return ( deterministic_hadamard_matrix(group_size, dtype=dtype, device=device) * group_size**-0.5 ) def _rtne_fp4(x: torch.Tensor): device = x.device grid = torch.tensor( [ -6.0, -4.0, -3.0, -2.0, -1.5, -1.0, -0.5, -0.0, 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, ], dtype=x.dtype, device=x.device, ) grid_int = torch.tensor( [-1, -2, -3, -4, -5, -6, -7, -8, 0, 1, 2, 3, 4, 5, 6, 7], dtype=torch.uint8, device=device, ) inds = torch.bucketize(x, grid) lo, hi = (inds - 1).clamp(min=0, max=15), inds.clamp(min=0, max=15) g_lo, g_hi = grid[lo], grid[hi] pick_hi = (g_hi - x < x - g_lo) | (g_hi - x == x - g_lo) & (grid_int[hi] % 2 == 0) y = torch.where(pick_hi, g_hi, g_lo) y_int = torch.where(pick_hi, grid_int[hi], grid_int[lo]) y_int_packed = (y_int[..., 1::2] & 0xF) << 4 | y_int[..., ::2] & 0xF return y, y_int_packed def _dq_fp4(x_e2m1: torch.Tensor, x_e4m3: torch.Tensor, alpha: float): device = x_e2m1.device x_e2m1_i32 = x_e2m1.view(dtype=torch.uint8).to(dtype=torch.int32) x_e2m1_unpacked = torch.stack( [x_e2m1_i32 & 0xF, (x_e2m1_i32 >> 4) & 0xF], dim=-1 ).flatten(start_dim=-2) grid_dq = torch.tensor( [ 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0, ], dtype=torch.float64, device=device, ) x_fp4_dq = grid_dq[x_e2m1_unpacked] scales_dq = x_e4m3.to(torch.float64) x_dq = (x_fp4_dq.unflatten(dim=-1, sizes=(-1, 16)) * scales_dq[..., None]).flatten( start_dim=-2 ) / alpha # * (4. / 3.) return x_dq, x_fp4_dq, scales_dq def _unpack_mask(clip_mask: torch.Tensor) -> torch.Tensor: clip_mask_unpacked_dq = torch.zeros( *clip_mask.shape[:-1], clip_mask.size(-1) * 8, dtype=torch.bool, device=clip_mask.device, ) for i in range(8): clip_mask_unpacked_dq[..., i::8] = (clip_mask >> i) & 1 return clip_mask_unpacked_dq def _forward_quantize_ref(x: torch.Tensor, h: torch.Tensor, rot_size: int): device = x.device xh_ref64 = ( x.unflatten(dim=-1, sizes=(-1, rot_size)).to(dtype=torch.float64) @ h.reshape(rot_size, rot_size).to(dtype=torch.float64) ).flatten(start_dim=-2) abs_max = xh_ref64.unflatten(dim=-1, sizes=(-1, 16)).abs().amax(dim=-1) scales_ref64_ = abs_max + 1e-8 xh_e4m3_ref = scales_ref64_.to(dtype=torch.float8_e4m3fn) scales_ref64 = xh_e4m3_ref.to(dtype=torch.float64) xh_scaled_ref64 = ( xh_ref64.unflatten(dim=-1, sizes=(-1, 16)) / scales_ref64[..., None] ).flatten(start_dim=-2) xh_scaled_ref64 *= 6.0 clip_mask_unpacked_ref = xh_scaled_ref64.abs() < 6.0 clip_mask_ref = torch.zeros( *x.shape[:-1], x.size(-1) // 8, dtype=torch.uint8, device=device ) for i in range(8): clip_mask_ref |= clip_mask_unpacked_ref[..., i::8].to(dtype=torch.uint8) << i xh_fp4_ref, xh_e2m1_ref = _rtne_fp4(xh_scaled_ref64) xh_dq, xh_fp4_dq, scales_dq = _dq_fp4(xh_e2m1_ref, xh_e4m3_ref, 6.0) clip_mask_unpacked_dq = _unpack_mask(clip_mask_ref) assert xh_fp4_dq.equal(xh_fp4_ref) assert scales_dq.equal(scales_ref64) assert clip_mask_unpacked_dq.equal(clip_mask_unpacked_ref) return ( xh_dq, clip_mask_unpacked_ref, (xh_e2m1_ref, xh_e4m3_ref, clip_mask_ref), ) DTYPE = torch.bfloat16 DEVICE = torch.device("cuda:0") ROT_SIZES = [16, 32, 64, 128] GLOBAL_SCALES = [6.0] LLAMA_MODELS = { "7B": [(4096, 3 * 4096), (4096, 4096), (4096, 2 * 10752), (10752, 4096)], "13B": [(5120, 3 * 5120), (5120, 5120), (5120, 2 * 13568), (13568, 5120)], "33B": [(6656, 3 * 6656), (6656, 6656), (6656, 2 * 17664), (17664, 6656)], "70B": [(8192, 3 * 8192), (8192, 8192), (8192, 2 * 21760), (21760, 8192)], } @pytest.fixture(autouse=True) def _seed_each_test(): set_random_seed(0) np.random.seed(0) torch.random.manual_seed(0) @pytest.mark.parametrize("rot_size", ROT_SIZES) @pytest.mark.parametrize("global_scale_value", GLOBAL_SCALES) @torch.inference_mode() def test_fused_quantization(rot_size: int, global_scale_value: float): dtype, device = DTYPE, DEVICE h = get_hadamard_matrix(rot_size, dtype, device) x = torch.randn(2, 4096, 4096, dtype=dtype, device=device) * 25.0 global_scale = torch.tensor([global_scale_value], device=device) xh_dq_ref, _, _ = _forward_quantize_ref(x, h, rot_size) xh_e2m1, xh_e4m3 = fusedQuantizeNv(x, h, global_scale) xh_e4m3 = xh_e4m3.reshape(2, 4096, 4096 // 16) xh_dq, *_ = _dq_fp4(xh_e2m1, xh_e4m3, alpha=global_scale_value) torch.testing.assert_close(xh_dq, xh_dq_ref, rtol=0.34, atol=100) assert (xh_dq != xh_dq_ref).float().mean() <= 1e-1 m, n, k = 504, 4096 * 2, 4096 a = torch.randn(m, k, dtype=dtype, device=device) * 25.0 b = torch.randn(n, k, dtype=dtype, device=device) * 25.0 a_e2m1, a_e4m3 = fusedQuantizeNv(a, h, global_scale) b_e2m1, b_e4m3 = fusedQuantizeNv(b, h, global_scale) a_dq, *_ = _dq_fp4(a_e2m1, a_e4m3[:m, :k], alpha=1.0) b_dq, *_ = _dq_fp4(b_e2m1, b_e4m3[:n, :k], alpha=1.0) out_ref = a_dq @ b_dq.transpose(-2, -1) a_scale_block = to_blocked(a_e4m3, backend="triton").view(-1, k // 16) b_scale_block = to_blocked(b_e4m3, backend="triton").view(-1, k // 16) alpha = torch.tensor([1.0], device=device) out = ops.cutlass_scaled_fp4_mm( a_e2m1, b_e2m1, a_scale_block, b_scale_block, alpha, torch.bfloat16 ) assert out.equal(out_ref.to(dtype=out.dtype)) @pytest.mark.parametrize("model", list(LLAMA_MODELS.keys())) @pytest.mark.parametrize("layer_idx", [0, 1, 2, 3]) @pytest.mark.parametrize("batch", [1, 16]) @pytest.mark.parametrize("rot_size", ROT_SIZES) @torch.inference_mode() def test_llama_shapes(model: str, layer_idx: int, batch: int, rot_size: int): dtype, device = DTYPE, DEVICE m = batch k, n = LLAMA_MODELS[model][layer_idx] h = get_hadamard_matrix(rot_size, dtype, device) a = torch.randn(m, k, dtype=dtype, device=device) * 25.0 b = torch.randn(n, k, dtype=dtype, device=device) * 25.0 global_scale = torch.tensor([1.0], device=device) a_e2m1, a_e4m3 = fusedQuantizeNv(a, h, global_scale) b_e2m1, b_e4m3 = fusedQuantizeNv(b, h, global_scale) a_dq, *_ = _dq_fp4(a_e2m1, a_e4m3[:m, :k], alpha=1.0) b_dq, *_ = _dq_fp4(b_e2m1, b_e4m3[:n, :k], alpha=1.0) out_ref = a_dq @ b_dq.transpose(-2, -1) a_scale_block = to_blocked(a_e4m3, backend="triton").view(-1, k // 16) b_scale_block = to_blocked(b_e4m3, backend="triton").view(-1, k // 16) alpha = torch.tensor([1.0], device=device) out = ops.cutlass_scaled_fp4_mm( a_e2m1, b_e2m1, a_scale_block, b_scale_block, alpha, torch.bfloat16 ) assert out.equal(out_ref.to(dtype=out.dtype))
{ "repo_id": "vllm-project/vllm", "file_path": "tests/kernels/quantization/test_nvfp4_qutlass.py", "license": "Apache License 2.0", "lines": 224, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/quantization/fp_quant.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Test model set-up and inference for quantized HF models supported on the GPU backend using FPQuant. Validating the configuration and printing results for manual checking. Run `pytest tests/quantization/test_fp_quant.py`. """ import pytest from tests.quantization.utils import is_quant_method_supported MODELS = [ "ISTA-DASLab/Qwen3-0.6B-RTN-NVFP4", "ISTA-DASLab/Qwen3-0.6B-RTN-MXFP4", ] DTYPE = ["bfloat16"] EAGER = [True, False] @pytest.mark.skipif( not is_quant_method_supported("fp_quant"), reason="FPQuant is not supported on this GPU type.", ) @pytest.mark.parametrize("model", MODELS) @pytest.mark.parametrize("eager", EAGER) def test_fpquant(vllm_runner, model, eager): with vllm_runner(model, enforce_eager=eager) as llm: output = llm.generate_greedy(["1 2 3 4 5"], max_tokens=2) assert output[0][1] == "1 2 3 4 5 6"
{ "repo_id": "vllm-project/vllm", "file_path": "tests/quantization/fp_quant.py", "license": "Apache License 2.0", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/model_executor/layers/quantization/fp_quant.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Supports FP-Quant compression, see https://arxiv.org/abs/2509.23202 from typing import Any import torch from torch.nn.parameter import Parameter from vllm._custom_ops import ( cutlass_scaled_fp4_mm, fusedQuantizeMx, fusedQuantizeNv, matmul_mxf4_bf16_tn, ) from vllm.model_executor.layers.linear import ( LinearBase, LinearMethodBase, UnquantizedLinearMethod, ) from vllm.model_executor.layers.quantization import QuantizationMethods from vllm.model_executor.layers.quantization.base_config import QuantizationConfig from vllm.model_executor.layers.quantization.qutlass_utils import to_blocked from vllm.model_executor.utils import set_weight_attrs from vllm.platforms import current_platform from vllm.utils.torch_utils import direct_register_custom_op class FPQuantConfig(QuantizationConfig): """Config class for FPQuant.""" def __init__( self, hadamard_group_size: int = 32, forward_dtype: str = "mxfp4", forward_method: str = "abs_max", pseudoquantization: bool = False, modules_to_not_convert: list[str] | None = None, ) -> None: super().__init__() self.hadamard_group_size = hadamard_group_size self.forward_dtype = forward_dtype self.forward_method = forward_method self.pseudoquantization = pseudoquantization self.modules_to_not_convert = modules_to_not_convert if pseudoquantization: raise ValueError("Pseudoquantization is not supported for vLLM") def __repr__(self) -> str: return ( f"FPQuantConfig(hadamard_group_size={self.hadamard_group_size}, " f"forward_dtype={self.forward_dtype}, " f"forward_method={self.forward_method}, " f"pseudoquantization={self.pseudoquantization}, " f"modules_to_not_convert={self.modules_to_not_convert})" ) @classmethod def get_name(cls) -> QuantizationMethods: return "fp_quant" @classmethod def get_supported_act_dtypes(cls) -> list[torch.dtype]: return [torch.bfloat16] @classmethod def get_min_capability(cls) -> int: return 100 @classmethod def get_config_filenames(cls) -> list[str]: return [] # no extra configs. @classmethod def from_config(cls, config: dict[str, Any]) -> "FPQuantConfig": hadamard_group_size = cls.get_from_keys(config, ["hadamard_group_size"]) forward_dtype = cls.get_from_keys(config, ["forward_dtype"]) forward_method = cls.get_from_keys(config, ["forward_method"]) pseudoquantization = cls.get_from_keys(config, ["pseudoquantization"]) modules_to_not_convert = cls.get_from_keys(config, ["modules_to_not_convert"]) return cls( hadamard_group_size, forward_dtype, forward_method, pseudoquantization, modules_to_not_convert, ) def get_quant_method( self, layer: torch.nn.Module, prefix: str ) -> LinearMethodBase | None: if self.modules_to_not_convert is not None and any( prefix.endswith(module) for module in self.modules_to_not_convert ): return UnquantizedLinearMethod() if isinstance(layer, LinearBase): return FPQuantLinearMethod(self) return None class FPQuantLinearMethod(LinearMethodBase): """Linear method for FPQuant. Args: quant_config: The FPQuant quantization config. """ def __init__(self, quant_config: FPQuantConfig): self.quant_config = quant_config def create_weights( self, layer: torch.nn.Module, input_size_per_partition: int, output_partition_sizes: list[int], input_size: int, output_size: int, params_dtype: torch.dtype, **extra_weight_attrs, ): del output_size # Unused. del input_size # Unused. if params_dtype != torch.bfloat16: raise ValueError("Only bfloat16 is currently supported by FPQuant") if input_size_per_partition % self.quant_config.hadamard_group_size != 0: # noqa: E501 raise ValueError( "The input size is not aligned with the quantized " "weight shape. This can be caused by too large " "tensor parallel size. Or other skill issues." ) assert self.quant_config.forward_dtype in ["mxfp4", "nvfp4"], ( "Only mxfp4 and nvfp4 are supported for now" ) if self.quant_config.forward_dtype == "mxfp4": group_size = 32 elif self.quant_config.forward_dtype == "nvfp4": group_size = 16 else: raise ValueError( f"Unsupported forward_dtype: {self.quant_config.forward_dtype}" ) qweight = Parameter( torch.empty( sum(output_partition_sizes), input_size_per_partition // 2, dtype=torch.uint8, ), requires_grad=False, ) set_weight_attrs( qweight, { "input_dim": 1, "output_dim": 0, "packed_dim": 1, "pack_factor": 2, } | extra_weight_attrs, ) layer.register_parameter("qweight", qweight) scales = Parameter( torch.empty( sum(output_partition_sizes), input_size_per_partition // group_size, dtype=torch.uint8, ), requires_grad=False, ) set_weight_attrs( scales, { "input_dim": 1, "output_dim": 0, "packed_dim": 1, "pack_factor": group_size, } | extra_weight_attrs, ) layer.register_parameter("scales", scales) weight_global_scale = Parameter( torch.empty(1, dtype=torch.float32), requires_grad=False, ) set_weight_attrs( weight_global_scale, {"ignore_warning": True} | extra_weight_attrs ) layer.register_parameter("weight_global_scale", weight_global_scale) act_global_scale = Parameter( torch.empty(1, dtype=torch.float32), requires_grad=False, ) set_weight_attrs( act_global_scale, {"ignore_warning": True} | extra_weight_attrs ) layer.register_parameter("act_global_scale", act_global_scale) forward_hadamard_matrix = Parameter( torch.empty( self.quant_config.hadamard_group_size, self.quant_config.hadamard_group_size, dtype=params_dtype, ), requires_grad=False, ) set_weight_attrs( forward_hadamard_matrix, {"ignore_warning": True} | extra_weight_attrs ) layer.register_parameter("forward_hadamard_matrix", forward_hadamard_matrix) backward_hadamard_matrix = Parameter( torch.empty( self.quant_config.hadamard_group_size, self.quant_config.hadamard_group_size, dtype=params_dtype, ), requires_grad=False, ) set_weight_attrs( backward_hadamard_matrix, {"ignore_warning": True} | extra_weight_attrs ) layer.register_parameter("backward_hadamard_matrix", backward_hadamard_matrix) def apply( self, layer: torch.nn.Module, x: torch.Tensor, bias: torch.Tensor | None = None, ) -> torch.Tensor: return quantized_forward( x, layer.qweight, layer.scales, layer.weight_global_scale, layer.act_global_scale, bias, layer.forward_hadamard_matrix, self.quant_config.forward_method, self.quant_config.forward_dtype, ) def fused_quantize_mx( x_flat: torch.Tensor, hadamard_matrix: torch.Tensor, forward_method: str ) -> tuple[torch.Tensor, torch.Tensor]: return fusedQuantizeMx(x_flat, hadamard_matrix, method=forward_method) def fused_quantize_mx_fake(x_flat, hadamard_matrix, forward_method): rows, cols = x_flat.size(0), x_flat.size(1) // 32 padded_rows = ((rows + 128 - 1) // 128) * 128 padded_cols = ((cols + 4 - 1) // 4) * 4 xh_e2m1 = torch.empty( x_flat.size(0), x_flat.size(1) // 2, dtype=torch.uint8, device=x_flat.device ) xh_e8m0 = torch.empty( padded_rows, padded_cols, dtype=torch.float8_e8m0fnu, device=x_flat.device ) return xh_e2m1, xh_e8m0 direct_register_custom_op( op_name="fused_quantize_mx", op_func=fused_quantize_mx, mutates_args=[], fake_impl=fused_quantize_mx_fake, dispatch_key=current_platform.dispatch_key, ) def matmul_mxf4_bf16( x: torch.Tensor, w: torch.Tensor, xs: torch.Tensor, ws: torch.Tensor, alpha: torch.Tensor, ) -> torch.Tensor: return matmul_mxf4_bf16_tn( x, w, to_blocked(xs, backend="triton").view(torch.float8_e8m0fnu), to_blocked(ws, backend="triton").view(torch.float8_e8m0fnu), alpha, ) def matmul_mxf4_bf16_fake(x, w, xs, ws, alpha): return torch.empty(*x.shape[:-1], w.shape[0], dtype=torch.bfloat16, device=x.device) direct_register_custom_op( op_name="matmul_mxf4_bf16", op_func=matmul_mxf4_bf16, mutates_args=[], fake_impl=matmul_mxf4_bf16_fake, dispatch_key=current_platform.dispatch_key, ) def fused_quantize_nv( x_flat: torch.Tensor, hadamard_matrix: torch.Tensor, global_scale: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: return fusedQuantizeNv(x_flat, hadamard_matrix, global_scale) def fused_quantize_nv_fake(x_flat, hadamard_matrix, global_scale): rows, cols = x_flat.size(0), x_flat.size(1) // 16 padded_rows = ((rows + 128 - 1) // 128) * 128 padded_cols = ((cols + 4 - 1) // 4) * 4 xh_e2m1 = torch.empty( x_flat.size(0), x_flat.size(1) // 2, dtype=torch.uint8, device=x_flat.device ) xh_e8m0 = torch.empty( padded_rows, padded_cols, dtype=torch.float8_e4m3fn, device=x_flat.device ) return xh_e2m1, xh_e8m0 direct_register_custom_op( op_name="fused_quantize_nv", op_func=fused_quantize_nv, mutates_args=[], fake_impl=fused_quantize_nv_fake, dispatch_key=current_platform.dispatch_key, ) def matmul_nvf4_bf16( x: torch.Tensor, w: torch.Tensor, xs: torch.Tensor, ws: torch.Tensor, alpha: torch.Tensor, ) -> torch.Tensor: return cutlass_scaled_fp4_mm( x, w, to_blocked(xs, backend="triton") .view(torch.float8_e4m3fn) .view(-1, x.shape[1] // 8), # *2//16 to_blocked(ws, backend="triton") .view(torch.float8_e4m3fn) .view(-1, x.shape[1] // 8), alpha, torch.bfloat16, ) def matmul_nvf4_bf16_fake(x, w, xs, ws, alpha): return torch.empty(*x.shape[:-1], w.shape[0], dtype=torch.bfloat16, device=x.device) direct_register_custom_op( op_name="matmul_nvf4_bf16", op_func=matmul_nvf4_bf16, mutates_args=[], fake_impl=matmul_nvf4_bf16_fake, dispatch_key=current_platform.dispatch_key, ) def quantized_forward( x: torch.Tensor, qweight: torch.Tensor, weight_scales: torch.Tensor, weight_global_scale: torch.Tensor, act_global_scale: torch.Tensor, bias: torch.Tensor | None, forward_hadamard_matrix: torch.Tensor, forward_method: str, forward_dtype: str, ) -> torch.Tensor: x_flat = x.contiguous().flatten(end_dim=-2) if forward_dtype == "mxfp4": x_flat_q, x_flat_scales = torch.ops.vllm.fused_quantize_mx( x_flat, forward_hadamard_matrix, forward_method ) y = torch.ops.vllm.matmul_mxf4_bf16( x_flat_q, qweight, x_flat_scales, weight_scales, 1 / (weight_global_scale * act_global_scale), ) elif forward_dtype == "nvfp4": x_flat_q, x_flat_scales = torch.ops.vllm.fused_quantize_nv( x_flat, forward_hadamard_matrix, act_global_scale ) y = torch.ops.vllm.matmul_nvf4_bf16( x_flat_q, qweight, x_flat_scales, weight_scales, 1 / (weight_global_scale * act_global_scale), ) else: raise ValueError(f"Unsupported forward_dtype: {forward_dtype}") y = y.view(*x.shape[:-1], y.shape[-1]) if bias is not None: y += bias return y
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/layers/quantization/fp_quant.py", "license": "Apache License 2.0", "lines": 353, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/layers/quantization/qutlass_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # # Modified by Roberto L. Castro (Roberto.LopezCastro@ist.ac.at). # # Copied from https://github.com/pytorch/ao/tree/main/torchao/prototype/mx_formats # # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Literal import torch from torch.library import wrap_triton from vllm.triton_utils import tl, triton from vllm.utils.math_utils import cdiv @triton.jit def triton_scale_swizzle( scale_ptr: torch.Tensor, scale_rows: int, scale_cols: int, output_ptr: torch.Tensor, input_row_stride: int, output_block_stride: int, BLOCK_ROWS: tl.constexpr, BLOCK_COLS: tl.constexpr, ): """ Rearranges tensor data from row-major to block-scaled swizzle format. Args: scale_ptr: Pointer to the input scale tensor scale_rows: Number of rows in the scale tensor scale_cols: Number of columns in the scale tensor output_ptr: Pointer to the output tensor input_row_stride: Stride between rows in the input tensor output_block_stride: Stride between blocks in the output tensor BLOCK_ROWS: Number of rows in a tile (compile-time constant) BLOCK_COLS: Number of columns in a tile (compile-time constant) """ pid_row = tl.program_id(0) pid_col = tl.program_id(1) rows = tl.arange(0, BLOCK_ROWS)[:, None] cols = tl.arange(0, BLOCK_COLS)[None, :] # Calculate starting row and column for this tile start_row = pid_row * BLOCK_ROWS start_col = pid_col * BLOCK_COLS global_rows = start_row + rows global_cols = start_col + cols mask = (global_rows < scale_rows) & (global_cols < scale_cols) input_scales = tl.load( scale_ptr + global_rows * input_row_stride + global_cols, mask=mask, other=0.0, ) r_div_32 = rows // 32 r_mod_32 = rows % 32 # 2) Rearrange to (32, 4, 4) then to final (32, 16) coordinates dest_indices = r_mod_32 * 16 + r_div_32 * 4 + cols # Flatten dest_indices_flat = tl.reshape(dest_indices, (BLOCK_ROWS * BLOCK_COLS)) scales_flat = tl.reshape(input_scales, (BLOCK_ROWS * BLOCK_COLS)) # Calculate block offset using provided output block stride LOCAL_NUMEL = BLOCK_ROWS * BLOCK_COLS block_offset = pid_col * LOCAL_NUMEL + (pid_row * output_block_stride) tl.store( output_ptr + block_offset + dest_indices_flat, scales_flat, ) def triton_mx_block_rearrange(scale_tensor: torch.Tensor) -> torch.Tensor: """ Rearranges an E8M0 tensor scale from row-major format to block-scaled swizzle format. This format is suitable for Tmem as described in NVIDIA documentation: https://docs.nvidia.com/cuda/cublas/index.html#d-block-scaling-factors-layout Args: scale_tensor: Input tensor in row-major format with 8-bit elements Returns: Rearranged tensor in block-scaled swizzle format """ assert scale_tensor.element_size() == 1, ( "Expected element size to be 1 byte (8 bits)" ) assert scale_tensor.is_contiguous(), "Input tensor must be contiguous" rows, cols = scale_tensor.shape # Calculate blocks needed n_row_blocks = triton.cdiv(rows, 128) n_col_blocks = triton.cdiv(cols, 4) padded_rows = n_row_blocks * 128 padded_cols = n_col_blocks * 4 out = scale_tensor.new_empty((padded_rows, padded_cols)) # Input stride (for row-major format) input_row_stride = cols # We probably want handle multiple blocks per tile but # for now keep it simple BLOCK_ROWS, BLOCK_COLS = 128, 4 # Output block stride for the rearranged format output_block_stride = BLOCK_ROWS * BLOCK_COLS * (padded_cols // BLOCK_COLS) grid = lambda META: ( triton.cdiv(padded_rows, BLOCK_ROWS), triton.cdiv(padded_cols, BLOCK_COLS), ) wrap_triton(triton_scale_swizzle)[grid]( scale_tensor.view(torch.uint8), rows, cols, out.view(torch.uint8), input_row_stride, output_block_stride, BLOCK_ROWS=BLOCK_ROWS, BLOCK_COLS=BLOCK_COLS, ) return out def to_blocked( input_matrix: torch.Tensor, backend: Literal["torch", "triton"] = "triton" ) -> torch.Tensor: """ Rearrange a large matrix by breaking it into blocks and applying the rearrangement pattern. See: https://docs.nvidia.com/cuda/cublas/index.html#d-block-scaling-factors-layout Args: input_matrix: Input tensor of shape (H, W) backend: "torch" (PyTorch path) or "triton" (Triton kernel) Returns: Rearranged tensor of shape (32*cdiv(H,128), 16*cdiv(W,4)) """ if backend == "triton": return triton_mx_block_rearrange(input_matrix).flatten() elif backend != "torch": raise ValueError(f'backend must be "torch" or "triton", got {backend!r}') rows, cols = input_matrix.shape n_row_blocks = cdiv(rows, 128) n_col_blocks = cdiv(cols, 4) # Calculate the padded shape padded_rows = n_row_blocks * 128 padded_cols = n_col_blocks * 4 padded = input_matrix assert (rows, cols) == (padded_rows, padded_cols) # Rearrange the blocks blocks = padded.view(n_row_blocks, 128, n_col_blocks, 4).permute(0, 2, 1, 3) rearranged = blocks.reshape(-1, 4, 32, 4).transpose(1, 2).reshape(-1, 32, 16) return rearranged.flatten()
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/layers/quantization/qutlass_utils.py", "license": "Apache License 2.0", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/flex_olmo.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Inference-only FlexOlmo model compatible with HuggingFace weights.""" import torch from torch import nn from vllm.config import VllmConfig from vllm.distributed import get_tensor_model_parallel_world_size from vllm.logger import init_logger from vllm.model_executor.layers.fused_moe import FusedMoE from vllm.model_executor.layers.layernorm import RMSNorm from vllm.model_executor.layers.linear import ReplicatedLinear from vllm.model_executor.models.olmoe import OlmoeAttention, OlmoeForCausalLM from vllm.transformers_utils.configs import FlexOlmoConfig logger = init_logger(__name__) class FlexOlmoAttention(OlmoeAttention): def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__(vllm_config=vllm_config, prefix=prefix) hf_config = vllm_config.model_config.hf_config assert isinstance(hf_config, FlexOlmoConfig) self.k_norm = RMSNorm( self.total_num_kv_heads * self.head_dim, eps=hf_config.rms_norm_eps ) self.q_norm = RMSNorm( self.total_num_heads * self.head_dim, eps=hf_config.rms_norm_eps ) class FlexOlmoMoE(nn.Module): """A tensor-parallel MoE implementation for FlexOlmo that shards each expert across all ranks. Each expert's weights are sharded across all ranks and a fused MoE kernel is used for the forward pass, and finally we reduce the outputs across ranks. """ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() hf_config = vllm_config.model_config.hf_config assert isinstance(hf_config, FlexOlmoConfig) tp_size = get_tensor_model_parallel_world_size() # Gate always runs at half / full precision for now. self.gate = ReplicatedLinear( hf_config.hidden_size, hf_config.num_experts, bias=False, return_bias=False, quant_config=None, prefix=f"{prefix}.gate", ) self.experts = FusedMoE( num_experts=hf_config.num_experts, top_k=hf_config.num_experts_per_tok, hidden_size=hf_config.hidden_size, intermediate_size=hf_config.intermediate_size, reduce_results=True, renormalize=False, quant_config=None, tp_size=tp_size, prefix=f"{prefix}.experts", router_logits_dtype=torch.float32, ) self.top_k = hf_config.num_experts_per_tok def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # NOTE: hidden_states can have either 1D or 2D shape. orig_shape = hidden_states.shape hidden_dim = hidden_states.shape[-1] hidden_states = hidden_states.view(-1, hidden_dim) # router_logits: (num_tokens, n_experts) router_logits = self.gate(hidden_states) # Warning: The experts mutate the hidden state input! This messes up # basic things like the residual stream. final_hidden_states = self.experts( hidden_states=hidden_states.detach().clone(), router_logits=router_logits.float(), ) return final_hidden_states.view(orig_shape) class FlexOlmoDecoderLayer(nn.Module): def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: super().__init__() hf_config = vllm_config.model_config.hf_config assert isinstance(hf_config, FlexOlmoConfig) self.self_attn = FlexOlmoAttention( vllm_config=vllm_config, prefix=f"{prefix}.self_attn" ) self.post_attention_layernorm = RMSNorm( hf_config.hidden_size, eps=hf_config.rms_norm_eps ) self.post_feedforward_layernorm = RMSNorm( hf_config.hidden_size, eps=hf_config.rms_norm_eps ) self.mlp = FlexOlmoMoE(vllm_config=vllm_config, prefix=f"{prefix}.mlp") def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor | None]: # Attention block. residual = hidden_states hidden_states = self.self_attn(positions, hidden_states) hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = hidden_states + residual # MLP block. residual = hidden_states hidden_states = self.mlp(hidden_states) hidden_states = self.post_feedforward_layernorm(hidden_states) hidden_states = residual + hidden_states return hidden_states, None class FlexOlmoForCausalLM(OlmoeForCausalLM): fall_back_to_pt_during_load = False def __init__( self, *, vllm_config: VllmConfig, prefix: str = "", layer_type: type[nn.Module] = FlexOlmoDecoderLayer, ): super().__init__(vllm_config=vllm_config, prefix=prefix, layer_type=layer_type)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/flex_olmo.py", "license": "Apache License 2.0", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/transformers_utils/configs/flex_olmo.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any from transformers.configuration_utils import PretrainedConfig class FlexOlmoConfig(PretrainedConfig): model_type = "flex_olmo" keys_to_ignore_at_inference = ["past_key_values"] def __init__( self, vocab_size=100352, hidden_size=4096, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=None, hidden_act="silu", max_position_embeddings=4096, initializer_range=0.02, rms_norm_eps=1e-06, use_cache=True, pad_token_id=100277, bos_token_id=None, eos_token_id=100257, tie_word_embeddings=False, rope_parameters: dict[str, Any] | None = None, attention_bias=False, attention_dropout=0.0, num_experts_per_tok=5, num_experts=7, output_router_logits=False, router_aux_loss_coef=0.01, norm_topk_prob=False, **kwargs, ): if "architectures" not in kwargs: kwargs["architectures"] = ["FlexOlmoForCausalLM"] super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache # Try to set `rope_scaling` if available, otherwise use `rope_parameters` rope_scaling = kwargs.pop("rope_scaling", None) rope_parameters = rope_scaling or rope_parameters or {"rope_type": "default"} rope_theta = kwargs.pop("rope_theta", 500000.0) if "rope_theta" not in rope_parameters: rope_parameters["rope_theta"] = rope_theta self.rope_parameters = rope_parameters self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.num_experts_per_tok = num_experts_per_tok self.num_experts = num_experts self.output_router_logits = output_router_logits self.router_aux_loss_coef = router_aux_loss_coef self.norm_topk_prob = norm_topk_prob # Validate the correctness of rotary position embeddings parameters # BC: if there is a 'type' field, move it to 'rope_type'. if self.rope_parameters is not None and "type" in self.rope_parameters: self.rope_parameters["rope_type"] = self.rope_parameters["type"]
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/transformers_utils/configs/flex_olmo.py", "license": "Apache License 2.0", "lines": 75, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/compilation/partition_rules.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib from collections.abc import Generator import torch from vllm.logger import init_logger logger = init_logger(__name__) def should_split(node: torch.fx.Node, splitting_ops: list[str]) -> bool: """ Check if a node should be split for dynamo graph partition. It operates on dynamo graph, so the node.target can be anything. We need to check and split only on OpOverload and OpOverloadPacket. """ if node.op != "call_function": return False target = node.target if isinstance(target, torch._ops.OpOverloadPacket): # Example: "aten::add" return target._qualified_op_name in splitting_ops if isinstance(target, torch._ops.OpOverload): # Example: "aten::add" packet_name = target.name() # Example: "aten::add.default" op_overload_name = f"{packet_name}.{target._overloadname}" return op_overload_name in splitting_ops or packet_name in splitting_ops return False @contextlib.contextmanager def inductor_partition_rule_context( splitting_ops: list[str] | None, ) -> Generator[None, None, None]: """Context manager to temporarily register Inductor partition rules. Registers custom partition rules for specified operators, forcing the Inductor scheduler to partition the graph at these operators. The rules are automatically restored to their previous state on exit. Args: splitting_ops: List of operator names to partition on. """ if not splitting_ops: logger.debug("No partition ops provided; skipping rule registration.") yield return # Save current state before registering saved_splitting_ops: list[str] = list( torch._inductor.config.custom_should_partition_ops ) torch._inductor.config.custom_should_partition_ops = splitting_ops logger.debug( "Registered inductor partition rules for %d operators", len(splitting_ops) ) try: yield finally: # Clear and restore previous state torch._inductor.config.custom_should_partition_ops = saved_splitting_ops logger.debug("Restored previous partition rules state.")
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/compilation/partition_rules.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/entrypoints/llm/test_mm_cache_stats.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import logging import pytest import regex as re from vllm import LLM from vllm.entrypoints.chat_utils import ChatCompletionMessageParam from vllm.v1.metrics import loggers as stat_loggers from vllm.v1.metrics.reader import Counter, Metric from ..openai.test_vision import TEST_IMAGE_ASSETS def _make_messages(image_url: str) -> list[ChatCompletionMessageParam]: return [ { "role": "user", "content": [ { "type": "image_url", "image_url": {"url": image_url}, }, ], } ] def _get_counter_value(metrics: list[Metric], name: str): metric = next(m for m in metrics if m.name == name) assert isinstance(metric, Counter) return metric.value def _get_mm_cache_stats(metrics: list[Metric]): mm_cache_queries = _get_counter_value(metrics, "vllm:mm_cache_queries") mm_cache_hits = _get_counter_value(metrics, "vllm:mm_cache_hits") return mm_cache_queries, mm_cache_hits def _get_mm_cache_log(llm: LLM, caplog_vllm: pytest.LogCaptureFixture) -> float: caplog_vllm.clear() with caplog_vllm.at_level(logging.INFO, logger=stat_loggers.__name__): llm.llm_engine.do_log_stats() assert len(caplog_vllm.records) == 1 msg = caplog_vllm.records[0].getMessage() assert "MM cache hit rate" in msg match = re.search(r"MM cache hit rate: ([0-9.]+)%", msg) assert match is not None return float(match.group(1)) @pytest.mark.parametrize("image_urls", [TEST_IMAGE_ASSETS[:2]], indirect=True) @pytest.mark.parametrize("mm_processor_cache_type", ["lru", "shm"]) def test_mm_cache_stats( num_gpus_available, image_urls, mm_processor_cache_type, caplog_vllm, ): llm = LLM( model="llava-hf/llava-1.5-7b-hf", max_model_len=4096, max_num_seqs=5, enforce_eager=True, mm_processor_cache_type=mm_processor_cache_type, disable_log_stats=False, limit_mm_per_prompt={"image": 2}, ) llm.chat(_make_messages(image_urls[0])) assert _get_mm_cache_stats(llm.get_metrics()) == (1, 0) assert _get_mm_cache_log(llm, caplog_vllm) == pytest.approx(0.0) llm.chat(_make_messages(image_urls[1])) assert _get_mm_cache_stats(llm.get_metrics()) == (2, 0) assert _get_mm_cache_log(llm, caplog_vllm) == pytest.approx(0.0) llm.chat(_make_messages(image_urls[0])) assert _get_mm_cache_stats(llm.get_metrics()) == (3, 1) assert _get_mm_cache_log(llm, caplog_vllm) == pytest.approx(33.3) # NOTE: This only resets hit rate stats in CachingMetrics # The raw queries and hits counts remain unaffected llm.reset_mm_cache() llm.chat(_make_messages(image_urls[0])) assert _get_mm_cache_stats(llm.get_metrics()) == (4, 1) assert _get_mm_cache_log(llm, caplog_vllm) == pytest.approx(0.0) llm.chat(_make_messages(image_urls[1])) assert _get_mm_cache_stats(llm.get_metrics()) == (5, 1) assert _get_mm_cache_log(llm, caplog_vllm) == pytest.approx(0.0)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/entrypoints/llm/test_mm_cache_stats.py", "license": "Apache License 2.0", "lines": 75, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tools/install_nixl_from_source_ubuntu.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # install_prerequisites.py import argparse import glob import json import os import subprocess import sys import urllib.request # --- Configuration --- WHEELS_CACHE_HOME = os.environ.get("WHEELS_CACHE_HOME", "/tmp/wheels_cache") ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) UCX_DIR = os.path.join("/tmp", "ucx_source") NIXL_DIR = os.path.join("/tmp", "nixl_source") UCX_INSTALL_DIR = os.path.join("/tmp", "ucx_install") UCX_REPO_URL = "https://github.com/openucx/ucx.git" NIXL_REPO_URL = "https://github.com/ai-dynamo/nixl.git" # --- Helper Functions --- def get_latest_nixl_version(): """Helper function to get latest release version of NIXL""" try: nixl_release_url = "https://api.github.com/repos/ai-dynamo/nixl/releases/latest" with urllib.request.urlopen(nixl_release_url) as response: data = json.load(response) return data.get("tag_name", "0.7.0") except Exception: return "0.7.0" NIXL_VERSION = os.environ.get("NIXL_VERSION", get_latest_nixl_version()) def run_command(command, cwd=".", env=None): """Helper function to run a shell command and check for errors.""" print(f"--> Running command: {' '.join(command)} in '{cwd}'", flush=True) subprocess.check_call(command, cwd=cwd, env=env) def is_pip_package_installed(package_name): """Checks if a package is installed via pip without raising an exception.""" result = subprocess.run( [sys.executable, "-m", "pip", "show", package_name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) return result.returncode == 0 def find_nixl_wheel_in_cache(cache_dir): """Finds a nixl wheel file in the specified cache directory.""" # The repaired wheel will have a 'manylinux' tag, but this glob still works. search_pattern = os.path.join(cache_dir, f"nixl*{NIXL_VERSION}*.whl") wheels = glob.glob(search_pattern) if wheels: # Sort to get the most recent/highest version if multiple exist wheels.sort() return wheels[-1] return None def install_system_dependencies(): """Installs required system packages using apt-get if run as root.""" if os.geteuid() != 0: print("\n---", flush=True) print( "WARNING: Not running as root. \ Skipping system dependency installation.", flush=True, ) print( "Please ensure the listed packages are installed on your system:", flush=True, ) print( " patchelf build-essential git cmake ninja-build \ autotools-dev automake meson libtool libtool-bin", flush=True, ) print("---\n", flush=True) return print("--- Running as root. Installing system dependencies... ---", flush=True) apt_packages = [ "patchelf", # <-- Add patchelf here "build-essential", "git", "cmake", "ninja-build", "autotools-dev", "automake", "meson", "libtool", "libtool-bin", "pkg-config", ] run_command(["apt-get", "update"]) run_command(["apt-get", "install", "-y"] + apt_packages) print("--- System dependencies installed successfully. ---\n", flush=True) def build_and_install_prerequisites(args): """Builds UCX and NIXL from source, creating a self-contained wheel.""" if not args.force_reinstall and is_pip_package_installed("nixl"): print("--> NIXL is already installed. Nothing to do.", flush=True) return cached_wheel = find_nixl_wheel_in_cache(WHEELS_CACHE_HOME) if not args.force_reinstall and cached_wheel: print( f"\n--> Found self-contained wheel: \ {os.path.basename(cached_wheel)}.", flush=True, ) print("--> Installing from cache, skipping all source builds.", flush=True) install_command = [sys.executable, "-m", "pip", "install", cached_wheel] run_command(install_command) print("\n--- Installation from cache complete. ---", flush=True) return print( "\n--> No installed package or cached wheel found. \ Starting full build process...", flush=True, ) print("\n--> Installing auditwheel...", flush=True) run_command([sys.executable, "-m", "pip", "install", "auditwheel"]) install_system_dependencies() ucx_install_path = os.path.abspath(UCX_INSTALL_DIR) print(f"--> Using wheel cache directory: {WHEELS_CACHE_HOME}", flush=True) os.makedirs(WHEELS_CACHE_HOME, exist_ok=True) # -- Step 1: Build UCX from source -- print("\n[1/3] Configuring and building UCX from source...", flush=True) if not os.path.exists(UCX_DIR): run_command(["git", "clone", UCX_REPO_URL, UCX_DIR]) ucx_source_path = os.path.abspath(UCX_DIR) run_command(["git", "checkout", "v1.19.x"], cwd=ucx_source_path) run_command(["./autogen.sh"], cwd=ucx_source_path) configure_command = [ "./configure", f"--prefix={ucx_install_path}", "--enable-shared", "--disable-static", "--disable-doxygen-doc", "--enable-optimizations", "--enable-cma", "--enable-devel-headers", "--with-verbs", "--enable-mt", "--with-ze=no", ] run_command(configure_command, cwd=ucx_source_path) run_command(["make", "-j", str(os.cpu_count() or 1)], cwd=ucx_source_path) run_command(["make", "install"], cwd=ucx_source_path) print("--- UCX build and install complete ---", flush=True) # -- Step 2: Build NIXL wheel from source -- print("\n[2/3] Building NIXL wheel from source...", flush=True) if not os.path.exists(NIXL_DIR): run_command(["git", "clone", NIXL_REPO_URL, NIXL_DIR]) else: run_command(["git", "fetch", "--tags"], cwd=NIXL_DIR) run_command(["git", "checkout", NIXL_VERSION], cwd=NIXL_DIR) print(f"--> Checked out NIXL version: {NIXL_VERSION}", flush=True) build_env = os.environ.copy() build_env["PKG_CONFIG_PATH"] = os.path.join(ucx_install_path, "lib", "pkgconfig") ucx_lib_path = os.path.join(ucx_install_path, "lib") ucx_plugin_path = os.path.join(ucx_lib_path, "ucx") existing_ld_path = os.environ.get("LD_LIBRARY_PATH", "") build_env["LD_LIBRARY_PATH"] = ( f"{ucx_lib_path}:{ucx_plugin_path}:{existing_ld_path}".strip(":") ) build_env["LDFLAGS"] = "-Wl,-rpath,$ORIGIN" print(f"--> Using LD_LIBRARY_PATH: {build_env['LD_LIBRARY_PATH']}", flush=True) temp_wheel_dir = os.path.join(ROOT_DIR, "temp_wheelhouse") run_command( [ sys.executable, "-m", "pip", "wheel", ".", "--no-deps", f"--wheel-dir={temp_wheel_dir}", ], cwd=os.path.abspath(NIXL_DIR), env=build_env, ) # -- Step 3: Repair the wheel by copying UCX libraries -- print("\n[3/3] Repairing NIXL wheel to include UCX libraries...", flush=True) unrepaired_wheel = find_nixl_wheel_in_cache(temp_wheel_dir) if not unrepaired_wheel: raise RuntimeError("Failed to find the NIXL wheel after building it.") # We tell auditwheel to ignore the plugin that mesonpy already handled. auditwheel_command = [ "auditwheel", "repair", "--exclude", "libplugin_UCX.so", # <-- Exclude because mesonpy already includes it unrepaired_wheel, f"--wheel-dir={WHEELS_CACHE_HOME}", ] run_command(auditwheel_command, env=build_env) # --- CLEANUP --- # No more temporary files to remove, just the temp wheelhouse run_command(["rm", "-rf", temp_wheel_dir]) # --- END CLEANUP --- newly_built_wheel = find_nixl_wheel_in_cache(WHEELS_CACHE_HOME) if not newly_built_wheel: raise RuntimeError("Failed to find the repaired NIXL wheel.") print( f"--> Successfully built self-contained wheel: \ {os.path.basename(newly_built_wheel)}. Now installing...", flush=True, ) install_command = [ sys.executable, "-m", "pip", "install", "--no-deps", # w/o "no-deps", it will install cuda-torch newly_built_wheel, ] if args.force_reinstall: install_command.insert(-1, "--force-reinstall") run_command(install_command) print("--- NIXL installation complete ---", flush=True) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Build and install UCX and NIXL dependencies." ) parser.add_argument( "--force-reinstall", action="store_true", help="Force rebuild and reinstall of UCX and NIXL \ even if they are already installed.", ) args = parser.parse_args() build_and_install_prerequisites(args)
{ "repo_id": "vllm-project/vllm", "file_path": "tools/install_nixl_from_source_ubuntu.py", "license": "Apache License 2.0", "lines": 223, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/models/lfm2_moe.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Iterable from itertools import islice import torch import torch.nn as nn from vllm.compilation.decorators import support_torch_compile from vllm.config import CacheConfig, ModelConfig, VllmConfig, get_current_vllm_config from vllm.distributed import ( get_ep_group, get_pp_group, get_tensor_model_parallel_world_size, ) from vllm.model_executor.layers.activation import SiluAndMul from vllm.model_executor.layers.attention import Attention from vllm.model_executor.layers.fused_moe import FusedMoE from vllm.model_executor.layers.layernorm import RMSNorm from vllm.model_executor.layers.linear import ( MergedColumnParallelLinear, QKVParallelLinear, ReplicatedLinear, RowParallelLinear, ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.mamba.mamba_utils import ( MambaStateCopyFunc, MambaStateCopyFuncCalculator, MambaStateDtypeCalculator, MambaStateShapeCalculator, ) from vllm.model_executor.layers.mamba.short_conv import ShortConv from vllm.model_executor.layers.quantization import QuantizationConfig from vllm.model_executor.layers.rotary_embedding import get_rope from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, VocabParallelEmbedding, ) from vllm.model_executor.model_loader.weight_utils import default_weight_loader from vllm.sequence import IntermediateTensors from vllm.transformers_utils.configs import Lfm2MoeConfig from .interfaces import ( HasInnerState, IsHybrid, MixtureOfExperts, SupportsLoRA, SupportsPP, SupportsQuant, ) from .utils import ( AutoWeightsLoader, PPMissingLayer, WeightsMapper, extract_layer_index, is_pp_missing_parameter, make_empty_intermediate_tensors_factory, make_layers, maybe_prefix, ) class Lfm2MoeMlp(nn.Module): def __init__( self, dim: int, ff_dim: int, quant_config: QuantizationConfig | None = None, prefix: str = "", ): super().__init__() self.w13 = MergedColumnParallelLinear( input_size=dim, output_sizes=[ff_dim] * 2, bias=False, quant_config=quant_config, prefix=f"{prefix}.w13", ) self.w2 = RowParallelLinear( input_size=ff_dim, output_size=dim, bias=False, quant_config=quant_config, prefix=f"{prefix}.w2", ) self.act_fn = SiluAndMul() def forward(self, x: torch.Tensor) -> torch.Tensor: gate_up, _ = self.w13(x) x = self.act_fn(gate_up) x, _ = self.w2(x) return x class Lfm2MoeSparseMoeBlock(nn.Module): def __init__( self, config: Lfm2MoeConfig, quant_config: QuantizationConfig | None = None, prefix: str = "", enable_eplb: bool = False, ): super().__init__() self.tp_size = get_tensor_model_parallel_world_size() self.routed_scaling_factor = config.routed_scaling_factor self.ep_group = get_ep_group().device_group self.ep_rank = get_ep_group().rank_in_group self.ep_size = self.ep_group.size() self.n_routed_experts = config.num_experts if self.tp_size > self.n_routed_experts: raise ValueError( f"Tensor parallel size {self.tp_size} is greater than " f"the number of experts {self.n_routed_experts}." ) # Load balancing settings. vllm_config = get_current_vllm_config() eplb_config = vllm_config.parallel_config.eplb_config self.enable_eplb = enable_eplb self.n_logical_experts = self.n_routed_experts self.n_redundant_experts = eplb_config.num_redundant_experts self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts self.n_local_physical_experts = self.n_physical_experts // self.ep_size self.physical_expert_start = self.ep_rank * self.n_local_physical_experts self.physical_expert_end = ( self.physical_expert_start + self.n_local_physical_experts ) self.gate = ReplicatedLinear( config.hidden_size, config.num_experts, bias=False, quant_config=quant_config, prefix=f"{prefix}.gate", ) if config.use_expert_bias: self.gate.e_score_correction_bias = nn.Parameter( torch.empty(self.n_routed_experts, dtype=torch.float32) ) else: self.gate.e_score_correction_bias = None self.experts = FusedMoE( num_experts=self.n_routed_experts, top_k=config.num_experts_per_tok, hidden_size=config.hidden_size, intermediate_size=config.moe_intermediate_size, reduce_results=False, renormalize=config.norm_topk_prob, quant_config=quant_config, use_grouped_topk=True, # needed for softmax score func num_expert_group=1, topk_group=1, prefix=f"{prefix}.experts", enable_eplb=self.enable_eplb, num_redundant_experts=self.n_redundant_experts, scoring_func="sigmoid", e_score_correction_bias=self.gate.e_score_correction_bias, ) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: orig_shape = hidden_states.shape hidden_dim = hidden_states.shape[-1] hidden_states = hidden_states.view(-1, hidden_dim) # router_logits: (num_tokens, n_experts) router_logits, _ = self.gate(hidden_states) final_hidden_states = ( self.experts(hidden_states=hidden_states, router_logits=router_logits) * self.routed_scaling_factor ) if self.tp_size > 1: final_hidden_states = self.experts.maybe_all_reduce_tensor_model_parallel( # noqa E501 final_hidden_states ) return final_hidden_states.view(orig_shape) class Lfm2MoeAttention(nn.Module): def __init__( self, config: Lfm2MoeConfig, layer_idx: int, hidden_size: int, num_heads: int, num_kv_heads: int, max_position_embeddings: int = 8192, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.layer_idx = layer_idx self.hidden_size = hidden_size self.num_kv_heads = num_kv_heads tp_size = get_tensor_model_parallel_world_size() self.total_num_heads = num_heads assert self.total_num_heads % tp_size == 0 self.num_heads = self.total_num_heads // tp_size self.total_num_kv_heads = num_kv_heads if self.total_num_kv_heads >= tp_size: # Number of KV heads is greater than TP size, so we partition # the KV heads across multiple tensor parallel GPUs. assert self.total_num_kv_heads % tp_size == 0 else: # Number of KV heads is less than TP size, so we replicate # the KV heads across multiple tensor parallel GPUs. assert tp_size % self.total_num_kv_heads == 0 self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) self.head_dim = self.hidden_size // self.total_num_heads self.q_size = self.num_heads * self.head_dim self.kv_size = self.num_kv_heads * self.head_dim self.scaling = self.head_dim**-0.5 self.max_position_embeddings = max_position_embeddings self.qkv_proj = QKVParallelLinear( hidden_size=self.hidden_size, head_size=self.head_dim, total_num_heads=self.total_num_heads, total_num_kv_heads=self.total_num_kv_heads, bias=False, quant_config=quant_config, prefix=f"{prefix}.qkv_proj", ) self.out_proj = RowParallelLinear( input_size=self.total_num_heads * self.head_dim, output_size=self.hidden_size, bias=False, quant_config=quant_config, prefix=f"{prefix}.out_proj", ) self.rotary_emb = get_rope( self.head_dim, max_position=self.max_position_embeddings, rope_parameters=config.rope_parameters, is_neox_style=True, ) self.attn = Attention( self.num_heads, self.head_dim, self.scaling, num_kv_heads=self.num_kv_heads, cache_config=cache_config, prefix=f"{prefix}.attn", ) self.q_layernorm = RMSNorm(self.head_dim, eps=config.norm_eps) self.k_layernorm = RMSNorm(self.head_dim, eps=config.norm_eps) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, ) -> torch.Tensor: n_tokens, _ = hidden_states.shape qkv, _ = self.qkv_proj(hidden_states) q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) q = q.view(n_tokens, self.num_heads, self.head_dim).contiguous() k = k.view(n_tokens, self.num_kv_heads, self.head_dim).contiguous() q = self.q_layernorm(q) k = self.k_layernorm(k) q, k = self.rotary_emb(positions, q, k) q = q.view(n_tokens, self.num_heads * self.head_dim) k = k.view(n_tokens, self.num_kv_heads * self.head_dim) attn_output = self.attn(q, k, v) output, _ = self.out_proj(attn_output) return output class Lfm2MoeAttentionDecoderLayer(nn.Module): def __init__( self, config: Lfm2MoeConfig, layer_idx: int, model_config: ModelConfig | None = None, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", enable_eplb: bool = False, ) -> None: super().__init__() self.prefix = prefix self.config = config self.layer_idx = layer_idx max_position_embeddings = getattr(config, "max_position_embeddings", 8192) self.self_attn = Lfm2MoeAttention( config=config, layer_idx=layer_idx, hidden_size=config.hidden_size, num_heads=config.num_attention_heads, num_kv_heads=config.num_key_value_heads, max_position_embeddings=max_position_embeddings, cache_config=cache_config, quant_config=quant_config, prefix=f"{prefix}.self_attn", ) if layer_idx < config.num_dense_layers: self.feed_forward = Lfm2MoeMlp( dim=config.hidden_size, ff_dim=config.intermediate_size, quant_config=quant_config, prefix=f"{prefix}.feed_forward", ) else: self.feed_forward = Lfm2MoeSparseMoeBlock( config=config, quant_config=quant_config, prefix=f"{prefix}.feed_forward", enable_eplb=enable_eplb, ) self.operator_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) self.ffn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, **kwargs, ) -> tuple[torch.Tensor, torch.Tensor]: if residual is None: residual = hidden_states hidden_states = self.operator_norm(hidden_states) else: hidden_states, residual = self.operator_norm(hidden_states, residual) hidden_states = self.self_attn(positions=positions, hidden_states=hidden_states) hidden_states, residual = self.ffn_norm(hidden_states, residual) return self.feed_forward(hidden_states), residual class Lfm2MoeShortConvDecoderLayer(nn.Module): def __init__( self, config: Lfm2MoeConfig, layer_idx: int, model_config: ModelConfig | None = None, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", enable_eplb: bool = False, ) -> None: super().__init__() self.layer_idx = layer_idx self.short_conv = ShortConv( config=config, dim=config.hidden_size, layer_idx=layer_idx, model_config=model_config, cache_config=cache_config, prefix=f"{prefix}.conv", ) if layer_idx < config.num_dense_layers: self.feed_forward = Lfm2MoeMlp( dim=config.hidden_size, ff_dim=config.intermediate_size, quant_config=quant_config, prefix=f"{prefix}.feed_forward", ) else: self.feed_forward = Lfm2MoeSparseMoeBlock( config=config, quant_config=quant_config, prefix=f"{prefix}.feed_forward", enable_eplb=enable_eplb, ) self.operator_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) self.ffn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) def forward( self, hidden_states: torch.Tensor, residual: torch.Tensor | None, **kwargs, ): if residual is None: residual = hidden_states hidden_states = self.operator_norm(hidden_states) else: hidden_states, residual = self.operator_norm(hidden_states, residual) output = torch.empty_like(hidden_states) self.short_conv( hidden_states, output, ) hidden_states, residual = self.ffn_norm(output, residual) hidden_states = self.feed_forward(hidden_states) return hidden_states, residual @support_torch_compile class Lfm2MoeModel(nn.Module): def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() config = vllm_config.model_config.hf_config model_config = vllm_config.model_config cache_config = vllm_config.cache_config quant_config = vllm_config.quant_config parallel_config = vllm_config.parallel_config enable_eplb = parallel_config.enable_eplb eplb_config = parallel_config.eplb_config self.num_redundant_experts = eplb_config.num_redundant_experts self.config = config self.vocab_size = config.vocab_size self.embed_tokens = VocabParallelEmbedding( self.vocab_size, config.hidden_size, org_num_embeddings=config.vocab_size ) def get_layer(prefix: str): layer_idx = extract_layer_index(prefix) is_attn = self.config.layer_types[layer_idx] == "full_attention" layer_class = ( Lfm2MoeAttentionDecoderLayer if is_attn else Lfm2MoeShortConvDecoderLayer ) return layer_class( config, layer_idx, model_config, cache_config, quant_config=quant_config, prefix=prefix, enable_eplb=enable_eplb, ) self.start_layer, self.end_layer, self.layers = make_layers( config.num_hidden_layers, get_layer, prefix=f"{prefix}.layers" ) self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( ["hidden_states", "residual"], config.hidden_size ) if get_pp_group().is_last_rank: self.embedding_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) else: self.embedding_norm = PPMissingLayer() def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids) def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, ) -> torch.Tensor: if get_pp_group().is_first_rank: if inputs_embeds is not None: hidden_states = inputs_embeds else: hidden_states = self.embed_input_ids(input_ids) residual = None else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] residual = intermediate_tensors["residual"] for layer in islice(self.layers, self.start_layer, self.end_layer): hidden_states, residual = layer( positions=positions, hidden_states=hidden_states, residual=residual, ) if not get_pp_group().is_last_rank: return IntermediateTensors( {"hidden_states": hidden_states, "residual": residual} ) hidden_states, _ = self.embedding_norm(hidden_states, residual) return hidden_states def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: return FusedMoE.make_expert_params_mapping( self, ckpt_gate_proj_name="w1", ckpt_down_proj_name="w2", ckpt_up_proj_name="w3", num_experts=self.config.num_experts, num_redundant_experts=self.num_redundant_experts, ) def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: stacked_params_mapping = [ (".qkv_proj", ".q_proj", "q"), (".qkv_proj", ".k_proj", "k"), (".qkv_proj", ".v_proj", "v"), (".w13", ".w1", 0), (".w13", ".w3", 1), ] params_dict = dict(self.named_parameters()) loaded_params: set[str] = set() expert_params_mapping = self.get_expert_mapping() for name, loaded_weight in weights: if "expert_bias" in name: name = name.replace("expert_bias", "gate.e_score_correction_bias") if ".conv." in name: name = name.replace(".conv.", ".short_conv.", 1) for param_name, weight_name, shard_id in stacked_params_mapping: # Skip non-stacked layers and experts (experts handled below). # Use segment-boundary matching (trailing dot) to prevent # e.g. ".w1" from matching inside ".w13" in pre-fused keys. if weight_name + "." not in name: continue if ("feed_forward.experts." in name) and name not in params_dict: continue name = name.replace(weight_name + ".", param_name + ".") # Skip loading extra bias for GPTQ models. if ( name.endswith(".bias") or name.endswith("_bias") ) and name not in params_dict: continue # Skip layers on other devices. if is_pp_missing_parameter(name, self): continue param = params_dict[name] weight_loader = param.weight_loader weight_loader(param, loaded_weight, shard_id) break else: for mapping in expert_params_mapping: param_name, weight_name, expert_id, shard_id = mapping if weight_name not in name: continue name = name.replace(weight_name, param_name) # Skip layers on other devices. if is_pp_missing_parameter(name, self): continue # Skip loading extra bias for GPTQ models. if ( name.endswith(".bias") or name.endswith("_bias") ) and name not in params_dict: continue param = params_dict[name] weight_loader = param.weight_loader weight_loader( param, loaded_weight, name, shard_id=shard_id, expert_id=expert_id, ) break else: # Skip loading extra bias for GPTQ models. if ( name.endswith(".bias") or name.endswith("_bias") ) and name not in params_dict: continue # Skip layers on other devices. if is_pp_missing_parameter(name, self): continue param = params_dict[name] weight_loader = getattr( param, "weight_loader", default_weight_loader ) weight_loader(param, loaded_weight) loaded_params.add(name) return loaded_params class Lfm2MoeForCausalLM( nn.Module, HasInnerState, SupportsLoRA, SupportsPP, IsHybrid, SupportsQuant, MixtureOfExperts, ): packed_modules_mapping = { "qkv_proj": [ "q_proj", "k_proj", "v_proj", ], "w13": [ "w1", "w3", ], "in_proj": ["in_proj"], } # HF uses .conv. but vLLM uses .short_conv. to avoid LoRA regex collision # with the inner .conv.conv child (ShortConv has a child self.conv, so # naming the container .conv too makes _match_target_modules match both) hf_to_vllm_mapper = WeightsMapper( orig_to_new_substr={".conv.": ".short_conv."}, ) # LoRA specific attributes embedding_modules = { "embed_tokens": "input_embeddings", "lm_head": "output_embeddings", } @classmethod def get_mamba_state_dtype_from_config( cls, vllm_config: "VllmConfig", ) -> tuple[torch.dtype, ...]: return MambaStateDtypeCalculator.short_conv_state_dtype( vllm_config.model_config.dtype, vllm_config.cache_config.mamba_cache_dtype, ) @classmethod def get_mamba_state_shape_from_config( cls, vllm_config: "VllmConfig", ) -> tuple[tuple[int, int]]: """Calculate shapes for LFM2's convolutional cache. Args: vllm_config: vLLM config Returns: Tuple containing: - conv_state_shape: Shape for convolutional state cache """ parallel_config = vllm_config.parallel_config hf_config = vllm_config.model_config.hf_config return MambaStateShapeCalculator.short_conv_state_shape( tp_world_size=parallel_config.tensor_parallel_size, intermediate_size=hf_config.hidden_size, conv_kernel=hf_config.conv_L_cache, ) @classmethod def get_mamba_state_copy_func(cls) -> tuple[MambaStateCopyFunc]: return MambaStateCopyFuncCalculator.short_conv_state_copy_func() def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: config = vllm_config.model_config.hf_config quant_config = vllm_config.quant_config cache_config = vllm_config.cache_config if cache_config.mamba_cache_mode == "all": raise NotImplementedError( "Lfm2Moe currently does not support 'all' prefix caching, " "please use '--mamba-cache-mode=align' instead" ) super().__init__() self.config = config self.model = Lfm2MoeModel( vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") ) if get_pp_group().is_last_rank: self.lm_head = ParallelLMHead( config.vocab_size, config.hidden_size, quant_config=quant_config, prefix=maybe_prefix(prefix, "lm_head"), ) self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens) else: self.lm_head = PPMissingLayer() self.logits_processor = LogitsProcessor(config.vocab_size) self.make_empty_intermediate_tensors = ( self.model.make_empty_intermediate_tensors ) # Set MoE hyperparameters self.expert_weights = [] self.moe_layers = [] example_layer = None for layer in self.model.layers: if isinstance(layer, PPMissingLayer): continue assert isinstance( layer, (Lfm2MoeAttentionDecoderLayer, Lfm2MoeShortConvDecoderLayer) ) if isinstance(layer.feed_forward, Lfm2MoeSparseMoeBlock): example_layer = layer.feed_forward self.moe_layers.append(layer.feed_forward.experts) if example_layer is None: raise RuntimeError( "No Lfm2MoeSparseMoeBlock layer found in the model.layers." ) self.num_moe_layers = len(self.moe_layers) self.num_expert_groups = 1 self.num_shared_experts = 0 self.num_logical_experts = example_layer.n_logical_experts self.num_physical_experts = example_layer.n_physical_experts self.num_local_physical_experts = example_layer.n_local_physical_experts self.num_routed_experts = example_layer.n_routed_experts self.num_redundant_experts = example_layer.n_redundant_experts def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.model.embed_input_ids(input_ids) def update_physical_experts_metadata( self, num_physical_experts: int, num_local_physical_experts: int, ) -> None: assert self.num_local_physical_experts == num_local_physical_experts self.num_physical_experts = num_physical_experts self.num_local_physical_experts = num_local_physical_experts self.num_redundant_experts = num_physical_experts - self.num_logical_experts for layer in self.model.layers: if isinstance(layer.feed_forward, Lfm2MoeSparseMoeBlock): moe = layer.feed_forward moe.n_local_physical_experts = num_local_physical_experts moe.n_physical_experts = num_physical_experts moe.n_redundant_experts = self.num_redundant_experts moe.experts.update_expert_map() def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, **kwargs, ) -> torch.Tensor: hidden_states = self.model( input_ids, positions, intermediate_tensors, inputs_embeds ) return hidden_states def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: logits = self.logits_processor(self.lm_head, hidden_states) return logits def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: loader = AutoWeightsLoader( self, skip_prefixes=(["lm_head."] if self.config.tie_word_embeddings else None), ) return loader.load_weights(weights) def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: return self.model.get_expert_mapping()
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/models/lfm2_moe.py", "license": "Apache License 2.0", "lines": 682, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/transformers_utils/configs/lfm2_moe.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any from transformers.configuration_utils import PretrainedConfig class Lfm2MoeConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Lfm2MoeModel`]. It is used to instantiate a LFM2 Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the LFM2-8B-A1B model. e.g. [LiquidAI/LFM2-8B-A1B](https://huggingface.co/LiquidAI/LFM2-8B-A1B) Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 65536): Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Lfm2Model`] hidden_size (`int`, *optional*, defaults to 2048): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 7168): Dimension of the MLP representations. moe_intermediate_size (`int`, *optional*, defaults to 1792): Intermediate size of the routed expert. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. pad_token_id (`int`, *optional*, defaults to 0): Padding token id. bos_token_id (`int`, *optional*, defaults to 1): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 2): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `True`): Whether to tie weight embeddings rope_parameters (`dict`, *optional*): The parameters of the RoPE embeddings. max_position_embeddings (`int`, *optional*, defaults to 128000): The maximum sequence length that this model might ever be used with. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*, defaults to 8): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`. conv_bias (`bool`, *optional*, defaults to `False`): Whether to use bias in the conv layers. conv_L_cache (`int`, *optional*, defaults to 3): L_cache dim in the conv layers. num_dense_layers (`int`, *optional*, defaults to 2): Number of dense Lfm2MoeMLP layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head). num_experts_per_tok (`int`, *optional*, defaults to 4): Number of selected experts. num_experts (`int`, *optional*, defaults to 32): Number of routed experts. use_expert_bias (`bool`, *optional*, defaults to `True`): Whether to use the expert bias on the routing weights. routed_scaling_factor (`float`, *optional*, defaults to 1.0): Scaling factor for routed experts in MoE models. norm_topk_prob (`bool`, *optional*, defaults to `True`): Whether to normalize the topk probabilities. layer_types (`Optional`, *optional*): Type of each layers. ```python >>> from transformers import Lfm2MoeModel, Lfm2MoeConfig >>> # Initializing a LFM2 Moe model >>> configuration = Lfm2MoeConfig() >>> # Initializing a model from the LFM2-8B-A1B style configuration >>> model = Lfm2MoeModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" # noqa: E501 model_type = "lfm2_moe" keys_to_ignore_at_inference = ["past_key_values"] def __init__( self, vocab_size: int = 65536, hidden_size: int = 2048, intermediate_size: int = 7168, moe_intermediate_size: int = 1792, num_hidden_layers: int = 32, pad_token_id: int = 0, bos_token_id: int = 1, eos_token_id: int = 2, tie_word_embeddings: bool = True, rope_parameters: dict[str, Any] | None = None, max_position_embeddings: int = 128_000, use_cache: bool = True, norm_eps: float = 0.00001, num_attention_heads: int = 32, num_key_value_heads: int = 8, conv_bias: bool = False, conv_L_cache: int = 3, num_dense_layers: int = 2, num_experts_per_tok: int = 4, num_experts: int = 32, use_expert_bias: bool = True, routed_scaling_factor: float = 1.0, norm_topk_prob: bool = True, layer_types: list[str] | None = None, **kwargs, ): self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers rope_theta = kwargs.pop("rope_theta", 1000000.0) if rope_parameters is None: rope_parameters = {"rope_type": "default", "rope_theta": rope_theta} self.rope_parameters = rope_parameters self.max_position_embeddings = max_position_embeddings self.use_cache = use_cache self.norm_eps = norm_eps # attn operator config self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads # custom operator config self.conv_bias = conv_bias self.conv_L_cache = conv_L_cache # moe config self.num_dense_layers = num_dense_layers self.moe_intermediate_size = moe_intermediate_size self.num_experts_per_tok = num_experts_per_tok self.num_experts = num_experts self.use_expert_bias = use_expert_bias self.routed_scaling_factor = routed_scaling_factor self.norm_topk_prob = norm_topk_prob self.layer_types = layer_types tie_word_embeddings = kwargs.get( "tie_embedding", tie_word_embeddings ) # to fit original config keys super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) __all__ = ["Lfm2MoeConfig"]
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/transformers_utils/configs/lfm2_moe.py", "license": "Apache License 2.0", "lines": 145, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/utils_/test_cache.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.utils.cache import CacheInfo, LRUCache class TestLRUCache(LRUCache): def _on_remove(self, key, value): if not hasattr(self, "_remove_counter"): self._remove_counter = 0 self._remove_counter += 1 def test_lru_cache(): cache = TestLRUCache(3) assert cache.stat() == CacheInfo(hits=0, total=0) assert cache.stat(delta=True) == CacheInfo(hits=0, total=0) cache.put(1, 1) assert len(cache) == 1 cache.put(1, 1) assert len(cache) == 1 cache.put(2, 2) assert len(cache) == 2 cache.put(3, 3) assert len(cache) == 3 assert set(cache.cache) == {1, 2, 3} cache.put(4, 4) assert len(cache) == 3 assert set(cache.cache) == {2, 3, 4} assert cache._remove_counter == 1 assert cache.get(2) == 2 assert cache.stat() == CacheInfo(hits=1, total=1) assert cache.stat(delta=True) == CacheInfo(hits=1, total=1) assert cache[2] == 2 assert cache.stat() == CacheInfo(hits=2, total=2) assert cache.stat(delta=True) == CacheInfo(hits=1, total=1) cache.put(5, 5) assert set(cache.cache) == {2, 4, 5} assert cache._remove_counter == 2 assert cache.pop(5) == 5 assert len(cache) == 2 assert set(cache.cache) == {2, 4} assert cache._remove_counter == 3 assert cache.get(-1) is None assert cache.stat() == CacheInfo(hits=2, total=3) assert cache.stat(delta=True) == CacheInfo(hits=0, total=1) cache.pop(10) assert len(cache) == 2 assert set(cache.cache) == {2, 4} assert cache._remove_counter == 3 cache.get(10) assert len(cache) == 2 assert set(cache.cache) == {2, 4} assert cache._remove_counter == 3 cache.put(6, 6) assert len(cache) == 3 assert set(cache.cache) == {2, 4, 6} assert 2 in cache assert 4 in cache assert 6 in cache cache.remove_oldest() assert len(cache) == 2 assert set(cache.cache) == {2, 6} assert cache._remove_counter == 4 cache.clear() assert len(cache) == 0 assert cache._remove_counter == 6 assert cache.stat() == CacheInfo(hits=0, total=0) assert cache.stat(delta=True) == CacheInfo(hits=0, total=0) cache._remove_counter = 0 cache[1] = 1 assert len(cache) == 1 cache[1] = 1 assert len(cache) == 1 cache[2] = 2 assert len(cache) == 2 cache[3] = 3 assert len(cache) == 3 assert set(cache.cache) == {1, 2, 3} cache[4] = 4 assert len(cache) == 3 assert set(cache.cache) == {2, 3, 4} assert cache._remove_counter == 1 assert cache[2] == 2 cache[5] = 5 assert set(cache.cache) == {2, 4, 5} assert cache._remove_counter == 2 del cache[5] assert len(cache) == 2 assert set(cache.cache) == {2, 4} assert cache._remove_counter == 3 cache.pop(10) assert len(cache) == 2 assert set(cache.cache) == {2, 4} assert cache._remove_counter == 3 cache[6] = 6 assert len(cache) == 3 assert set(cache.cache) == {2, 4, 6} assert 2 in cache assert 4 in cache assert 6 in cache
{ "repo_id": "vllm-project/vllm", "file_path": "tests/utils_/test_cache.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/utils/cache.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections import UserDict from collections.abc import Callable, Hashable, Iterator, KeysView, Mapping from types import MappingProxyType from typing import NamedTuple, TypeVar, cast, overload import cachetools _K = TypeVar("_K", bound=Hashable) _V = TypeVar("_V") _T = TypeVar("_T") class _Sentinel: ... ALL_PINNED_SENTINEL = _Sentinel() class _MappingOrderCacheView(UserDict[_K, _V]): def __init__(self, data: Mapping[_K, _V], ordered_keys: Mapping[_K, None]): super().__init__(data) self.ordered_keys = ordered_keys def __iter__(self) -> Iterator[_K]: return iter(self.ordered_keys) def keys(self) -> KeysView[_K]: return KeysView(self.ordered_keys) class CacheInfo(NamedTuple): hits: int total: int @property def hit_ratio(self) -> float: if self.total == 0: return 0 return self.hits / self.total def __sub__(self, other: "CacheInfo"): return CacheInfo( hits=self.hits - other.hits, total=self.total - other.total, ) class LRUCache(cachetools.LRUCache[_K, _V]): def __init__(self, capacity: float, getsizeof: Callable[[_V], float] | None = None): super().__init__(capacity, getsizeof) self.pinned_items = set[_K]() self._hits = 0 self._total = 0 self._last_info = CacheInfo(hits=0, total=0) def __getitem__(self, key: _K, *, update_info: bool = True) -> _V: value = super().__getitem__(key) if update_info: self._hits += 1 self._total += 1 return value def __delitem__(self, key: _K) -> None: run_on_remove = key in self value = self.__getitem__(key, update_info=False) # type: ignore[call-arg] super().__delitem__(key) if key in self.pinned_items: # Todo: add warning to inform that del pinned item self._unpin(key) if run_on_remove: self._on_remove(key, value) @property def cache(self) -> Mapping[_K, _V]: """Return the internal cache dictionary in order (read-only).""" return _MappingOrderCacheView( self._Cache__data, # type: ignore self.order, ) @property def order(self) -> Mapping[_K, None]: """Return the internal order dictionary (read-only).""" return MappingProxyType(self._LRUCache__order) # type: ignore @property def capacity(self) -> float: return self.maxsize @property def usage(self) -> float: if self.maxsize == 0: return 0 return self.currsize / self.maxsize def stat(self, *, delta: bool = False) -> CacheInfo: """ Gets the cumulative number of hits and queries against this cache. If `delta=True`, instead gets these statistics since the last call that also passed `delta=True`. """ info = CacheInfo(hits=self._hits, total=self._total) if delta: info_delta = info - self._last_info self._last_info = info info = info_delta return info def touch(self, key: _K) -> None: try: self._LRUCache__order.move_to_end(key) # type: ignore except KeyError: self._LRUCache__order[key] = None # type: ignore @overload def get(self, key: _K, /) -> _V | None: ... @overload def get(self, key: _K, /, default: _V | _T) -> _V | _T: ... def get(self, key: _K, /, default: _V | _T | None = None) -> _V | _T | None: value: _V | _T | None if key in self: value = self.__getitem__(key, update_info=False) # type: ignore[call-arg] self._hits += 1 else: value = default self._total += 1 return value @overload def pop(self, key: _K) -> _V: ... @overload def pop(self, key: _K, default: _V | _T) -> _V | _T: ... def pop(self, key: _K, default: _V | _T | None = None) -> _V | _T | None: value: _V | _T | None if key not in self: return default value = self.__getitem__(key, update_info=False) # type: ignore[call-arg] self.__delitem__(key) return value def put(self, key: _K, value: _V) -> None: self.__setitem__(key, value) def pin(self, key: _K) -> None: """ Pins a key in the cache preventing it from being evicted in the LRU order. """ if key not in self: raise ValueError(f"Cannot pin key: {key} not in cache.") self.pinned_items.add(key) def _unpin(self, key: _K) -> None: """ Unpins a key in the cache allowing it to be evicted in the LRU order. """ self.pinned_items.remove(key) def _on_remove(self, key: _K, value: _V | None) -> None: pass def remove_oldest(self, *, remove_pinned: bool = False) -> None: if len(self) == 0: return self.popitem(remove_pinned=remove_pinned) def _remove_old_if_needed(self) -> None: while self.currsize > self.capacity: self.remove_oldest() def popitem(self, remove_pinned: bool = False): """Remove and return the `(key, value)` pair least recently used.""" if not remove_pinned: # pop the oldest item in the cache that is not pinned lru_key = next( (key for key in self.order if key not in self.pinned_items), ALL_PINNED_SENTINEL, ) if lru_key is ALL_PINNED_SENTINEL: raise RuntimeError( "All items are pinned, cannot remove oldest from the cache." ) else: lru_key = next(iter(self.order)) value = self.pop(cast(_K, lru_key)) return (lru_key, value) def clear(self) -> None: while len(self) > 0: self.remove_oldest(remove_pinned=True) self._hits = 0 self._total = 0 self._last_info = CacheInfo(hits=0, total=0)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/utils/cache.py", "license": "Apache License 2.0", "lines": 162, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/layers/quantization/utils/mxfp6_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.ocp_mx_utils import OCP_MX_BLOCK_SIZE from vllm.utils.torch_utils import direct_register_custom_op def _quant_dequant_mxfp6( x: torch.Tensor, quant_dtype: str, scale_calculation_mode: str = "even", ) -> torch.Tensor: try: from quark.torch.kernel.hw_emulation.hw_emulation_interface import ( fake_quantize_fp4_fp6_per_group_with_scale, ) from quark.torch.quantization.utils import even_round, reshape_to_blocks except ImportError as err: raise ImportError( "The package `amd-quark` is required to use " "MX-FP6 models. Please install it with `pip install " "amd-quark`." ) from err axis = -1 block_x = reshape_to_blocks(x, OCP_MX_BLOCK_SIZE, axis) amax, _ = torch.max(torch.abs(block_x), dim=-1, keepdim=True) amax = amax.squeeze(-1) # TODO: there are other rounding strategies supported in quark and in the # config.json that we do not check for here! if scale_calculation_mode != "even": raise NotImplementedError( f"Scale calculation mode {scale_calculation_mode} is not yet " "supported in MX-FP6 quantization" ) scale = even_round(amax, quant_dtype) # Apply dequantize(quantize(x)). x = fake_quantize_fp4_fp6_per_group_with_scale( x, scale.to(x.device), axis=axis, group_size=OCP_MX_BLOCK_SIZE, quant_dtype=quant_dtype, ) return x def _quant_dequant_mxfp6_fake( x: torch.Tensor, quant_dtype: str, scale_calculation_mode: str = "even", ) -> torch.Tensor: return torch.empty_like(x) def _dequant_mxfp6( x: torch.Tensor, scale: torch.Tensor, float_dtype: torch.dtype, quant_dtype: str ) -> torch.Tensor: try: from quark.torch.kernel.hw_emulation.hw_emulation_interface import ( dequantize_fp4_fp6_per_group, ) from quark.torch.utils.pack import create_pack_method except ImportError as e: raise ImportError( "The package `amd-quark` is required to use " "MX-FP6 models. Please install it with `pip install " "amd-quark`." ) from e pack_method = create_pack_method(None, dtype=quant_dtype) unpacked_x = pack_method.unpack(x, reorder=False) scale = 2 ** (scale.view(torch.uint8).to(torch.int16) - 127).to(float_dtype) # TODO: `dequantize_fp4_fp6_per_group` and `prepare_inputs_per_group` # always return fp32. return dequantize_fp4_fp6_per_group( unpacked_x, scale, axis=-1, group_size=OCP_MX_BLOCK_SIZE, quant_dtype=quant_dtype, ).to(float_dtype) def _dequant_mxfp6_fake( x: torch.Tensor, scale: torch.Tensor, float_dtype: torch.dtype, quant_dtype: str ) -> torch.Tensor: assert (x.shape[-1] * 4) % 3 == 0 return torch.empty( (*x.shape[:-1], (x.shape[-1] * 4) // 3), dtype=float_dtype, device=x.device ) # Protect these operations into a torch custom op to avoid errors as # torch._dynamo.exc.Unsupported: Attempted to call function marked as skipped # Explanation: Dynamo does not know how to trace the builtin # `kernel_ext.PyCapsule.dq_uint8_mxfp4_to_half.` This function is either a # Python builtin (e.g. _warnings.warn) or a third-party C/C++ Python # extension (perhaps created with pybind). # TODO: Make sure there is no way to avoid having these functions # marked as skipped by dynamo. try: direct_register_custom_op( op_name="quant_dequant_mxfp6", op_func=_quant_dequant_mxfp6, mutates_args=[], fake_impl=_quant_dequant_mxfp6_fake, ) except AttributeError as error: raise error # Expose keyword arguments. def quant_dequant_mxfp6( x: torch.Tensor, quant_dtype: str, scale_calculation_mode: str = "even", ) -> torch.Tensor: return torch.ops.vllm.quant_dequant_mxfp6(x, quant_dtype, scale_calculation_mode) try: direct_register_custom_op( op_name="dequant_mxfp6", op_func=_dequant_mxfp6, mutates_args=[], fake_impl=_dequant_mxfp6_fake, ) except AttributeError as error: raise error def dequant_mxfp6( x: torch.Tensor, scale: torch.Tensor, float_dtype: torch.dtype, quant_dtype: str ) -> torch.Tensor: return torch.ops.vllm.dequant_mxfp6(x, scale, float_dtype, quant_dtype)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/layers/quantization/utils/mxfp6_utils.py", "license": "Apache License 2.0", "lines": 118, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/model_executor/layers/quantization/utils/ocp_mx_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from enum import Enum from vllm.logger import init_logger logger = init_logger(__name__) OCP_MX_BLOCK_SIZE = 32 OCP_MX_DTYPES = { "mxfp4", "mxfp6_e3m2", "mxfp6_e2m3", "mxfp8_e4m3", "mxfp8_e5m2", "mxint8", } SUPPORTED_OCP_MX_DTYPES = {"mxfp4", "mxfp6_e3m2", "mxfp6_e2m3"} class OCP_MX_Scheme(str, Enum): w_mxfp4 = "w_mxfp4" w_mxfp4_a_mxfp4 = "w_mxfp4_a_mxfp4" w_mxfp4_a_mxfp6_e3m2 = "w_mxfp4_a_mxfp6_e3m2" w_mxfp4_a_mxfp6_e2m3 = "w_mxfp4_a_mxfp6_e2m3" w_mxfp4_a_fp8 = "w_mxfp4_a_fp8" w_mxfp6_e3m2 = "w_mxfp6_e3m2" w_mxfp6_e3m2_a_mxfp6_e3m2 = "w_mxfp6_e3m2_a_mxfp6_e3m2" w_mxfp6_e3m2_a_fp8 = "w_mxfp6_e3m2_a_fp8" w_mxfp6_e2m3 = "w_mxfp6_e2m3" w_mxfp6_e2m3_a_mxfp6_e2m3 = "w_mxfp6_e2m3_a_mxfp6_e2m3" w_mxfp6_e2m3_a_fp8 = "w_mxfp6_e2m3_a_fp8" @classmethod def from_quant_dtype(cls, input_dtype: str | None, weight_dtype: str | None): if input_dtype not in OCP_MX_DTYPES and weight_dtype not in OCP_MX_DTYPES: return None elif input_dtype is None and weight_dtype == "mxfp4": return cls.w_mxfp4 elif input_dtype is None and weight_dtype == "mxfp6_e3m2": return cls.w_mxfp6_e3m2 elif input_dtype is None and weight_dtype == "mxfp6_e2m3": return cls.w_mxfp6_e2m3 elif input_dtype == "mxfp4" and weight_dtype == "mxfp4": return cls.w_mxfp4_a_mxfp4 elif input_dtype == "mxfp6_e3m2" and weight_dtype == "mxfp4": return cls.w_mxfp4_a_mxfp6_e3m2 elif input_dtype == "mxfp6_e2m3" and weight_dtype == "mxfp4": return cls.w_mxfp4_a_mxfp6_e2m3 elif input_dtype == "fp8" and weight_dtype == "mxfp4": return cls.w_mxfp4_a_fp8 elif input_dtype == "mxfp6_e3m2" and weight_dtype == "mxfp6_e3m2": return cls.w_mxfp6_e3m2_a_mxfp6_e3m2 elif input_dtype == "fp8" and weight_dtype == "mxfp6_e3m2": return cls.w_mxfp6_e3m2_a_fp8 elif input_dtype == "mxfp6_e2m3" and weight_dtype == "mxfp6_e2m3": return cls.w_mxfp6_e2m3_a_mxfp6_e2m3 elif input_dtype == "fp8" and weight_dtype == "mxfp6_e2m3": return cls.w_mxfp6_e2m3_a_fp8 else: logger.warning( "input_dtype='%s' and" " weight_dtype='%s' is not supported " "in OCP_MX_Scheme at the moment.", input_dtype, weight_dtype, ) return None
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/model_executor/layers/quantization/utils/ocp_mx_utils.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm: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 from vllm.utils.torch_utils import set_random_seed # 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, clean_logits: bool, 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) if clean_logits: 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.parametrize("clean_logits", [True, False]) @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, clean_logits: bool, ) -> None: """ Test top_k_per_row. """ set_random_seed(0) 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, clean_logits, "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 = torch.empty((num_rows, top_k), dtype=torch.int32, device="cuda") for i in range(num_rows): row_end = int(row_ends[i]) k_i = min(top_k, row_end) idx = logits[i, :row_end].topk(k_i, dim=-1)[1] torch_indices[i, :k_i] = idx # 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, clean_logits: bool, 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( low=next_n, high=vocab_size, 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, clean_logits, 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 = torch.empty((num_rows, top_k), dtype=torch.int32, device="cuda") for i in range(num_rows): row_end = int(row_ends[i]) k_i = min(top_k, row_end) idx = logits[i, :row_end].topk(k_i, dim=-1)[1] torch_indices[i, :k_i] = idx # 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("clean_logits", [True, False]) @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, clean_logits: bool, data_generation: str, ) -> None: """ Test top_k_per_row with seq_lens tensor. """ set_random_seed(0) vocab_size = 20000 _run_top_k_per_row_decode_test( top_k, batch_size, next_n, vocab_size, clean_logits, data_generation ) @pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA") @pytest.mark.parametrize("clean_logits", [True, False]) @torch.inference_mode() def test_top_k_per_row_decode_large_vocab_size(clean_logits: bool) -> None: """ Test top_k_per_row_decode with large vocabulary size. """ set_random_seed(0) 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, clean_logits, data_generation ) @pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA") @pytest.mark.parametrize("clean_logits", [True, False]) @torch.inference_mode() def test_deepseek_hybrid_topk(clean_logits: bool) -> None: torch.set_default_device("cuda:0") top_k = 2048 # Test case 1: Short sequences (< 8192) batch_size_short = 4 next_n = 1 num_rows_short = batch_size_short * next_n # Create sequences with max length < 8192 seq_lens_short = torch.randint( 4000, 8000, (batch_size_short,), dtype=torch.int32, device="cuda" ) row_starts_short = torch.zeros(num_rows_short, dtype=torch.int32, device="cuda") row_indices_short = torch.arange(num_rows_short, device="cuda") // next_n next_n_offset_short = torch.arange(num_rows_short, device="cuda") % next_n row_ends_short = ( seq_lens_short[row_indices_short] - next_n + next_n_offset_short + 1 ) logits_short = create_random_logits( row_starts_short, row_ends_short, torch.float32, 42, clean_logits, "random" ) indices_vllm = torch.empty( (num_rows_short, top_k), dtype=torch.int32, device="cuda" ) # Use vllm's kernel for short sequences torch.ops._C.top_k_per_row_decode( logits_short, next_n, seq_lens_short, indices_vllm, num_rows_short, logits_short.stride(0), logits_short.stride(1), top_k, ) # Test case 2: Long sequences (>= 8192) - should use large_context_topk kernel batch_size_long = 4 num_rows_long = batch_size_long * next_n # Create sequences with max length >= 8192 seq_lens_long = torch.randint( 8192, 16384, (batch_size_long,), dtype=torch.int32, device="cuda" ) row_starts_long = torch.zeros(num_rows_long, dtype=torch.int32, device="cuda") row_indices_long = torch.arange(num_rows_long, device="cuda") // next_n next_n_offset_long = torch.arange(num_rows_long, device="cuda") % next_n row_ends_long = seq_lens_long[row_indices_long] - next_n + next_n_offset_long + 1 logits_long = create_random_logits( row_starts_long, row_ends_long, torch.float32, 43, clean_logits, "random" ) indices = torch.empty((num_rows_long, top_k), dtype=torch.int32, device="cuda") # Use large_context_topk kernel for long sequences if next_n == 1: lengths = seq_lens_long else: offsets = torch.arange(next_n, device=logits_long.device, dtype=torch.int32) lengths = (seq_lens_long.unsqueeze(1) - next_n + 1 + offsets).flatten() torch.ops._C.large_context_topk( logits_long, indices, lengths, None, ) torch_indices_short = torch.empty( (num_rows_short, top_k), dtype=torch.int32, device="cuda" ) for i in range(num_rows_short): row_end = int(row_ends_short[i]) k_i = min(top_k, row_end) idx = logits_short[i, :row_end].topk(k_i, dim=-1)[1] torch_indices_short[i, :k_i] = idx assert compare_top_k_results( logits_short, indices_vllm, torch_indices_short, row_starts_short, row_ends_short, top_k, ), "top_k_per_row_decode kernel (short sequences) doesn't match torch.topk" torch_indices_long = torch.empty( (num_rows_long, top_k), dtype=torch.int32, device="cuda" ) for i in range(num_rows_long): row_end = int(row_ends_long[i]) k_i = min(top_k, row_end) idx = logits_long[i, :row_end].topk(k_i, dim=-1)[1] torch_indices_long[i, :k_i] = idx assert compare_top_k_results( logits_long, indices, torch_indices_long, row_starts_long, row_ends_long, top_k ), "large_context_topk kernel (long sequences) doesn't match torch.topk"
{ "repo_id": "vllm-project/vllm", "file_path": "tests/kernels/test_top_k_per_row.py", "license": "Apache License 2.0", "lines": 332, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/v1/worker/dp_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import numpy as np import torch import torch.distributed as dist from vllm.config import ParallelConfig from vllm.distributed.parallel_state import get_dp_group from vllm.logger import init_logger from vllm.v1.worker.ubatch_utils import ( check_ubatch_thresholds, is_last_ubatch_empty, ) logger = init_logger(__name__) def _get_device_and_group(parallel_config: ParallelConfig): # Use the actual device assigned to the DP group, not just the device type device = get_dp_group().device group = get_dp_group().device_group # Transferring this tensor from GPU to CPU will introduce a GPU sync # point that could adversely affect performance of vllm with asynch # scheduling. This environment variable exists to quickly disable # this optimization if we run into this case. if parallel_config.disable_nccl_for_dp_synchronization: logger.info_once( "Using CPU all reduce to synchronize DP padding between ranks." ) device = "cpu" group = get_dp_group().cpu_group return device, group def _run_ar( should_ubatch: bool, orig_num_tokens_per_ubatch: int, padded_num_tokens_per_ubatch: int, cudagraph_mode: int, parallel_config: ParallelConfig, ) -> torch.Tensor: dp_size = parallel_config.data_parallel_size dp_rank = parallel_config.data_parallel_rank device, group = _get_device_and_group(parallel_config) tensor = torch.zeros(4, dp_size, device=device, dtype=torch.int32) tensor[0][dp_rank] = orig_num_tokens_per_ubatch tensor[1][dp_rank] = padded_num_tokens_per_ubatch tensor[2][dp_rank] = 1 if should_ubatch else 0 tensor[3][dp_rank] = cudagraph_mode dist.all_reduce(tensor, group=group) return tensor def _post_process_ubatch(tensor: torch.Tensor, num_ubatches: int) -> bool: orig_num_tokens_tensor = tensor[0, :] padded_num_tokens_tensor = tensor[1, :] # First determine if we are going to be ubatching. should_ubatch: bool = bool(torch.all(tensor[2] == 1).item()) if not should_ubatch: return False # If the DP ranks are planning to ubatch, make sure that # there are no "empty" second ubatches orig_min_num_tokens = int(orig_num_tokens_tensor.min().item()) padded_max_num_tokens = int(padded_num_tokens_tensor.max().item()) if is_last_ubatch_empty(orig_min_num_tokens, padded_max_num_tokens, num_ubatches): logger.debug( "Aborting ubatching %s %s", orig_min_num_tokens, padded_max_num_tokens ) should_ubatch = False return should_ubatch def _post_process_dp_padding(tensor: torch.Tensor, should_dp_pad: bool) -> torch.Tensor: num_tokens_across_dp = tensor[1, :] if should_dp_pad: # If DP padding is enabled, ensure that each rank is processing the same number # of tokens max_num_tokens = int(num_tokens_across_dp.max().item()) return torch.tensor( [max_num_tokens] * len(num_tokens_across_dp), device="cpu", dtype=torch.int32, ) else: return num_tokens_across_dp.cpu() def _post_process_cudagraph_mode(tensor: torch.Tensor) -> int: """ Synchronize cudagraph_mode across DP ranks by taking the minimum. If any rank has NONE (0), all ranks use NONE. This ensures all ranks send consistent values (all padded or all unpadded). """ return int(tensor[3, :].min().item()) def _synchronize_dp_ranks( num_tokens_unpadded: int, num_tokens_padded: int, should_attempt_ubatching: bool, cudagraph_mode: int, parallel_config: ParallelConfig, ) -> tuple[bool, torch.Tensor | None, int]: """ 1. Decides if each DP rank is going to microbatch. Either all ranks run with microbatching or none of them do. 2. Determines the total number of tokens that each rank will run. When running microbatched or if cudagraph is enabled (synced across ranks), all ranks will be padded out so that they run with the same number of tokens. 3. Synchronizes cudagraph_mode across ranks by taking the minimum. Returns: tuple[ should_ubatch: Are all DP ranks going to microbatch num_tokens_after_padding: A tensor containing the total number of tokens per-microbatch for each DP rank including any DP padding. synced_cudagraph_mode: The synchronized cudagraph mode (min across ranks) ] """ assert num_tokens_padded >= num_tokens_unpadded # Coordinate between the DP ranks via an All Reduce # to determine the total number of tokens that each rank # will run and if we are using ubatching or not. tensor = _run_ar( should_ubatch=should_attempt_ubatching, orig_num_tokens_per_ubatch=num_tokens_unpadded, padded_num_tokens_per_ubatch=num_tokens_padded, cudagraph_mode=cudagraph_mode, parallel_config=parallel_config, ) # Synchronize cudagraph_mode across ranks first (take min). # This is needed before DP padding decision since we use the synced # cudagraph mode to determine whether DP padding is needed. synced_cudagraph_mode = _post_process_cudagraph_mode(tensor) # Check conditions for microbatching should_ubatch = _post_process_ubatch(tensor, parallel_config.num_ubatches) # DP padding is needed when cudagraph is enabled (synced across ranks) # or when ubatching/DBO is active (ubatching requires uniform batch # sizes across DP ranks currently). # Use the synced runtime cudagraph mode rather than the compilation config # so we can avoid padding when cudagraph is not enabled for this step. should_dp_pad = synced_cudagraph_mode != 0 or should_ubatch # Pad all DP ranks up to the maximum token count across ranks if # should_dp_pad is True num_tokens_after_padding = _post_process_dp_padding( tensor, should_dp_pad, ) return should_ubatch, num_tokens_after_padding, synced_cudagraph_mode def coordinate_batch_across_dp( num_tokens_unpadded: int, allow_microbatching: bool, parallel_config: ParallelConfig, num_tokens_padded: int | None = None, uniform_decode: bool | None = None, num_scheduled_tokens_per_request: np.ndarray | None = None, cudagraph_mode: int = 0, ) -> tuple[bool, torch.Tensor | None, int]: """ Coordinates amongst all DP ranks to determine if and how the full batch should be split into microbatches. Args: num_tokens_unpadded: Number of tokens without accounting for padding allow_microbatching: If microbatching should be attempted parallel_config: The parallel config num_tokens_padded: Number of tokens including any non-DP padding (CUDA graphs, TP, etc) uniform_decode: Only used if allow_microbatching is True. True if the batch only contains single token decodes num_scheduled_tokens_per_request: Only used if allow_microbatching is True. The number of tokens per request. cudagraph_mode: The cudagraph mode for this rank (0=NONE, 1=PIECEWISE, 2=FULL). DP padding is enabled when synced cudagraph mode across ranks is not NONE. Returns: tuple[ ubatch_slices: if this is set then all DP ranks have agreed to microbatch num_tokens_after_padding: A tensor containing the total number of tokens per-microbatch for each DP rank including padding. Will be padded up to the max value across all DP ranks when cudagraph is enabled. synced_cudagraph_mode: The synchronized cudagraph mode (min across ranks) ] """ if parallel_config.data_parallel_size == 1: # Early exit. return False, None, cudagraph_mode # If the caller has explicitly enabled microbatching. should_attempt_ubatching = False if allow_microbatching: # Check preconditions for microbatching assert uniform_decode is not None should_attempt_ubatching = check_ubatch_thresholds( parallel_config, num_tokens_unpadded, uniform_decode=uniform_decode, ) if num_tokens_padded is None: num_tokens_padded = num_tokens_unpadded (should_ubatch, num_tokens_after_padding, synced_cudagraph_mode) = ( _synchronize_dp_ranks( num_tokens_unpadded, num_tokens_padded, should_attempt_ubatching, cudagraph_mode, parallel_config, ) ) return (should_ubatch, num_tokens_after_padding, synced_cudagraph_mode)
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/v1/worker/dp_utils.py", "license": "Apache License 2.0", "lines": 191, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:vllm/v1/attention/backends/rocm_aiter_unified_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with PagedAttention and Triton prefix prefill.""" import torch from vllm import _custom_ops as ops from vllm._aiter_ops import rocm_aiter_ops from vllm.logger import init_logger from vllm.model_executor.layers.quantization.utils.quant_utils import ( QuantKey, kFp8StaticTensorSym, ) from vllm.v1.attention.backend import AttentionLayer, AttentionType from vllm.v1.attention.backends.flash_attn import FlashAttentionMetadata from vllm.v1.attention.backends.rocm_attn import ( RocmAttentionBackend, RocmAttentionImpl, RocmAttentionMetadataBuilder, ) logger = init_logger(__name__) class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend): accept_output_buffer: bool = True forward_includes_kv_cache_update: bool = False @staticmethod def get_name() -> str: return "ROCM_AITER_UNIFIED_ATTN" @staticmethod def get_impl_cls() -> type["RocmAiterUnifiedAttentionImpl"]: return RocmAiterUnifiedAttentionImpl @staticmethod def get_kv_cache_shape( num_blocks: int, block_size: int, num_kv_heads: int, head_size: int, cache_dtype_str: str = "auto", ) -> tuple[int, ...]: if block_size % 16 != 0: raise ValueError("Block size must be a multiple of 16.") return (2, num_blocks, block_size, num_kv_heads, head_size) @staticmethod def use_cascade_attention(*args, **kwargs) -> bool: return False @staticmethod def get_builder_cls() -> type["RocmAttentionMetadataBuilder"]: return RocmAttentionMetadataBuilder @classmethod def supports_attn_type(cls, attn_type: str) -> bool: """RocmAiterUnifiedAttention supports all attention types.""" return attn_type in ( AttentionType.DECODER, AttentionType.ENCODER, AttentionType.ENCODER_ONLY, AttentionType.ENCODER_DECODER, ) class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl): def fused_output_quant_supported(self, quant_key: QuantKey): return quant_key == kFp8StaticTensorSym def __init__( self, num_heads: int, head_size: int, scale: float, num_kv_heads: int, alibi_slopes: list[float] | None, sliding_window: int | None, kv_cache_dtype: str, logits_soft_cap: float | None = None, attn_type: AttentionType = AttentionType.DECODER, kv_sharing_target_layer_name: int | None = None, sinks: torch.Tensor | None = None, ) -> None: super().__init__( num_heads, head_size, scale, num_kv_heads, alibi_slopes, sliding_window, kv_cache_dtype, logits_soft_cap, attn_type, kv_sharing_target_layer_name, sinks, ) logger.info_once( "Using aiter unified attention for RocmAiterUnifiedAttentionImpl" ) from aiter.ops.triton.unified_attention import unified_attention self.unified_attention = unified_attention def forward( self, layer: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, attn_metadata: FlashAttentionMetadata, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Forward pass with FlashAttention. Args: query: shape = [num_tokens, num_heads, head_size] key: shape = [num_tokens, num_kv_heads, head_size] value: shape = [num_tokens, num_kv_heads, head_size] kv_cache: shape = [2, num_blocks, block_size, num_kv_heads, head_size] attn_metadata: Metadata for attention. Returns: shape = [num_tokens, num_heads * head_size] """ assert output is not None, "Output tensor must be provided." if output_block_scale is not None: raise NotImplementedError( "fused block_scale output quantization is not yet supported" " for RocmAttentionImpl" ) if attn_metadata is None: # Profiling run. return output.fill_(0) assert attn_metadata.use_cascade is False # IMPORTANT! # NOTE(woosuk): With piece-wise CUDA graphs, this method is executed in # eager-mode PyTorch. Thus, we need to be careful about any CPU overhead # in this method. For example, `view` and `slice` (or `[:n]`) operations # are surprisingly slow even in the case they do not invoke any GPU ops. # Minimize the PyTorch ops in this method as much as possible. # Whenever making a change in this method, please benchmark the # performance to make sure it does not introduce any overhead. num_actual_tokens = attn_metadata.num_actual_tokens # Handle encoder attention differently - no KV cache needed if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER): # For encoder attention, # we use direct Q, K, V tensors without caching return self._forward_encoder_attention( query[:num_actual_tokens], key[:num_actual_tokens], value[:num_actual_tokens], output[:num_actual_tokens], attn_metadata, layer, ) key_cache, value_cache = kv_cache.unbind(0) if self.kv_cache_dtype.startswith("fp8"): key_cache = key_cache.view(self.fp8_dtype) value_cache = value_cache.view(self.fp8_dtype) assert layer._q_scale_float == 1.0, ( "A non 1.0 q_scale is not currently supported." ) cu_seqlens_q = attn_metadata.query_start_loc seqused_k = attn_metadata.seq_lens max_seqlen_q = attn_metadata.max_query_len max_seqlen_k = attn_metadata.max_seq_len block_table = attn_metadata.block_table descale_shape = ( cu_seqlens_q.shape[0] - 1, key.shape[1] if key is not None else self.num_kv_heads, ) self.unified_attention( q=query[:num_actual_tokens], k=key_cache, v=value_cache, out=output[:num_actual_tokens], cu_seqlens_q=cu_seqlens_q, max_seqlen_q=max_seqlen_q, seqused_k=seqused_k, max_seqlen_k=max_seqlen_k, softmax_scale=self.scale, causal=True, alibi_slopes=self.alibi_slopes, window_size=self.sliding_window, block_table=block_table, softcap=self.logits_soft_cap, q_descale=None, # Not supported k_descale=layer._k_scale.expand(descale_shape), v_descale=layer._v_scale.expand(descale_shape), sinks=self.sinks, output_scale=output_scale, ) return output def do_kv_cache_update( self, layer: AttentionLayer, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, slot_mapping: torch.Tensor, ): if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER): # For encoder attention, # we use direct Q, K, V tensors without caching return key_cache, value_cache = kv_cache.unbind(0) # Reshape the input keys and values and store them in the cache. ops.reshape_and_cache_flash( key, value, key_cache, value_cache, slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) def fused_rope_kvcache_supported(self): return rocm_aiter_ops.is_enabled() def do_rope_and_kv_cache_update( self, layer: AttentionLayer, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, positions: torch.Tensor, cos_sin_cache: torch.Tensor, is_neox: bool, kv_cache: torch.Tensor, layer_slot_mapping: torch.Tensor, ): if self.attn_type in (AttentionType.ENCODER_ONLY, AttentionType.ENCODER): # For encoder attention, # we use direct Q, K, V tensors without caching return key_cache, value_cache = kv_cache.unbind(0) flash_layout = True is_fp8_kv_cache = self.kv_cache_dtype.startswith("fp8") if is_fp8_kv_cache: key_cache = key_cache.view(self.fp8_dtype) value_cache = value_cache.view(self.fp8_dtype) rocm_aiter_ops.triton_rope_and_cache( query, key, value, positions, cos_sin_cache, is_neox, key_cache, value_cache, layer_slot_mapping, layer._k_scale, layer._v_scale, flash_layout, is_fp8_kv_cache, )
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/v1/attention/backends/rocm_aiter_unified_attn.py", "license": "Apache License 2.0", "lines": 244, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/v1/metrics/test_stats.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.v1.engine import FinishReason from vllm.v1.metrics.stats import IterationStats, PromptTokenStats, RequestStateStats def test_iteration_stats_repr(): iteration_stats = IterationStats() assert repr(iteration_stats).startswith("IterationStats(") def test_prefill_kv_computed_with_cache(): """Test that prefill KV compute correctly excludes cached tokens.""" iteration_stats = IterationStats() req_stats = RequestStateStats(arrival_time=0.0) req_stats.scheduled_ts = 0.1 req_stats.first_token_ts = 0.5 req_stats.last_token_ts = 5.0 req_stats.num_generation_tokens = 50 # Case 1: With prefix cache (1200 tokens cached) iteration_stats.update_from_finished_request( finish_reason=FinishReason.STOP, num_prompt_tokens=10000, max_tokens_param=100, req_stats=req_stats, num_cached_tokens=1200, ) finished_req = iteration_stats.finished_requests[0] assert finished_req.num_prompt_tokens == 10000 assert finished_req.num_cached_tokens == 1200 # Verify calculation: prefill KV = prompt tokens - cached tokens prefill_kv_computed = finished_req.num_prompt_tokens - max( finished_req.num_cached_tokens, 0 ) assert prefill_kv_computed == 8800 # 10000 - 1200 def test_prefill_kv_computed_no_cache(): """Test prefill KV compute without prefix caching.""" iteration_stats = IterationStats() req_stats = RequestStateStats(arrival_time=0.0) req_stats.scheduled_ts = 0.1 req_stats.first_token_ts = 0.5 req_stats.last_token_ts = 2.0 req_stats.num_generation_tokens = 10 # Case 2: No prefix cache iteration_stats.update_from_finished_request( finish_reason=FinishReason.STOP, num_prompt_tokens=2000, max_tokens_param=100, req_stats=req_stats, num_cached_tokens=0, ) finished_req = iteration_stats.finished_requests[0] assert finished_req.num_prompt_tokens == 2000 assert finished_req.num_cached_tokens == 0 # Verify calculation: prefill KV = full prompt when no cache prefill_kv_computed = finished_req.num_prompt_tokens - max( finished_req.num_cached_tokens, 0 ) assert prefill_kv_computed == 2000 def test_prefill_kv_computed_edge_cases(): """Test edge cases for prefill KV compute calculation.""" iteration_stats = IterationStats() req_stats = RequestStateStats(arrival_time=0.0) req_stats.scheduled_ts = 0.1 req_stats.first_token_ts = 0.5 req_stats.last_token_ts = 1.0 req_stats.num_generation_tokens = 1 # Case 3: Negative num_cached_tokens (shouldn't happen, but handle gracefully) iteration_stats.update_from_finished_request( finish_reason=FinishReason.STOP, num_prompt_tokens=100, max_tokens_param=10, req_stats=req_stats, num_cached_tokens=-1, ) finished_req = iteration_stats.finished_requests[0] # max() should handle negative values prefill_kv_computed = finished_req.num_prompt_tokens - max( finished_req.num_cached_tokens, 0 ) assert prefill_kv_computed == 100 # Should treat negative as 0 # Case 4: All tokens cached (shouldn't happen in practice) iteration_stats2 = IterationStats() iteration_stats2.update_from_finished_request( finish_reason=FinishReason.STOP, num_prompt_tokens=100, max_tokens_param=10, req_stats=req_stats, num_cached_tokens=100, ) finished_req2 = iteration_stats2.finished_requests[0] prefill_kv_computed2 = finished_req2.num_prompt_tokens - max( finished_req2.num_cached_tokens, 0 ) assert prefill_kv_computed2 == 0 # All cached, nothing computed def test_prompt_token_stats_all_computed(): """Test all tokens computed locally, no caching.""" stats = PromptTokenStats() # Case 1: No caching (All tokens computed locally) stats.update_from_output( num_cached_tokens=0, num_external_computed_tokens=0, prompt_len=1000, ) assert stats.computed == 1000 assert stats.local_cache_hit == 0 assert stats.external_kv_transfer == 0 assert stats.total == 1000 def test_prompt_token_stats_partial_local_cache(): """Test partial local prefix cache hit.""" stats = PromptTokenStats() # Case 2: Partial local cache stats.update_from_output( num_cached_tokens=300, num_external_computed_tokens=0, prompt_len=1000, ) assert stats.computed == 700 assert stats.local_cache_hit == 300 assert stats.external_kv_transfer == 0 def test_prompt_token_stats_partial_external_transfer(): """Test partial external KV transfer.""" stats = PromptTokenStats() # Case 3: Partial external transfer stats.update_from_output( num_cached_tokens=500, num_external_computed_tokens=500, prompt_len=1000, ) assert stats.computed == 500 assert stats.local_cache_hit == 0 assert stats.external_kv_transfer == 500 def test_prompt_token_stats_mixed_sources(): """Test mix of local cache and external transfer.""" stats = PromptTokenStats() # Case 4: Mixed sources stats.update_from_output( num_cached_tokens=600, num_external_computed_tokens=200, prompt_len=1000, ) assert stats.computed == 400 assert stats.local_cache_hit == 400 assert stats.external_kv_transfer == 200 def test_prompt_token_stats_full_local_cache_recompute(): """Test full local cache triggers last token recomputation. When all tokens are cached, the scheduler reduces num_cached_tokens by 1 to force the model to recompute the last token. """ stats = PromptTokenStats() # Case 5: Full local cache (999 cached after reduction, 1 recomputed) stats.update_from_output( num_cached_tokens=999, num_external_computed_tokens=0, prompt_len=1000, ) assert stats.computed == 1 assert stats.local_cache_hit == 1000 assert stats.recomputed_tokens == 1 def test_prompt_token_stats_full_external_transfer_recompute(): """Test full external transfer triggers last token recomputation.""" stats = PromptTokenStats() # Case 6: Full external transfer (999 cached after reduction, 1 recomputed) stats.update_from_output( num_cached_tokens=999, num_external_computed_tokens=1000, prompt_len=1000, ) assert stats.computed == 1 assert stats.local_cache_hit == 0 assert stats.external_kv_transfer == 1000 assert stats.recomputed_tokens == 1
{ "repo_id": "vllm-project/vllm", "file_path": "tests/v1/metrics/test_stats.py", "license": "Apache License 2.0", "lines": 168, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/models/multimodal/pooling/test_clip.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from transformers import CLIPModel from ....conftest import IMAGE_ASSETS, HfRunner, PromptImageInput, VllmRunner from ...utils import check_embeddings_close HF_TEXT_PROMPTS = [ "a photo of a stop sign", "a photo of a cherry blossom", ] HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts( { "stop_sign": "", "cherry_blossom": "", } ) MODELS = ["openai/clip-vit-base-patch32"] def _run_test( hf_runner: type[HfRunner], vllm_runner: type[VllmRunner], input_texts: list[str], input_images: PromptImageInput, model: str, *, dtype: str, ) -> None: # NOTE: take care of the order. run vLLM first, and then run HF. # vLLM needs a fresh new process without cuda initialization. # if we run HF first, the cuda initialization will be done and it # will hurt multiprocessing backend with fork method (the default method). with vllm_runner( model, runner="pooling", dtype=dtype, enforce_eager=True, max_model_len=77 ) as vllm_model: vllm_outputs = vllm_model.embed(input_texts, images=input_images) with hf_runner(model, dtype=dtype, auto_cls=CLIPModel) as hf_model: all_inputs = hf_model.get_inputs(input_texts, images=input_images) all_outputs = [] for inputs in all_inputs: inputs = hf_model.wrap_device(inputs) if "pixel_values" in inputs: pooled_output = hf_model.model.get_image_features( pixel_values=inputs.pixel_values, ).squeeze(0) else: pooled_output = hf_model.model.get_text_features( input_ids=inputs.input_ids, attention_mask=inputs.attention_mask, ).squeeze(0) all_outputs.append(pooled_output.tolist()) hf_outputs = all_outputs check_embeddings_close( embeddings_0_lst=hf_outputs, embeddings_1_lst=vllm_outputs, name_0="hf", name_1="vllm", ) @pytest.mark.parametrize("model", MODELS) @pytest.mark.parametrize("dtype", ["float"]) def test_models_text( hf_runner, vllm_runner, image_assets, model: str, dtype: str, ) -> None: input_texts_images = [(text, None) for text in HF_TEXT_PROMPTS] input_texts = [text for text, _ in input_texts_images] input_images = [image for _, image in input_texts_images] _run_test( hf_runner, vllm_runner, input_texts, input_images, # type: ignore model, dtype=dtype, ) @pytest.mark.parametrize("model", MODELS) @pytest.mark.parametrize("dtype", ["float"]) def test_models_image( hf_runner, vllm_runner, image_assets, model: str, dtype: str, ) -> None: input_texts_images = [ (text, asset.pil_image) for text, asset in zip(HF_IMAGE_PROMPTS, image_assets) ] input_texts = [text for text, _ in input_texts_images] input_images = [image for _, image in input_texts_images] _run_test( hf_runner, vllm_runner, input_texts, input_images, model, dtype=dtype, ) @pytest.mark.parametrize("model", MODELS) @pytest.mark.parametrize("dtype", ["float"]) def test_models_text_image_no_crash( vllm_runner, image_assets, model: str, dtype: str, ) -> None: texts = [HF_TEXT_PROMPTS[0]] images = [image_assets[0].pil_image] with vllm_runner( model, runner="pooling", dtype=dtype, enforce_eager=True, max_model_len=77 ) as vllm_model: with pytest.raises(ValueError, match="not both"): vllm_model.embed(texts, images=images) # Should still be able to run subsequent requests vllm_model.embed(texts) vllm_model.embed([""], images=images)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/models/multimodal/pooling/test_clip.py", "license": "Apache License 2.0", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:tests/reasoning/test_olmo3_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from transformers import AutoTokenizer from tests.reasoning.utils import run_reasoning_extraction from vllm.reasoning import ReasoningParser, ReasoningParserManager parser_name = "olmo3" START_REASONING = "<think>" END_REASONING = "</think>" NO_REASONING = { "output": f"{START_REASONING}{END_REASONING}No thoughts, head empty!", "reasoning": None, "content": "No thoughts, head empty!", } NO_REASONING_WITH_NEWLINE = { "output": f"{START_REASONING}\n{END_REASONING}\n\nNo thoughts, head empty!", "reasoning": "\n", "content": "\n\nNo thoughts, head empty!", } SIMPLE_REASONING = { "output": f"{START_REASONING}This is a reasoning section{END_REASONING}This is the rest", # noqa: E501 "reasoning": "This is a reasoning section", "content": "This is the rest", } SIMPLE_REASONING_WITH_NEWLINE = { "output": f"{START_REASONING} Look!\n\nI'm thinking...{END_REASONING}\nThis is the rest", # noqa: E501 "reasoning": " Look!\n\nI'm thinking...", "content": "\nThis is the rest", } SIMPLE_REASONING_WITH_MULTIPLE_NEWLINES = { "output": f"{START_REASONING}\nLook!\nI'm thinking...\n\n{END_REASONING}\n\n\nThis is the rest", # noqa: E501 "reasoning": "\nLook!\nI'm thinking...\n\n", "content": "\n\n\nThis is the rest", } NO_REASONING_ONLY_END_THINK = { "output": f"{END_REASONING}\n\nNo thoughts, head empty!", "reasoning": None, "content": "\n\nNo thoughts, head empty!", } REASONING_ONLY_END_THINK = { "output": f"The user is asking me not to think.{END_REASONING}No thoughts!", "reasoning": "The user is asking me not to think.", "content": "No thoughts!", } TEST_CASES = [ pytest.param( False, # not streaming NO_REASONING, id="no_reasoning", ), pytest.param( False, # not streaming NO_REASONING_WITH_NEWLINE, id="no_reasoning_with_newline", ), pytest.param( False, # not streaming SIMPLE_REASONING, id="simple_reasoning", ), pytest.param( False, # not streaming SIMPLE_REASONING_WITH_NEWLINE, id="simple_reasoning_with_newline", ), pytest.param( True, # enable streaming SIMPLE_REASONING_WITH_MULTIPLE_NEWLINES, id="simple_reasoning_with_multiple_newlines", ), pytest.param( False, # not streaming NO_REASONING_ONLY_END_THINK, id="no_reasoning_only_end_think", ), pytest.param( False, # not streaming REASONING_ONLY_END_THINK, id="yes_reasoning_only_end_think", ), pytest.param( True, # enable streaming NO_REASONING, id="no_reasoning_streaming", ), pytest.param( True, # enable streaming NO_REASONING_WITH_NEWLINE, id="no_reasoning_with_newline_streaming", ), pytest.param( True, # enable streaming SIMPLE_REASONING, id="simple_reasoning_streaming", ), pytest.param( True, # enable streaming SIMPLE_REASONING_WITH_NEWLINE, id="simple_reasoning_with_newline_streaming", ), pytest.param( True, # enable streaming SIMPLE_REASONING_WITH_MULTIPLE_NEWLINES, id="simple_reasoning_with_multiple_newlines_streaming", ), pytest.param( True, # enable streaming NO_REASONING_ONLY_END_THINK, id="no_reasoning_only_end_think_streaming", ), pytest.param( True, # enable streaming REASONING_ONLY_END_THINK, id="yes_reasoning_only_end_think_streaming", ), ] # Global tokenizer initialization to avoid repeated loading tokenizer = AutoTokenizer.from_pretrained("allenai/dolma2-tokenizer") @pytest.mark.parametrize("streaming, param_dict", TEST_CASES) def test_reasoning( streaming: bool, param_dict: dict[str, str], ): output = tokenizer.tokenize(param_dict["output"]) # decode everything to tokens model_output: list[str] = [ tokenizer.convert_tokens_to_string([token]) for token in output ] parser_cls = ReasoningParserManager.get_reasoning_parser(parser_name) parser: ReasoningParser = parser_cls(tokenizer) reasoning, content = run_reasoning_extraction( reasoning_parser=parser, model_output=model_output, streaming=streaming ) assert reasoning == param_dict["reasoning"] assert content == param_dict["content"]
{ "repo_id": "vllm-project/vllm", "file_path": "tests/reasoning/test_olmo3_reasoning_parser.py", "license": "Apache License 2.0", "lines": 135, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:vllm/reasoning/olmo3_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import dataclasses as dt import enum from collections.abc import Sequence from typing import TYPE_CHECKING import regex as re if TYPE_CHECKING: from vllm.tokenizers import TokenizerLike from vllm.entrypoints.openai.chat_completion.protocol import ( ChatCompletionRequest, ) from vllm.entrypoints.openai.engine.protocol import ( DeltaMessage, ) from vllm.entrypoints.openai.responses.protocol import ( ResponsesRequest, ) from vllm.logger import init_logger from vllm.reasoning import ReasoningParser logger = init_logger(__name__) class Olmo3ReasoningState(enum.Enum): REASONING = 1 CONTENT = 2 @dt.dataclass(frozen=True) class Indices: start: int end: int def __len__(self): return self.end - self.start def string_overlap(a: str, b: str) -> tuple[Indices | None, Indices | None]: """ Find the longest overlap where the end of string a matches the start of string b. Args: a: First string b: Second string Returns: Tuple of IndicesTuples representing the overlapping portions in each string, or a tuple of None if no overlap exists """ # swap so a is always the shorter string a, b, swap = (a, b, False) if len(a) < len(b) else (b, a, True) # first check: is a fully contained in b? if a in b: ind_a = Indices(0, len(a)) ind_b = Indices(b.index(a), b.index(a) + len(a)) return (ind_b, ind_a) if swap else (ind_a, ind_b) # second check: does the end of a overlap with the # beginning of b? for i in range(len(a) - 1, 0, -1): if a[-i:] == b[:i]: ind_a = Indices(len(a) - i, len(a)) ind_b = Indices(0, i) return (ind_b, ind_a) if swap else (ind_a, ind_b) # third check: does the beginning of a overlap with # the end of b? for i in range(len(a) - 1, 0, -1): if b[-i:] == a[:i]: ind_a = Indices(0, i) ind_b = Indices(len(b) - i, len(b)) return (ind_b, ind_a) if swap else (ind_a, ind_b) return None, None @dt.dataclass class Olmo3ReasoningBuffer: think_start: str = "<think>" think_end: str = "</think>" buffer: str = "" # we start in reasoning state to support cases where we hardcode # <think> as the start of the reasoning block. # In those cases, the only token we will see is </think>, which # is when we switch to content state. state: Olmo3ReasoningState = Olmo3ReasoningState.REASONING def process_buffer(self) -> DeltaMessage | None: start_think_idx = self.buffer.find(self.think_start) if start_think_idx >= 0: self.state = Olmo3ReasoningState.REASONING pretext, self.buffer = ( self.buffer[:start_think_idx], self.buffer[start_think_idx + len(self.think_start) :], ) if start_think_idx > 0: # this covers the case there's content before # the start of the reasoning block return DeltaMessage(content=pretext) end_think_idx = self.buffer.rfind(self.think_end) if end_think_idx >= 0: self.state = Olmo3ReasoningState.CONTENT pretext, self.buffer = ( self.buffer[:end_think_idx], self.buffer[end_think_idx + len(self.think_end) :], ) if end_think_idx > 0: # this covers the case there's content before # the end of the reasoning block return DeltaMessage(reasoning=pretext) if self.state == Olmo3ReasoningState.REASONING: # we are inside reasoning block, return and empty # the text buffer ( text_buffer, self.buffer, ) = self.buffer, "" return DeltaMessage(reasoning=text_buffer) if self.state == Olmo3ReasoningState.CONTENT: # we are outside reasoning block, return and empty # the text buffer ( text_buffer, self.buffer, ) = self.buffer, "" return DeltaMessage(content=text_buffer) # nothing to return unless we are in reasoning or content state return None def __len__(self): # is the length of the text buffer return len(self.buffer) def add_text(self, delta_text: str) -> DeltaMessage | None: # we start by adding the delta text to the buffer self.buffer += delta_text # setting this to empty before starting delta_message: DeltaMessage | None = None # we start by computing the overlap between the delta_text # and start/end of think tokens. _, overlap_think_start = string_overlap(delta_text, self.think_start) _, overlap_think_end = string_overlap(delta_text, self.think_end) partial_overlap_start = overlap_think_start is not None and len( overlap_think_start ) < len(self.think_start) partial_overlap_end = overlap_think_end is not None and len( overlap_think_end ) < len(self.think_end) if ( partial_overlap_start and self.think_start in self.buffer and not partial_overlap_end ): # we can only process the buffer if partial overlap # is the last part of think token (thus causing # text_buffer to contain the start of think token) # and there are no partial overlaps with end think delta_message = self.process_buffer() elif partial_overlap_end and self.think_end in self.buffer: # same as before (partial overlap only allowed) # if the buffer contains the end think token, # but we don't have to check for partial overlap # with start think token because they are handled # by the previous condition delta_message = self.process_buffer() elif partial_overlap_start or partial_overlap_end: # in general, if there are overlaps, we don't # process the buffer because we want to wait until # the think token is fully completed. return None else: # we process the buffer as normal delta_message = self.process_buffer() return delta_message class Olmo3ReasoningParser(ReasoningParser): """ Reasoning parser for Olmo 3 model Olmo3ReasoningParser This class implements a reasoning parser specifically designed for the Olmo 3 family of models. Olmo 3 models do not use special tokens to indicate reasoning; rather, reasoning trace is wrapped in `<think>` and `</think>`, which are tokenized using standard vocabulary entries. Because of this, the parser operates in string space, accumulating the characters in a buffer until it sees `<think>` or `</think>`. tokens to switch modes. Key Features: - For non-stream output, Recognizes and extracts reasoning (text bracketed by `<think>` and `</think>`) and content (everything after the first `</think>`). - For stream process, it uses a buffer to accumulate delta text, and output progressive delta messages as soon as thinking starts or ends. - For reliability, some Olmo 3 models may hardcode the first `<think>` token is the input text (similar to Deepseek R1, or reasoning-only Qwen models). To support such variants, the parser can optionally work in cases where the first `<think>` token is missing from generation. """ def __init__(self, tokenizer: "TokenizerLike", *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) self.think_start = r"<think>" self.think_end = r"</think>" # notice that the first think is optional; this allows template to # work in cases when we hardcode a <think> at the beginning of the # reasoning template. reasoning_expr = ( rf"^(?:{self.think_start})?(?P<reasoning>.*?)" rf"{self.think_end}(?P<content>.*)$" ) self.reasoning_regex = re.compile(reasoning_expr, re.DOTALL) self.buffer = Olmo3ReasoningBuffer( think_start=self.think_start, think_end=self.think_end ) def is_reasoning_end(self, input_ids: Sequence[int]) -> bool: text = self.model_tokenizer.decode(input_ids) return self.think_end in text def extract_content_ids(self, input_ids: list[int]) -> list[int]: # for Olmo 3 streaming reason parsing, the stream parse # will call first, and the same token will be called in # is_reasoning_end and extract_content_ids # this id is not part of content, so just return [] here. return [] def extract_reasoning( self, model_output: str, request: ChatCompletionRequest | ResponsesRequest, ) -> tuple[str | None, str | None]: """Extract the reasoning content & content sections, respectively. If the sequence doesn't match what we expect, i.e., the model generates something else, all content is considered non-reasoning content. Args: model_output (str): Output of the model to be parsed. request (ChatCompletionRequest | ResponsesRequest): Request being processed. Returns: tuple[Optional[str], Optional[str]]: Tuple pair containing the reasoning content and non-reasoning content. """ re_match = self.reasoning_regex.match(model_output) if re_match: reasoning = re_match.group("reasoning") or None content = re_match.group("content") or None return reasoning, content # no reasoning content return None, model_output def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: """Extract content using token ID sequence state machine""" delta_message = self.buffer.add_text(delta_text) if delta_message is None and self.buffer.think_end in self.buffer.buffer: # this is a bit hacky, but, because of how the buffer is # constructed, if the last delta_text contains characters that # marks the end of thinking tokens, then messages in the buffer # would never be processed because we get no other turn. To get # around that, we check if the text buffer contains the end of # thinking tokens, and, if so, we reprocess the buffer again. delta_message = self.buffer.process_buffer() return delta_message
{ "repo_id": "vllm-project/vllm", "file_path": "vllm/reasoning/olmo3_reasoning_parser.py", "license": "Apache License 2.0", "lines": 249, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:benchmarks/kernels/benchmark_reshape_and_cache.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import random import time import torch from tabulate import tabulate from vllm import _custom_ops as ops from vllm.logger import init_logger from vllm.utils.argparse_utils import FlexibleArgumentParser from vllm.utils.torch_utils import ( STR_DTYPE_TO_TORCH_DTYPE, create_kv_caches_with_random, set_random_seed, ) logger = init_logger(__name__) @torch.inference_mode() def run_benchmark( num_tokens: int, num_heads: int, head_size: int, block_size: int, num_blocks: int, dtype: torch.dtype, kv_cache_dtype: str, num_iters: int, benchmark_mode: str, device: str = "cuda", ) -> float: """Return latency (seconds) for given num_tokens.""" if kv_cache_dtype == "fp8" and head_size % 16: raise ValueError("fp8 kv-cache requires head_size to be a multiple of 16.") set_random_seed(42) torch.set_default_device(device) # create random key / value tensors [T, H, D]. key = torch.randn(num_tokens, num_heads, head_size, dtype=dtype, device=device) value = torch.randn_like(key) # prepare the slot mapping. # each token is assigned a unique slot in the KV-cache. num_slots = block_size * num_blocks if num_tokens > num_slots: raise ValueError("num_tokens cannot exceed the total number of cache slots") slot_mapping_lst = random.sample(range(num_slots), num_tokens) slot_mapping = torch.tensor(slot_mapping_lst, dtype=torch.long, device=device) key_caches, value_caches = create_kv_caches_with_random( num_blocks, block_size, 1, # num_layers num_heads, head_size, kv_cache_dtype, dtype, device=device, ) key_cache, value_cache = key_caches[0], value_caches[0] # to free unused memory del key_caches, value_caches # compute per-kernel scaling factors for fp8 conversion (if used). k_scale = (key.amax() / 64.0).to(torch.float32) v_scale = (value.amax() / 64.0).to(torch.float32) function_under_test = lambda: ops.reshape_and_cache( key, # noqa: F821 value, # noqa: F821 key_cache, # noqa: F821 value_cache, # noqa: F821 slot_mapping, # noqa: F821 kv_cache_dtype, k_scale, v_scale, ) if benchmark_mode == "cudagraph": g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): function_under_test() torch.cuda.synchronize() function_under_test = lambda: g.replay() def run_cuda_benchmark(n_iters: int) -> float: nonlocal key, value, key_cache, value_cache, slot_mapping torch.cuda.synchronize() start = time.perf_counter() for _ in range(n_iters): function_under_test() torch.cuda.synchronize() end = time.perf_counter() return (end - start) / n_iters # warm-up run_cuda_benchmark(3) lat = run_cuda_benchmark(num_iters) # free tensors to mitigate OOM when sweeping del key, value, key_cache, value_cache, slot_mapping torch.cuda.empty_cache() return lat def main(args): rows = [] for exp in range(1, 17): n_tok = 2**exp lat = run_benchmark( num_tokens=n_tok, num_heads=args.num_heads, head_size=args.head_size, block_size=args.block_size, num_blocks=args.num_blocks, dtype=STR_DTYPE_TO_TORCH_DTYPE[args.dtype], kv_cache_dtype=args.kv_cache_dtype, num_iters=args.iters, benchmark_mode=args.mode, device="cuda", ) rows.append([n_tok, lat * 1e6]) # convert to microseconds print(f"Benchmark results for implementation cuda (measuring with {args.mode}):") print(tabulate(rows, headers=["num_tokens", "latency (µs)"], floatfmt=".3f")) if __name__ == "__main__": parser = FlexibleArgumentParser() parser.add_argument("--num-heads", type=int, default=128) parser.add_argument( "--head-size", type=int, choices=[64, 80, 96, 112, 120, 128, 192, 256], default=128, ) parser.add_argument("--block-size", type=int, choices=[16, 32], default=16) parser.add_argument("--num-blocks", type=int, default=128 * 128) parser.add_argument( "--dtype", type=str, choices=["half", "bfloat16", "float"], default="bfloat16", ) parser.add_argument( "--kv-cache-dtype", type=str, choices=["auto", "fp8"], default="auto", ) parser.add_argument("--iters", type=int, default=200) parser.add_argument( "--mode", type=str, choices=["cudagraph", "no_graph"], default="cudagraph", ) args = parser.parse_args() main(args)
{ "repo_id": "vllm-project/vllm", "file_path": "benchmarks/kernels/benchmark_reshape_and_cache.py", "license": "Apache License 2.0", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/entrypoints/openai/test_serving_responses.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from contextlib import AsyncExitStack from unittest.mock import MagicMock import pytest import pytest_asyncio from openai.types.responses.tool import ( CodeInterpreterContainerCodeInterpreterToolAuto, LocalShell, Mcp, Tool, ) import vllm.envs as envs from vllm.entrypoints.mcp.tool_server import ToolServer from vllm.entrypoints.openai.engine.protocol import ( ErrorResponse, RequestResponseMetadata, ) from vllm.entrypoints.openai.responses.context import ConversationContext, SimpleContext from vllm.entrypoints.openai.responses.protocol import ResponsesRequest from vllm.entrypoints.openai.responses.serving import ( OpenAIServingResponses, _extract_allowed_tools_from_mcp_requests, extract_tool_types, ) from vllm.entrypoints.openai.responses.streaming_events import ( StreamingState, ) from vllm.inputs.data import TokensPrompt from vllm.outputs import CompletionOutput, RequestOutput from vllm.sampling_params import SamplingParams class MockConversationContext(ConversationContext): """Mock conversation context for testing""" def __init__(self): self.init_tool_sessions_called = False self.init_tool_sessions_args = None self.init_tool_sessions_kwargs = None def append_output(self, output) -> None: pass def append_tool_output(self, output) -> None: pass async def call_tool(self): return [] def need_builtin_tool_call(self) -> bool: return False def render_for_completion(self): return [] async def init_tool_sessions(self, tool_server, exit_stack, request_id, mcp_tools): self.init_tool_sessions_called = True self.init_tool_sessions_args = (tool_server, exit_stack, request_id, mcp_tools) async def cleanup_session(self) -> None: pass @pytest.fixture def mock_serving_responses(): """Create a mock OpenAIServingResponses instance""" serving_responses = MagicMock(spec=OpenAIServingResponses) serving_responses.tool_server = MagicMock(spec=ToolServer) return serving_responses @pytest.fixture def mock_context(): """Create a mock conversation context""" return MockConversationContext() @pytest.fixture def mock_exit_stack(): """Create a mock async exit stack""" return MagicMock(spec=AsyncExitStack) def test_extract_tool_types(monkeypatch: pytest.MonkeyPatch) -> None: tools: list[Tool] = [] assert extract_tool_types(tools) == set() tools.append(LocalShell(type="local_shell")) assert extract_tool_types(tools) == {"local_shell"} tools.append(CodeInterpreterContainerCodeInterpreterToolAuto(type="auto")) assert extract_tool_types(tools) == {"local_shell", "auto"} tools.extend( [ Mcp(type="mcp", server_label="random", server_url=""), Mcp(type="mcp", server_label="container", server_url=""), Mcp(type="mcp", server_label="code_interpreter", server_url=""), Mcp(type="mcp", server_label="web_search_preview", server_url=""), ] ) # When envs.VLLM_GPT_OSS_SYSTEM_TOOL_MCP_LABELS is not set, # mcp tool types are all ignored. assert extract_tool_types(tools) == {"local_shell", "auto"} # container is allowed, it would be extracted monkeypatch.setenv("VLLM_GPT_OSS_SYSTEM_TOOL_MCP_LABELS", "container") assert extract_tool_types(tools) == {"local_shell", "auto", "container"} # code_interpreter and web_search_preview are allowed, # they would be extracted monkeypatch.setenv( "VLLM_GPT_OSS_SYSTEM_TOOL_MCP_LABELS", "code_interpreter,web_search_preview" ) assert extract_tool_types(tools) == { "local_shell", "auto", "code_interpreter", "web_search_preview", } class TestInitializeToolSessions: """Test class for _initialize_tool_sessions method""" @pytest_asyncio.fixture async def serving_responses_instance(self): """Create a real OpenAIServingResponses instance for testing""" # Create minimal mocks for required dependencies engine_client = MagicMock() model_config = MagicMock() model_config.max_model_len = 100 model_config.hf_config.model_type = "test" model_config.get_diff_sampling_param.return_value = {} engine_client.model_config = model_config engine_client.input_processor = MagicMock() engine_client.io_processor = MagicMock() engine_client.renderer = MagicMock() models = MagicMock() tool_server = MagicMock(spec=ToolServer) # Create the actual instance instance = OpenAIServingResponses( engine_client=engine_client, models=models, request_logger=None, chat_template=None, chat_template_content_format="auto", tool_server=tool_server, ) return instance @pytest.mark.asyncio async def test_initialize_tool_sessions( self, serving_responses_instance, mock_context, mock_exit_stack ): """Test that method works correctly with only MCP tools""" request = ResponsesRequest(input="test input", tools=[]) # Call the method await serving_responses_instance._initialize_tool_sessions( request, mock_context, mock_exit_stack ) assert mock_context.init_tool_sessions_called is False # Create only MCP tools tools = [ {"type": "web_search_preview"}, {"type": "code_interpreter", "container": {"type": "auto"}}, ] request = ResponsesRequest(input="test input", tools=tools) # Call the method await serving_responses_instance._initialize_tool_sessions( request, mock_context, mock_exit_stack ) # Verify that init_tool_sessions was called assert mock_context.init_tool_sessions_called def test_validate_create_responses_input( self, serving_responses_instance, mock_context, mock_exit_stack ): request = ResponsesRequest( input="test input", previous_input_messages=[ { "role": "user", "content": [ { "type": "text", "text": "What is my horoscope? I am an Aquarius.", } ], } ], previous_response_id="lol", ) error = serving_responses_instance._validate_create_responses_input(request) assert error is not None assert error.error.type == "invalid_request_error" class TestValidateGeneratorInput: """Test class for _validate_generator_input method""" @pytest_asyncio.fixture async def serving_responses_instance(self): """Create a real OpenAIServingResponses instance for testing""" # Create minimal mocks for required dependencies engine_client = MagicMock() model_config = MagicMock() model_config.max_model_len = 100 model_config.hf_config.model_type = "test" model_config.get_diff_sampling_param.return_value = {} engine_client.model_config = model_config engine_client.input_processor = MagicMock() engine_client.io_processor = MagicMock() engine_client.renderer = MagicMock() models = MagicMock() # Create the actual instance instance = OpenAIServingResponses( engine_client=engine_client, models=models, request_logger=None, chat_template=None, chat_template_content_format="auto", ) return instance def test_validate_generator_input(self, serving_responses_instance): """Test _validate_generator_input with valid prompt length""" # Create an engine prompt with valid length (less than max_model_len) valid_prompt_token_ids = list(range(5)) # 5 tokens < 100 max_model_len engine_prompt = TokensPrompt(prompt_token_ids=valid_prompt_token_ids) # Call the method result = serving_responses_instance._validate_generator_input(engine_prompt) # Should return None for valid input assert result is None # create an invalid engine prompt invalid_prompt_token_ids = list(range(200)) # 100 tokens >= 100 max_model_len engine_prompt = TokensPrompt(prompt_token_ids=invalid_prompt_token_ids) # Call the method result = serving_responses_instance._validate_generator_input(engine_prompt) # Should return an ErrorResponse assert result is not None assert isinstance(result, ErrorResponse) @pytest.mark.asyncio async def test_reasoning_tokens_counted_for_text_reasoning_model(monkeypatch): """Ensure reasoning_tokens usage is derived from thinking token spans.""" class FakeTokenizer: def __init__(self): self._vocab = {"<think>": 1, "</think>": 2, "reason": 3, "final": 4} def get_vocab(self): return self._vocab # Force non-harmony, SimpleContext path monkeypatch.setattr(envs, "VLLM_USE_EXPERIMENTAL_PARSER_CONTEXT", False) engine_client = MagicMock() model_config = MagicMock() model_config.hf_config.model_type = "test" model_config.hf_text_config = MagicMock() model_config.get_diff_sampling_param.return_value = {} engine_client.model_config = model_config engine_client.input_processor = MagicMock() engine_client.io_processor = MagicMock() engine_client.renderer = MagicMock() tokenizer = FakeTokenizer() engine_client.renderer.get_tokenizer.return_value = tokenizer models = MagicMock() serving = OpenAIServingResponses( engine_client=engine_client, models=models, request_logger=None, chat_template=None, chat_template_content_format="auto", reasoning_parser="qwen3", ) # Build a SimpleContext with thinking tokens in the output. context = SimpleContext() token_ids = [1, 10, 2, 20] # <think> 10 </think> 20 -> reasoning token count = 1 completion = CompletionOutput( index=0, text="<think>reason</think>final", token_ids=token_ids, cumulative_logprob=0.0, logprobs=None, finish_reason="stop", stop_reason=None, ) req_output = RequestOutput( request_id="req", prompt="hi", prompt_token_ids=[7, 8], prompt_logprobs=None, outputs=[completion], finished=True, num_cached_tokens=0, ) context.append_output(req_output) async def dummy_result_generator(): yield None request = ResponsesRequest(input="hi", tools=[], stream=False) sampling_params = SamplingParams(max_tokens=16) metadata = RequestResponseMetadata(request_id="req") response = await serving.responses_full_generator( request=request, sampling_params=sampling_params, result_generator=dummy_result_generator(), context=context, model_name="test-model", tokenizer=tokenizer, request_metadata=metadata, ) assert response.usage.output_tokens_details.reasoning_tokens == 1 class TestExtractAllowedToolsFromMcpRequests: """Test class for _extract_allowed_tools_from_mcp_requests function""" def test_extract_allowed_tools_basic_formats(self): """Test extraction with list format, object format, and None.""" from openai.types.responses.tool import McpAllowedToolsMcpToolFilter tools = [ # List format Mcp( type="mcp", server_label="server1", allowed_tools=["tool1", "tool2"], ), # Object format Mcp( type="mcp", server_label="server2", allowed_tools=McpAllowedToolsMcpToolFilter( tool_names=["tool3", "tool4"] ), ), # None (no filter) Mcp( type="mcp", server_label="server3", allowed_tools=None, ), ] result = _extract_allowed_tools_from_mcp_requests(tools) assert result == { "server1": ["tool1", "tool2"], "server2": ["tool3", "tool4"], "server3": None, } def test_extract_allowed_tools_star_normalization(self): """Test that '*' wildcard is normalized to None (select all tools). This is the key test requested by reviewers to explicitly demonstrate that the "*" select-all scenario is handled correctly. """ from openai.types.responses.tool import McpAllowedToolsMcpToolFilter tools = [ # Star in list format Mcp( type="mcp", server_label="server1", allowed_tools=["*"], ), # Star mixed with other tools in list Mcp( type="mcp", server_label="server2", allowed_tools=["tool1", "*"], ), # Star in object format Mcp( type="mcp", server_label="server3", allowed_tools=McpAllowedToolsMcpToolFilter(tool_names=["*"]), ), ] result = _extract_allowed_tools_from_mcp_requests(tools) # All should be normalized to None (allows all tools) assert result == { "server1": None, "server2": None, "server3": None, } def test_extract_allowed_tools_filters_non_mcp(self): """Test that non-MCP tools are ignored during extraction.""" tools = [ Mcp( type="mcp", server_label="server1", allowed_tools=["tool1"], ), LocalShell(type="local_shell"), # Non-MCP tool should be ignored Mcp( type="mcp", server_label="server2", allowed_tools=["tool2"], ), ] result = _extract_allowed_tools_from_mcp_requests(tools) # Non-MCP tools should be ignored assert result == { "server1": ["tool1"], "server2": ["tool2"], } class TestHarmonyPreambleStreaming: """Tests for preamble (commentary with no recipient) streaming events.""" @staticmethod def _make_ctx(*, channel, recipient, delta="hello"): """Build a lightweight mock StreamingHarmonyContext.""" ctx = MagicMock() ctx.last_content_delta = delta ctx.parser.current_channel = channel ctx.parser.current_recipient = recipient return ctx @staticmethod def _make_previous_item(*, channel, recipient, text="preamble text"): """Build a lightweight mock previous_item (openai_harmony Message).""" content_part = MagicMock() content_part.text = text item = MagicMock() item.channel = channel item.recipient = recipient item.content = [content_part] return item def test_preamble_delta_emits_text_events(self) -> None: """commentary + recipient=None should emit output_text.delta events.""" from vllm.entrypoints.openai.responses.streaming_events import ( emit_content_delta_events, ) ctx = self._make_ctx(channel="commentary", recipient=None) state = StreamingState() events = emit_content_delta_events(ctx, state) type_names = [e.type for e in events] assert "response.output_text.delta" in type_names assert "response.output_item.added" in type_names def test_preamble_delta_second_token_no_added(self) -> None: """Second preamble token should emit delta only, not added again.""" from vllm.entrypoints.openai.responses.streaming_events import ( emit_content_delta_events, ) ctx = self._make_ctx(channel="commentary", recipient=None, delta="w") state = StreamingState() state.sent_output_item_added = True state.current_item_id = "msg_test" state.current_content_index = 0 events = emit_content_delta_events(ctx, state) type_names = [e.type for e in events] assert "response.output_text.delta" in type_names assert "response.output_item.added" not in type_names def test_commentary_with_function_recipient_not_preamble(self) -> None: """commentary + recipient='functions.X' must NOT use preamble path.""" from vllm.entrypoints.openai.responses.streaming_events import ( emit_content_delta_events, ) ctx = self._make_ctx( channel="commentary", recipient="functions.get_weather", ) state = StreamingState() events = emit_content_delta_events(ctx, state) type_names = [e.type for e in events] assert "response.output_text.delta" not in type_names def test_preamble_done_emits_text_done_events(self) -> None: """Completed preamble should emit text done + content_part done + output_item done, same shape as final channel.""" from vllm.entrypoints.openai.responses.streaming_events import ( emit_previous_item_done_events, ) previous = self._make_previous_item(channel="commentary", recipient=None) state = StreamingState() state.current_item_id = "msg_test" state.current_output_index = 0 state.current_content_index = 0 events = emit_previous_item_done_events(previous, state) type_names = [e.type for e in events] assert "response.output_text.done" in type_names assert "response.content_part.done" in type_names assert "response.output_item.done" in type_names def test_commentary_with_recipient_no_preamble_done(self) -> None: """commentary + recipient='functions.X' should route to function call done, not preamble done.""" from vllm.entrypoints.openai.responses.streaming_events import ( emit_previous_item_done_events, ) previous = self._make_previous_item( channel="commentary", recipient="functions.get_weather" ) state = StreamingState() state.current_item_id = "fc_test" events = emit_previous_item_done_events(previous, state) type_names = [e.type for e in events] assert "response.output_text.done" not in type_names
{ "repo_id": "vllm-project/vllm", "file_path": "tests/entrypoints/openai/test_serving_responses.py", "license": "Apache License 2.0", "lines": 453, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm:examples/offline_inference/kv_load_failure_recovery/decode_example.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import argparse from vllm import LLM, SamplingParams from vllm.config import KVTransferConfig def read_prompts(): """Read prompts from prefill_output.txt""" prompts = [] try: with open("prefill_output.txt") as f: for line in f: prompts.append(line.strip()) print(f"Loaded {len(prompts)} prompts from prefill_output.txt") return prompts except FileNotFoundError: print("Error: prefill_output.txt file not found") exit(-1) def main(): prompts = read_prompts() sampling_params = SamplingParams(temperature=0, top_p=0.95, max_tokens=10) parser = argparse.ArgumentParser() parser.add_argument( "--simulate-failure", action="store_true", help="Simulate KV load failure." ) parser.add_argument( "--async-load", action="store_true", help="Simulate async KV load" ) args = parser.parse_args() if args.simulate_failure: ktc = KVTransferConfig( kv_connector="LoadRecoveryExampleConnector", kv_role="kv_both", kv_connector_extra_config={ "shared_storage_path": "local_storage", "async_load": args.async_load, }, kv_connector_module_path="load_recovery_example_connector", kv_load_failure_policy="recompute", ) out_file = ( "async_decode_recovered_output.txt" if args.async_load else "sync_decode_recovered_output.txt" ) else: ktc = KVTransferConfig( kv_connector="ExampleConnector", kv_role="kv_both", kv_connector_extra_config={ "shared_storage_path": "local_storage", }, ) out_file = "decode_output.txt" llm = LLM( model="meta-llama/Llama-3.2-1B-Instruct", enforce_eager=True, gpu_memory_utilization=0.8, max_num_batched_tokens=64, max_num_seqs=16, kv_transfer_config=ktc, ) outputs = llm.generate(prompts, sampling_params) sep_str = "-" * 30 with open(out_file, "w", encoding="utf-8") as f: for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text out_str = f"Prompt: {prompt!r}\nGenerated text: {generated_text!r}" print(out_str) print(sep_str) f.write(out_str) f.write(sep_str) if __name__ == "__main__": main()
{ "repo_id": "vllm-project/vllm", "file_path": "examples/offline_inference/kv_load_failure_recovery/decode_example.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:examples/offline_inference/kv_load_failure_recovery/prefill_example.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm import LLM, SamplingParams from vllm.config import KVTransferConfig def read_prompts(): context = "Hi " * 1000 context2 = "Hey " * 500 return [ context + "Hello, my name is", context + "The capital of France is", context2 + "Your name is", context2 + "The capital of China is", ] def main(): prompts = read_prompts() sampling_params = SamplingParams(temperature=0, top_p=0.95, max_tokens=1) llm = LLM( model="meta-llama/Llama-3.2-1B-Instruct", enforce_eager=True, gpu_memory_utilization=0.8, kv_transfer_config=KVTransferConfig( kv_connector="ExampleConnector", kv_role="kv_both", kv_connector_extra_config={"shared_storage_path": "local_storage"}, ), ) # , max_model_len=2048, max_num_batched_tokens=2048) # 1ST generation (prefill instance) outputs = llm.generate( prompts, sampling_params, ) new_prompts = [] print("-" * 30) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text new_prompts.append(prompt + generated_text) print(f"Prompt: {prompt!r}\nGenerated text: {generated_text!r}") print("-" * 30) # Write new_prompts to prefill_output.txt with open("prefill_output.txt", "w") as f: for prompt in new_prompts: f.write(prompt + "\n") print(f"Saved {len(new_prompts)} prompts to prefill_output.txt") if __name__ == "__main__": main()
{ "repo_id": "vllm-project/vllm", "file_path": "examples/offline_inference/kv_load_failure_recovery/prefill_example.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
vllm-project/vllm:tests/v1/kv_connector/unit/test_kv_load_failure_recovery.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Callable from unittest.mock import Mock import pytest from vllm.v1.core.sched.scheduler import Scheduler from vllm.v1.request import Request, RequestStatus from .utils import ( create_model_runner_output, create_request, create_scheduler, create_vllm_config, ) def _make_get_num_new_matched_tokens( req_num_new_matched_tokens: dict[str, int], async_load, ) -> Callable[[Request, int], tuple[int, bool]]: def get_num_new_matched_tokens(request: Request, _: int) -> tuple[int, bool]: value = req_num_new_matched_tokens.get(request.request_id, 0) return value, async_load return get_num_new_matched_tokens @pytest.fixture def scheduler(): vllm_config = create_vllm_config(kv_load_failure_policy="recompute") return create_scheduler(vllm_config) @pytest.mark.parametrize( "num_prompt_blocks,num_external_computed_blocks,invalid_block_idxs", [ (100, 99, {0, 98}), (100, 99, {50, 98}), (100, 99, {98}), ], ) def test_async_load_failure( scheduler: Scheduler, num_prompt_blocks: int, num_external_computed_blocks: int, invalid_block_idxs: set[int], ): assert num_prompt_blocks >= num_external_computed_blocks num_prompt_tokens = num_prompt_blocks * scheduler.block_size num_external_computed_tokens = num_external_computed_blocks * scheduler.block_size request1 = create_request(num_tokens=num_prompt_tokens) scheduler.add_request(request=request1) request2 = create_request(num_tokens=num_prompt_tokens) scheduler.add_request(request=request2) request3 = create_request(num_tokens=num_prompt_tokens) scheduler.add_request(request=request3) # Mock KV connector method. # req_id -> num_external_computed_tokens req_num_new_matched_tokens = { request1.request_id: num_external_computed_tokens, request2.request_id: num_external_computed_tokens, request3.request_id: num_external_computed_tokens, } scheduler.connector = Mock() scheduler.connector.get_num_new_matched_tokens.side_effect = ( _make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=True) ) scheduler.connector.take_events.return_value = () scheduler_output = scheduler.schedule() assert len(scheduler.waiting) == 3 for request in scheduler.waiting: assert request.num_computed_tokens == 0 assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS assert scheduler.connector.get_num_new_matched_tokens.call_count == 3 # Simulate a failure in loading some of request2 blocks. (req2_block_ids,) = scheduler.kv_cache_manager.get_block_ids(request2.request_id) invalid_block_ids = {req2_block_ids[i] for i in invalid_block_idxs} model_runner_output = create_model_runner_output( reqs=[], finished_recving={request1.request_id, request3.request_id}, invalid_block_ids=invalid_block_ids, use_eos=True, ) scheduler.update_from_output(scheduler_output, model_runner_output) min_invalid_block_idx = min(invalid_block_idxs) assert len(scheduler.waiting) == 3 for request in scheduler.waiting: if request.request_id == request2.request_id: assert request.num_computed_tokens == ( min_invalid_block_idx * scheduler.block_size ) else: assert request.num_computed_tokens == 0 assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS assert scheduler.failed_recving_kv_req_ids == {request2.request_id} assert scheduler.connector.get_num_new_matched_tokens.call_count == 3 @pytest.mark.parametrize( "num_prompt_blocks,num_external_computed_blocks,invalid_block_idxs", [ (100, 99, {0, 98}), (100, 99, {50, 98}), (100, 99, {98}), ], ) def test_sync_load_failure( scheduler: Scheduler, num_prompt_blocks: int, num_external_computed_blocks: int, invalid_block_idxs: set[int], ): assert num_prompt_blocks >= num_external_computed_blocks num_prompt_tokens = num_prompt_blocks * scheduler.block_size num_external_computed_tokens = num_external_computed_blocks * scheduler.block_size request1 = create_request(num_tokens=num_prompt_tokens) scheduler.add_request(request=request1) request2 = create_request(num_tokens=num_prompt_tokens) scheduler.add_request(request=request2) request3 = create_request(num_tokens=num_prompt_tokens) scheduler.add_request(request=request3) # Mock KV connector method. # req_id -> num_external_computed_tokens req_num_new_matched_tokens = { request1.request_id: num_external_computed_tokens, request2.request_id: num_external_computed_tokens, request3.request_id: num_external_computed_tokens, } scheduler.connector = Mock() scheduler.connector.get_num_new_matched_tokens.side_effect = ( _make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=False) ) scheduler.connector.request_finished.return_value = (False, None) scheduler.connector.take_events.return_value = () scheduler_output = scheduler.schedule() # req_id -> num_computed_tokens expected_computed_tokens = { request1.request_id: num_external_computed_tokens, request2.request_id: num_external_computed_tokens, request3.request_id: num_external_computed_tokens, } assert len(scheduler.running) == 3 assert len(scheduler_output.scheduled_new_reqs) == 3 for request in scheduler_output.scheduled_new_reqs: assert request.num_computed_tokens == expected_computed_tokens[request.req_id] assert scheduler.connector.get_num_new_matched_tokens.call_count == 3 # Simulate a failure in loading some of request2 blocks. req2_block_ids = scheduler_output.scheduled_new_reqs[1].block_ids[0] invalid_block_ids = {req2_block_ids[i] for i in invalid_block_idxs} model_runner_output = create_model_runner_output( [request1, request2, request3], invalid_block_ids=invalid_block_ids, use_eos=True, ) scheduler.update_from_output(scheduler_output, model_runner_output) assert len(scheduler.running) == 1 assert scheduler.running[0].request_id == request2.request_id assert scheduler.running[0].num_computed_tokens == ( min(invalid_block_idxs) * scheduler.block_size ) assert scheduler.connector.get_num_new_matched_tokens.call_count == 3 assert scheduler.connector.request_finished.call_count == 2 @pytest.mark.parametrize( "num_prompt_blocks," "num_external_computed_blocks," "num_common_prefix_blocks," "invalid_block_idxs", [ (100, 99, 50, {0, 49}), (100, 99, 50, {25, 49}), (100, 99, 50, {49}), ], ) def test_sync_load_failure_with_shared_blocks( scheduler: Scheduler, num_prompt_blocks: int, num_external_computed_blocks: int, num_common_prefix_blocks: int, invalid_block_idxs: set[int], ): assert num_prompt_blocks >= num_external_computed_blocks >= num_common_prefix_blocks num_prompt_tokens = num_prompt_blocks * scheduler.block_size num_external_computed_tokens = num_external_computed_blocks * scheduler.block_size common_prefix_len = num_common_prefix_blocks * scheduler.block_size request1 = create_request( num_tokens=num_prompt_tokens, common_prefix_len=common_prefix_len ) scheduler.add_request(request=request1) request2 = create_request( num_tokens=num_prompt_tokens, common_prefix_len=common_prefix_len ) scheduler.add_request(request=request2) # Mock KV connector method. # req_id -> num_external_computed_tokens req_num_new_matched_tokens = { request1.request_id: num_external_computed_tokens, } scheduler.connector = Mock() scheduler.connector.get_num_new_matched_tokens.side_effect = ( _make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=False) ) scheduler.connector.take_events.return_value = () scheduler_output = scheduler.schedule() # req_id -> num_computed_tokens expected_computed_tokens = { request1.request_id: num_external_computed_tokens, request2.request_id: common_prefix_len, } assert len(scheduler.running) == 2 assert len(scheduler_output.scheduled_new_reqs) == 2 for request in scheduler_output.scheduled_new_reqs: assert request.num_computed_tokens == expected_computed_tokens[request.req_id] assert scheduler.connector.get_num_new_matched_tokens.call_count == 2 # Simulate a failure in loading some of the shared blocks. req1_block_ids = scheduler_output.scheduled_new_reqs[0].block_ids[0] invalid_block_ids = {req1_block_ids[i] for i in invalid_block_idxs} model_runner_output = create_model_runner_output( [request1, request2], invalid_block_ids=invalid_block_ids, use_eos=True ) scheduler.update_from_output(scheduler_output, model_runner_output) # req_id -> num_computed_tokens # all the common prefix blocks will be computed by request1 expected_computed_tokens = { request1.request_id: min(invalid_block_idxs) * scheduler.block_size, request2.request_id: common_prefix_len, } assert len(scheduler.running) == 2 for request in scheduler.running: assert ( request.num_computed_tokens == expected_computed_tokens[request.request_id] ) assert scheduler.connector.get_num_new_matched_tokens.call_count == 2 @pytest.mark.parametrize( "num_prompt_blocks,num_external_computed_blocks,invalid_block_idxs", [ (100, 99, {0, 50, 98}), (100, 99, {98, 50, 0}), ], ) def test_async_progressive_load_failure( scheduler: Scheduler, num_prompt_blocks: int, num_external_computed_blocks: int, invalid_block_idxs: set[int], ): assert num_prompt_blocks >= num_external_computed_blocks num_prompt_tokens = num_prompt_blocks * scheduler.block_size num_external_computed_tokens = num_external_computed_blocks * scheduler.block_size request = create_request(num_tokens=num_prompt_tokens) scheduler.add_request(request=request) # Mock KV connector method. # req_id -> num_external_computed_tokens req_num_new_matched_tokens = { request.request_id: num_external_computed_tokens, } scheduler.connector = Mock() scheduler.connector.get_num_new_matched_tokens.side_effect = ( _make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=True) ) scheduler.connector.take_events.return_value = () scheduler_output = scheduler.schedule() assert len(scheduler.waiting) == 1 assert scheduler.waiting.peek_request().request_id == request.request_id assert request.num_computed_tokens == 0 assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS assert scheduler.connector.get_num_new_matched_tokens.call_count == 1 min_invalid_block_idx = max(invalid_block_idxs) + 1 # Simulate failures when progressively loading request blocks. for invalid_block_idx in invalid_block_idxs: (req_block_ids,) = scheduler.kv_cache_manager.get_block_ids(request.request_id) invalid_block_ids = {req_block_ids[invalid_block_idx]} model_runner_output = create_model_runner_output( reqs=[], finished_recving=set(), invalid_block_ids=invalid_block_ids, use_eos=True, ) scheduler.update_from_output(scheduler_output, model_runner_output) min_invalid_block_idx = min(min_invalid_block_idx, invalid_block_idx) assert len(scheduler.waiting) == 1 assert scheduler.waiting.peek_request().request_id == request.request_id assert request.num_computed_tokens == ( min_invalid_block_idx * scheduler.block_size ) assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS assert scheduler.failed_recving_kv_req_ids == {request.request_id} assert scheduler.connector.get_num_new_matched_tokens.call_count == 1
{ "repo_id": "vllm-project/vllm", "file_path": "tests/v1/kv_connector/unit/test_kv_load_failure_recovery.py", "license": "Apache License 2.0", "lines": 277, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm: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" ) @pytest.mark.parametrize("clean_logits", [True, False]) def test_deepgemm_fp8_mqa_logits(clean_logits: bool): 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, clean_logits=clean_logits ) 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") if clean_logits: 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(ref_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" ) @pytest.mark.parametrize("clean_logits", [True, False]) def test_deepgemm_fp8_paged_mqa_logits(clean_logits: bool): 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, clean_logits=clean_logits, ) 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=}"
{ "repo_id": "vllm-project/vllm", "file_path": "tests/kernels/attention/test_deepgemm_attention.py", "license": "Apache License 2.0", "lines": 267, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
vllm-project/vllm: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.v1.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.v1.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 = 64 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.v1.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)
{ "repo_id": "vllm-project/vllm", "file_path": "tests/kernels/attention/test_flashmla_sparse.py", "license": "Apache License 2.0", "lines": 103, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test