repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/disagg/protocol.py
vllm/entrypoints/serve/disagg/protocol.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any from pydantic import BaseModel, Field from vllm.entrypoints.openai.protocol import ( ChatCompletionLogProbs, Logprob, SamplingParams, StreamOptions, ) from vllm.utils import random_uuid ####### Tokens IN <> Tokens OUT ####### class GenerateRequest(BaseModel): request_id: str = Field( default_factory=lambda: f"{random_uuid()}", description=( "The request_id related to this request. If the caller does " "not set it, a random_uuid will be generated. This id is used " "through out the inference process and return in response." ), ) token_ids: list[int] """The token ids to generate text from.""" # features: MultiModalFeatureSpec # TODO (NickLucche): implement once Renderer work is completed features: str | None = None """The processed MM inputs for the model.""" sampling_params: SamplingParams """The sampling parameters for the model.""" model: str | None = None stream: bool | None = False stream_options: StreamOptions | None = None cache_salt: str | None = Field( default=None, description=( "If specified, the prefix cache will be salted with the provided " "string to prevent an attacker to guess prompts in multi-user " "environments. The salt should be random, protected from " "access by 3rd parties, and long enough to be " "unpredictable (e.g., 43 characters base64-encoded, corresponding " "to 256 bit)." ), ) priority: int = Field( default=0, description=( "The priority of the request (lower means earlier handling; " "default: 0). Any priority other than 0 will raise an error " "if the served model does not use priority scheduling." ), ) kv_transfer_params: dict[str, Any] | None = Field( default=None, description="KVTransfer parameters used for disaggregated serving.", ) class GenerateResponseChoice(BaseModel): index: int logprobs: ChatCompletionLogProbs | None = None # per OpenAI spec this is the default finish_reason: str | None = "stop" token_ids: list[int] | None = None class GenerateResponse(BaseModel): request_id: str = Field( default_factory=lambda: f"{random_uuid()}", description=( "The request_id related to this request. If the caller does " "not set it, a random_uuid will be generated. This id is used " "through out the inference process and return in response." ), ) choices: list[GenerateResponseChoice] prompt_logprobs: list[dict[int, Logprob] | None] | None = None kv_transfer_params: dict[str, Any] | None = Field( default=None, description="KVTransfer parameters used for disaggregated serving.", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/cache/__init__.py
vllm/entrypoints/serve/cache/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/cache/api_router.py
vllm/entrypoints/serve/cache/api_router.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from fastapi import APIRouter, FastAPI, Query, Request from fastapi.responses import Response import vllm.envs as envs from vllm.engine.protocol import EngineClient from vllm.logger import init_logger logger = init_logger(__name__) router = APIRouter() def engine_client(request: Request) -> EngineClient: return request.app.state.engine_client @router.post("/reset_prefix_cache") async def reset_prefix_cache( raw_request: Request, reset_running_requests: bool = Query(default=False), reset_external: bool = Query(default=False), ): """ Reset the local prefix cache. Optionally, if the query parameter `reset_external=true` also resets the external (connector-managed) prefix cache. Note that we currently do not check if the prefix cache is successfully reset in the API server. Example: POST /reset_prefix_cache?reset_external=true """ logger.info("Resetting prefix cache...") await engine_client(raw_request).reset_prefix_cache( reset_running_requests, reset_external ) return Response(status_code=200) @router.post("/reset_mm_cache") async def reset_mm_cache(raw_request: Request): """ Reset the multi-modal cache. Note that we currently do not check if the multi-modal cache is successfully reset in the API server. """ logger.info("Resetting multi-modal cache...") await engine_client(raw_request).reset_mm_cache() return Response(status_code=200) def attach_router(app: FastAPI): if not envs.VLLM_SERVER_DEV_MODE: return app.include_router(router)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/rpc/__init__.py
vllm/entrypoints/serve/rpc/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/rpc/api_router.py
vllm/entrypoints/serve/rpc/api_router.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import json from http import HTTPStatus from typing import Any from fastapi import APIRouter, FastAPI, HTTPException, Request from fastapi.responses import JSONResponse, Response import vllm.envs as envs from vllm.engine.protocol import EngineClient from vllm.logger import init_logger logger = init_logger(__name__) router = APIRouter() def engine_client(request: Request) -> EngineClient: return request.app.state.engine_client @router.post("/collective_rpc") async def collective_rpc(raw_request: Request): try: body = await raw_request.json() except json.JSONDecodeError as e: raise HTTPException( status_code=HTTPStatus.BAD_REQUEST.value, detail=f"JSON decode error: {e}", ) from e method = body.get("method") if method is None: raise HTTPException( status_code=HTTPStatus.BAD_REQUEST.value, detail="Missing 'method' in request body", ) # For security reason, only serialized string args/kwargs are passed. # User-defined `method` is responsible for deserialization if needed. args: list[str] = body.get("args", []) kwargs: dict[str, str] = body.get("kwargs", {}) timeout: float | None = body.get("timeout") results = await engine_client(raw_request).collective_rpc( method=method, timeout=timeout, args=tuple(args), kwargs=kwargs ) if results is None: return Response(status_code=200) response: list[Any] = [] for result in results: if result is None or isinstance(result, dict | list): response.append(result) else: response.append(str(result)) return JSONResponse(content={"results": response}) def attach_router(app: FastAPI): if not envs.VLLM_SERVER_DEV_MODE: return app.include_router(router)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/profile/__init__.py
vllm/entrypoints/serve/profile/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/profile/api_router.py
vllm/entrypoints/serve/profile/api_router.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from fastapi import APIRouter, FastAPI, Request from fastapi.responses import Response from vllm.config import ProfilerConfig from vllm.engine.protocol import EngineClient from vllm.logger import init_logger logger = init_logger(__name__) router = APIRouter() def engine_client(request: Request) -> EngineClient: return request.app.state.engine_client @router.post("/start_profile") async def start_profile(raw_request: Request): logger.info("Starting profiler...") await engine_client(raw_request).start_profile() logger.info("Profiler started.") return Response(status_code=200) @router.post("/stop_profile") async def stop_profile(raw_request: Request): logger.info("Stopping profiler...") await engine_client(raw_request).stop_profile() logger.info("Profiler stopped.") return Response(status_code=200) def attach_router(app: FastAPI): profiler_config = getattr(app.state.args, "profiler_config", None) assert profiler_config is None or isinstance(profiler_config, ProfilerConfig) if profiler_config is not None and profiler_config.profiler is not None: logger.warning_once( "Profiler with mode '%s' is enabled in the " "API server. This should ONLY be used for local development!", profiler_config.profiler, ) app.include_router(router)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/rlhf/__init__.py
vllm/entrypoints/serve/rlhf/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/rlhf/api_router.py
vllm/entrypoints/serve/rlhf/api_router.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from http import HTTPStatus from fastapi import APIRouter, FastAPI, Query, Request from fastapi.responses import JSONResponse from vllm.engine.protocol import EngineClient from vllm.logger import init_logger logger = init_logger(__name__) def engine_client(request: Request) -> EngineClient: return request.app.state.engine_client router = APIRouter() @router.post("/pause") async def pause_generation( raw_request: Request, wait_for_inflight_requests: bool = Query(False), clear_cache: bool = Query(True), ) -> JSONResponse: """Pause generation requests to allow weight updates. Args: wait_for_inflight_requests: When ``True`` waits for in-flight requests to finish before pausing. When ``False`` (default), aborts any in-flight requests immediately. clear_cache: Whether to clear KV/prefix caches after draining. """ engine = engine_client(raw_request) try: await engine.pause_generation( wait_for_inflight_requests=wait_for_inflight_requests, clear_cache=clear_cache, ) return JSONResponse( content={"status": "paused"}, status_code=HTTPStatus.OK.value, ) except ValueError as err: return JSONResponse( content={"error": str(err)}, status_code=HTTPStatus.BAD_REQUEST.value, ) except Exception as err: # pragma: no cover - defensive logger.exception("Failed to pause generation") return JSONResponse( content={"error": f"Failed to pause generation: {err}"}, status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, ) @router.post("/resume") async def resume_generation(raw_request: Request) -> JSONResponse: """Resume generation after a pause.""" engine = engine_client(raw_request) try: await engine.resume_generation() return JSONResponse( content={"status": "resumed"}, status_code=HTTPStatus.OK.value, ) except Exception as err: # pragma: no cover - defensive logger.exception("Failed to resume generation") return JSONResponse( content={"error": f"Failed to resume generation: {err}"}, status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, ) @router.get("/is_paused") async def is_paused(raw_request: Request) -> JSONResponse: """Return the current pause status.""" engine = engine_client(raw_request) try: paused = await engine.is_paused() except Exception as err: # pragma: no cover - defensive logger.exception("Failed to fetch pause status") return JSONResponse( content={"error": f"Failed to fetch pause status: {err}"}, status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, ) return JSONResponse(content={"is_paused": paused}) def attach_router(app: FastAPI): app.include_router(router)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/lora/__init__.py
vllm/entrypoints/serve/lora/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/lora/api_router.py
vllm/entrypoints/serve/lora/api_router.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import model_hosting_container_standards.sagemaker as sagemaker_standards from fastapi import APIRouter, Depends, FastAPI, Request from fastapi.responses import JSONResponse, Response from vllm import envs from vllm.entrypoints.openai.api_server import models, validate_json_request from vllm.entrypoints.openai.protocol import ( ErrorResponse, LoadLoRAAdapterRequest, UnloadLoRAAdapterRequest, ) from vllm.entrypoints.openai.serving_models import OpenAIServingModels from vllm.logger import init_logger logger = init_logger(__name__) router = APIRouter() def attach_router(app: FastAPI): if not envs.VLLM_ALLOW_RUNTIME_LORA_UPDATING: """If LoRA dynamic loading & unloading is not enabled, do nothing.""" return logger.warning( "LoRA dynamic loading & unloading is enabled in the API server. " "This should ONLY be used for local development!" ) @sagemaker_standards.register_load_adapter_handler( request_shape={ "lora_name": "body.name", "lora_path": "body.src", }, ) @router.post("/v1/load_lora_adapter", dependencies=[Depends(validate_json_request)]) async def load_lora_adapter(request: LoadLoRAAdapterRequest, raw_request: Request): handler: OpenAIServingModels = models(raw_request) response = await handler.load_lora_adapter(request) if isinstance(response, ErrorResponse): return JSONResponse( content=response.model_dump(), status_code=response.error.code ) return Response(status_code=200, content=response) @sagemaker_standards.register_unload_adapter_handler( request_shape={ "lora_name": "path_params.adapter_name", } ) @router.post( "/v1/unload_lora_adapter", dependencies=[Depends(validate_json_request)] ) async def unload_lora_adapter( request: UnloadLoRAAdapterRequest, raw_request: Request ): handler: OpenAIServingModels = models(raw_request) response = await handler.unload_lora_adapter(request) if isinstance(response, ErrorResponse): return JSONResponse( content=response.model_dump(), status_code=response.error.code ) return Response(status_code=200, content=response) # register the router app.include_router(router)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/tokenize/serving.py
vllm/entrypoints/serve/tokenize/serving.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import Any, Final import jinja2 from fastapi import Request from vllm.engine.protocol import EngineClient from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption from vllm.entrypoints.logger import RequestLogger from vllm.entrypoints.openai.protocol import ( DetokenizeRequest, DetokenizeResponse, ErrorResponse, TokenizeChatRequest, TokenizeRequest, TokenizeResponse, TokenizerInfoResponse, ) from vllm.entrypoints.openai.serving_engine import OpenAIServing from vllm.entrypoints.openai.serving_models import OpenAIServingModels from vllm.entrypoints.renderer import RenderConfig from vllm.inputs import TokensPrompt from vllm.logger import init_logger from vllm.tokenizers import TokenizerLike logger = init_logger(__name__) class OpenAIServingTokenization(OpenAIServing): def __init__( self, engine_client: EngineClient, models: OpenAIServingModels, *, request_logger: RequestLogger | None, chat_template: str | None, chat_template_content_format: ChatTemplateContentFormatOption, trust_request_chat_template: bool = False, log_error_stack: bool = False, ) -> None: super().__init__( engine_client=engine_client, models=models, request_logger=request_logger, log_error_stack=log_error_stack, ) self.chat_template = chat_template self.chat_template_content_format: Final = chat_template_content_format self.trust_request_chat_template = trust_request_chat_template async def create_tokenize( self, request: TokenizeRequest, raw_request: Request, ) -> TokenizeResponse | ErrorResponse: error_check_ret = await self._check_model(request) if error_check_ret is not None: return error_check_ret request_id = f"tokn-{self._base_request_id(raw_request)}" try: lora_request = self._maybe_get_adapters(request) tokenizer = await self.engine_client.get_tokenizer() renderer = self._get_renderer(tokenizer) if isinstance(request, TokenizeChatRequest): tool_dicts = ( None if request.tools is None else [tool.model_dump() for tool in request.tools] ) error_check_ret = self._validate_chat_template( request_chat_template=request.chat_template, chat_template_kwargs=request.chat_template_kwargs, trust_request_chat_template=self.trust_request_chat_template, ) if error_check_ret is not None: return error_check_ret _, engine_prompts = await self._preprocess_chat( request, tokenizer, request.messages, tool_dicts=tool_dicts, chat_template=request.chat_template or self.chat_template, chat_template_content_format=self.chat_template_content_format, add_generation_prompt=request.add_generation_prompt, continue_final_message=request.continue_final_message, chat_template_kwargs=request.chat_template_kwargs, add_special_tokens=request.add_special_tokens, ) else: engine_prompts = await renderer.render_prompt( prompt_or_prompts=request.prompt, config=self._build_render_config(request), ) except (ValueError, TypeError, jinja2.TemplateError) as e: logger.exception("Error in preprocessing prompt inputs") return self.create_error_response(f"{e} {e.__cause__}") input_ids: list[int] = [] for engine_prompt in engine_prompts: self._log_inputs( request_id, engine_prompt, params=None, lora_request=lora_request ) if isinstance(engine_prompt, dict) and "prompt_token_ids" in engine_prompt: input_ids.extend(engine_prompt["prompt_token_ids"]) token_strs = None if request.return_token_strs: token_strs = tokenizer.convert_ids_to_tokens(input_ids) return TokenizeResponse( tokens=input_ids, token_strs=token_strs, count=len(input_ids), max_model_len=self.max_model_len, ) async def create_detokenize( self, request: DetokenizeRequest, raw_request: Request, ) -> DetokenizeResponse | ErrorResponse: error_check_ret = await self._check_model(request) if error_check_ret is not None: return error_check_ret request_id = f"tokn-{self._base_request_id(raw_request)}" lora_request = self._maybe_get_adapters(request) tokenizer = await self.engine_client.get_tokenizer() self._log_inputs( request_id, TokensPrompt(prompt_token_ids=request.tokens), params=None, lora_request=lora_request, ) prompt_input = await self._tokenize_prompt_input_async( request, tokenizer, request.tokens, ) input_text = prompt_input["prompt"] return DetokenizeResponse(prompt=input_text) async def get_tokenizer_info( self, ) -> TokenizerInfoResponse | ErrorResponse: """Get comprehensive tokenizer information.""" try: tokenizer = await self.engine_client.get_tokenizer() info = TokenizerInfo(tokenizer, self.chat_template).to_dict() return TokenizerInfoResponse(**info) except Exception as e: return self.create_error_response(f"Failed to get tokenizer info: {str(e)}") def _build_render_config(self, request: TokenizeRequest) -> RenderConfig: return RenderConfig(add_special_tokens=request.add_special_tokens) @dataclass class TokenizerInfo: tokenizer: TokenizerLike chat_template: str | None def to_dict(self) -> dict[str, Any]: """Return the tokenizer configuration.""" return self._get_tokenizer_config() def _get_tokenizer_config(self) -> dict[str, Any]: """Get tokenizer configuration directly from the tokenizer object.""" config = dict(getattr(self.tokenizer, "init_kwargs", None) or {}) # Remove file path fields config.pop("vocab_file", None) config.pop("merges_file", None) config = self._make_json_serializable(config) config["tokenizer_class"] = type(self.tokenizer).__name__ if self.chat_template: config["chat_template"] = self.chat_template return config def _make_json_serializable(self, obj): """Convert any non-JSON-serializable objects to serializable format.""" if hasattr(obj, "content"): return obj.content elif isinstance(obj, dict): return {k: self._make_json_serializable(v) for k, v in obj.items()} elif isinstance(obj, list): return [self._make_json_serializable(item) for item in obj] else: return obj
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/tokenize/__init__.py
vllm/entrypoints/serve/tokenize/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/entrypoints/serve/tokenize/api_router.py
vllm/entrypoints/serve/tokenize/api_router.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from http import HTTPStatus from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from typing_extensions import assert_never from vllm.entrypoints.openai.api_server import validate_json_request from vllm.entrypoints.openai.protocol import ( DetokenizeRequest, DetokenizeResponse, ErrorResponse, TokenizeRequest, TokenizeResponse, ) from vllm.entrypoints.serve.tokenize.serving import OpenAIServingTokenization from vllm.entrypoints.utils import ( with_cancellation, ) from vllm.logger import init_logger logger = init_logger(__name__) def tokenization(request: Request) -> OpenAIServingTokenization: return request.app.state.openai_serving_tokenization router = APIRouter() @router.post( "/tokenize", dependencies=[Depends(validate_json_request)], responses={ HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse}, HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse}, HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse}, HTTPStatus.NOT_IMPLEMENTED.value: {"model": ErrorResponse}, }, ) @with_cancellation async def tokenize(request: TokenizeRequest, raw_request: Request): handler = tokenization(raw_request) try: generator = await handler.create_tokenize(request, raw_request) except NotImplementedError as e: raise HTTPException( status_code=HTTPStatus.NOT_IMPLEMENTED.value, detail=str(e) ) from e except Exception as e: raise HTTPException( status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e) ) from e if isinstance(generator, ErrorResponse): return JSONResponse( content=generator.model_dump(), status_code=generator.error.code ) elif isinstance(generator, TokenizeResponse): return JSONResponse(content=generator.model_dump()) assert_never(generator) @router.post( "/detokenize", dependencies=[Depends(validate_json_request)], responses={ HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse}, HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse}, HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse}, }, ) @with_cancellation async def detokenize(request: DetokenizeRequest, raw_request: Request): handler = tokenization(raw_request) try: generator = await handler.create_detokenize(request, raw_request) except OverflowError as e: raise RequestValidationError(errors=[str(e)]) from e except Exception as e: raise HTTPException( status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e) ) from e if isinstance(generator, ErrorResponse): return JSONResponse( content=generator.model_dump(), status_code=generator.error.code ) elif isinstance(generator, DetokenizeResponse): return JSONResponse(content=generator.model_dump()) assert_never(generator) def attach_router(app: FastAPI): if getattr(app.state.args, "enable_tokenizer_info_endpoint", False): """Conditionally register the tokenizer info endpoint if enabled.""" @router.get("/tokenizer_info") async def get_tokenizer_info(raw_request: Request): """Get comprehensive tokenizer information.""" result = await tokenization(raw_request).get_tokenizer_info() return JSONResponse( content=result.model_dump(), status_code=result.error.code if isinstance(result, ErrorResponse) else 200, ) app.include_router(router)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/serial_utils.py
vllm/v1/serial_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import dataclasses import importlib import pickle from collections.abc import Callable, Sequence from functools import partial from inspect import isclass from types import FunctionType from typing import Any, TypeAlias, get_type_hints import cloudpickle import msgspec import numpy as np import torch import zmq from msgspec import msgpack from pydantic import GetCoreSchemaHandler from pydantic_core import core_schema from vllm import envs from vllm.logger import init_logger from vllm.multimodal.inputs import ( BaseMultiModalField, MultiModalBatchedField, MultiModalFieldConfig, MultiModalFieldElem, MultiModalFlatField, MultiModalKwargsItem, MultiModalKwargsItems, MultiModalSharedField, NestedTensors, ) from vllm.utils.platform_utils import is_pin_memory_available from vllm.v1.utils import tensor_data logger = init_logger(__name__) CUSTOM_TYPE_PICKLE = 1 CUSTOM_TYPE_CLOUDPICKLE = 2 CUSTOM_TYPE_RAW_VIEW = 3 # MultiModalField class serialization type map. # These need to list all possible field types and match them # to factory methods in `MultiModalFieldConfig`. MMF_CLASS_TO_FACTORY: dict[type[BaseMultiModalField], str] = { MultiModalFlatField: "flat", MultiModalSharedField: "shared", MultiModalBatchedField: "batched", } bytestr: TypeAlias = bytes | bytearray | memoryview | zmq.Frame def _log_insecure_serialization_warning(): logger.warning_once( "Allowing insecure serialization using pickle due to " "VLLM_ALLOW_INSECURE_SERIALIZATION=1" ) def _typestr(val: Any) -> tuple[str, str] | None: if val is None: return None t = type(val) return t.__module__, t.__qualname__ def _encode_type_info_recursive(obj: Any) -> Any: """Recursively encode type information for nested structures of lists/dicts.""" if obj is None: return None if type(obj) is list: return [_encode_type_info_recursive(item) for item in obj] if type(obj) is dict: return {k: _encode_type_info_recursive(v) for k, v in obj.items()} return _typestr(obj) def _decode_type_info_recursive( type_info: Any, data: Any, convert_fn: Callable[[Sequence[str], Any], Any] ) -> Any: """Recursively decode type information for nested structures of lists/dicts.""" if type_info is None: return data if isinstance(type_info, dict): assert isinstance(data, dict) return { k: _decode_type_info_recursive(type_info[k], data[k], convert_fn) for k in type_info } if isinstance(type_info, list) and ( # Exclude serialized tensors/numpy arrays. len(type_info) != 2 or not isinstance(type_info[0], str) ): assert isinstance(data, list) return [ _decode_type_info_recursive(ti, d, convert_fn) for ti, d in zip(type_info, data) ] return convert_fn(type_info, data) class UtilityResult: """Wrapper for special handling when serializing/deserializing.""" def __init__(self, r: Any = None): self.result = r class MsgpackEncoder: """Encoder with custom torch tensor and numpy array serialization. Note that unlike vanilla `msgspec` Encoders, this interface is generally not thread-safe when encoding tensors / numpy arrays. By default, arrays below 256B are serialized inline Larger will get sent via dedicated messages. Note that this is a per-tensor limit. """ def __init__(self, size_threshold: int | None = None): if size_threshold is None: size_threshold = envs.VLLM_MSGPACK_ZERO_COPY_THRESHOLD self.encoder = msgpack.Encoder(enc_hook=self.enc_hook) # This is used as a local stash of buffers that we can then access from # our custom `msgspec` hook, `enc_hook`. We don't have a way to # pass custom data to the hook otherwise. self.aux_buffers: list[bytestr] | None = None self.size_threshold = size_threshold if envs.VLLM_ALLOW_INSECURE_SERIALIZATION: _log_insecure_serialization_warning() def encode(self, obj: Any) -> Sequence[bytestr]: try: self.aux_buffers = bufs = [b""] bufs[0] = self.encoder.encode(obj) # This `bufs` list allows us to collect direct pointers to backing # buffers of tensors and np arrays, and return them along with the # top-level encoded buffer instead of copying their data into the # new buffer. return bufs finally: self.aux_buffers = None def encode_into(self, obj: Any, buf: bytearray) -> Sequence[bytestr]: try: self.aux_buffers = [buf] bufs = self.aux_buffers self.encoder.encode_into(obj, buf) return bufs finally: self.aux_buffers = None def enc_hook(self, obj: Any) -> Any: if isinstance(obj, torch.Tensor): return self._encode_tensor(obj) # Fall back to pickle for object or void kind ndarrays. if isinstance(obj, np.ndarray) and obj.dtype.kind not in ("O", "V"): return self._encode_ndarray(obj) if isinstance(obj, slice): # We are assuming only int-based values will be used here. return tuple( int(v) if v is not None else None for v in (obj.start, obj.stop, obj.step) ) if isinstance(obj, MultiModalKwargsItem): return self._encode_mm_item(obj) if isinstance(obj, MultiModalKwargsItems): return self._encode_mm_items(obj) if isinstance(obj, UtilityResult): result = obj.result if not envs.VLLM_ALLOW_INSECURE_SERIALIZATION: return None, result # Since utility results are not strongly typed, we recursively # encode type information for nested structures of lists/dicts # to help with correct msgspec deserialization. return _encode_type_info_recursive(result), result if not envs.VLLM_ALLOW_INSECURE_SERIALIZATION: raise TypeError( f"Object of type {type(obj)} is not serializable" "Set VLLM_ALLOW_INSECURE_SERIALIZATION=1 to allow " "fallback to pickle-based serialization." ) if isinstance(obj, FunctionType): # `pickle` is generally faster than cloudpickle, but can have # problems serializing methods. return msgpack.Ext(CUSTOM_TYPE_CLOUDPICKLE, cloudpickle.dumps(obj)) return msgpack.Ext( CUSTOM_TYPE_PICKLE, pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) ) def _encode_ndarray( self, obj: np.ndarray ) -> tuple[str, tuple[int, ...], int | memoryview]: assert self.aux_buffers is not None # If the array is non-contiguous, we need to copy it first arr_data = obj.data if obj.flags.c_contiguous else obj.tobytes() if not obj.shape or obj.nbytes < self.size_threshold: # Encode small arrays and scalars inline. Using this extension type # ensures we can avoid copying when decoding. data = msgpack.Ext(CUSTOM_TYPE_RAW_VIEW, arr_data) else: # Otherwise encode index of backing buffer to avoid copy. data = len(self.aux_buffers) self.aux_buffers.append(arr_data) # We serialize the ndarray as a tuple of native types. # The data is either inlined if small, or an index into a list of # backing buffers that we've stashed in `aux_buffers`. return obj.dtype.str, obj.shape, data def _encode_tensor( self, obj: torch.Tensor ) -> tuple[str, tuple[int, ...], int | memoryview]: assert self.aux_buffers is not None # view the tensor as a contiguous 1D array of bytes arr_data = tensor_data(obj) if obj.nbytes < self.size_threshold: # Smaller tensors are encoded inline, just like ndarrays. data = msgpack.Ext(CUSTOM_TYPE_RAW_VIEW, arr_data) else: # Otherwise encode index of backing buffer to avoid copy. data = len(self.aux_buffers) self.aux_buffers.append(arr_data) dtype = str(obj.dtype).removeprefix("torch.") return dtype, obj.shape, data def _encode_mm_items(self, items: MultiModalKwargsItems) -> dict[str, Any]: return { modality: [self._encode_mm_item(item) for item in itemlist] for modality, itemlist in items.items() } def _encode_mm_item(self, item: MultiModalKwargsItem) -> list[dict[str, Any]]: return [self._encode_mm_field_elem(elem) for elem in item.values()] def _encode_mm_field_elem(self, elem: MultiModalFieldElem) -> dict[str, Any]: return { "modality": elem.modality, "key": elem.key, "data": ( None if elem.data is None else self._encode_nested_tensors(elem.data) ), "field": self._encode_mm_field(elem.field), } def _encode_nested_tensors(self, nt: NestedTensors) -> Any: if isinstance(nt, torch.Tensor): return self._encode_tensor(nt) if isinstance(nt, (int, float)): # Although it violates NestedTensors type, MultiModalKwargs # values are sometimes floats. return nt return [self._encode_nested_tensors(x) for x in nt] def _encode_mm_field(self, field: BaseMultiModalField): # Figure out the factory name for the field type. name = MMF_CLASS_TO_FACTORY.get(field.__class__) if not name: raise TypeError(f"Unsupported field type: {field.__class__}") # We just need to copy all of the field values in order # which will be then used to reconstruct the field. factory_kw = {f.name: getattr(field, f.name) for f in dataclasses.fields(field)} return name, factory_kw class MsgpackDecoder: """Decoder with custom torch tensor and numpy array serialization. Note that unlike vanilla `msgspec` Decoders, this interface is generally not thread-safe when encoding tensors / numpy arrays. """ def __init__(self, t: Any | None = None, share_mem: bool = True): self.share_mem = share_mem self.pin_tensors = is_pin_memory_available() args = () if t is None else (t,) self.decoder = msgpack.Decoder( *args, ext_hook=self.ext_hook, dec_hook=self.dec_hook ) self.aux_buffers: Sequence[bytestr] = () if envs.VLLM_ALLOW_INSECURE_SERIALIZATION: _log_insecure_serialization_warning() def decode(self, bufs: bytestr | Sequence[bytestr]) -> Any: if isinstance(bufs, bytestr): # type: ignore return self.decoder.decode(bufs) self.aux_buffers = bufs try: return self.decoder.decode(bufs[0]) finally: self.aux_buffers = () def dec_hook(self, t: type, obj: Any) -> Any: # Given native types in `obj`, convert to type `t`. if isclass(t): if issubclass(t, np.ndarray): return self._decode_ndarray(obj) if issubclass(t, torch.Tensor): return self._decode_tensor(obj) if t is slice: return slice(*obj) if issubclass(t, MultiModalKwargsItem): return self._decode_mm_item(obj) if issubclass(t, MultiModalKwargsItems): return self._decode_mm_items(obj) if t is UtilityResult: return self._decode_utility_result(obj) return obj def _decode_utility_result(self, obj: Any) -> UtilityResult: result_type, result = obj if result_type is not None: if not envs.VLLM_ALLOW_INSECURE_SERIALIZATION: raise TypeError( "VLLM_ALLOW_INSECURE_SERIALIZATION must " "be set to use custom utility result types" ) # Use recursive decoding to handle nested structures result = _decode_type_info_recursive( result_type, result, self._convert_result ) return UtilityResult(result) def _convert_result(self, result_type: Sequence[str], result: Any) -> Any: if result_type is None: return result mod_name, name = result_type mod = importlib.import_module(mod_name) result_type = getattr(mod, name) return msgspec.convert(result, result_type, dec_hook=self.dec_hook) def _decode_ndarray(self, arr: Any) -> np.ndarray: dtype, shape, data = arr # zero-copy decode. We assume the ndarray will not be kept around, # as it now locks the whole received message buffer in memory. buffer = self.aux_buffers[data] if isinstance(data, int) else data arr = np.frombuffer(buffer, dtype=dtype) if not self.share_mem: arr = arr.copy() return arr.reshape(shape) def _decode_tensor(self, arr: Any) -> torch.Tensor: dtype, shape, data = arr is_aux = isinstance(data, int) buffer = self.aux_buffers[data] if is_aux else data buffer = buffer if isinstance(buffer, memoryview) else memoryview(buffer) torch_dtype = getattr(torch, dtype) assert isinstance(torch_dtype, torch.dtype) if not buffer.nbytes: # torch.frombuffer doesn't like empty buffers assert 0 in shape return torch.empty(shape, dtype=torch_dtype) # Create uint8 array arr = torch.frombuffer(buffer, dtype=torch.uint8) # Clone ensures tensor is backed by pytorch-owned memory for safe # future async CPU->GPU transfer. # Pin larger tensors for more efficient CPU->GPU transfer. if not is_aux: arr = arr.clone() elif not self.share_mem: arr = arr.pin_memory() if self.pin_tensors else arr.clone() # Convert back to proper shape & type return arr.view(torch_dtype).view(shape) def _decode_mm_items(self, obj: dict[str, Any]) -> MultiModalKwargsItems: return MultiModalKwargsItems( { modality: [self._decode_mm_item(item) for item in itemlist] for modality, itemlist in obj.items() } ) def _decode_mm_item(self, obj: list[Any]) -> MultiModalKwargsItem: return MultiModalKwargsItem.from_elems( [self._decode_mm_field_elem(v) for v in obj] ) def _decode_mm_field_elem(self, obj: dict[str, Any]) -> MultiModalFieldElem: if obj["data"] is not None: obj["data"] = self._decode_nested_tensors(obj["data"]) # Reconstruct the field processor using MultiModalFieldConfig factory_meth_name, factory_kw = obj["field"] factory_meth = getattr(MultiModalFieldConfig, factory_meth_name) # Special case: decode the union "slices" field of # MultiModalFlatField if factory_meth_name == "flat": factory_kw["slices"] = self._decode_nested_slices(factory_kw["slices"]) obj["field"] = factory_meth("", **factory_kw).field return MultiModalFieldElem(**obj) def _decode_nested_tensors(self, obj: Any) -> NestedTensors: if isinstance(obj, (int, float)): # Although it violates NestedTensors type, MultiModalKwargs # values are sometimes floats. return obj if not isinstance(obj, list): raise TypeError(f"Unexpected NestedTensors contents: {type(obj)}") if obj and isinstance(obj[0], str): return self._decode_tensor(obj) return [self._decode_nested_tensors(x) for x in obj] def _decode_nested_slices(self, obj: Any) -> Any: assert isinstance(obj, (list, tuple)) if obj and not isinstance(obj[0], (list, tuple)): return slice(*obj) return [self._decode_nested_slices(x) for x in obj] def ext_hook(self, code: int, data: memoryview) -> Any: if code == CUSTOM_TYPE_RAW_VIEW: return data if envs.VLLM_ALLOW_INSECURE_SERIALIZATION: if code == CUSTOM_TYPE_PICKLE: return pickle.loads(data) if code == CUSTOM_TYPE_CLOUDPICKLE: return cloudpickle.loads(data) raise NotImplementedError(f"Extension type code {code} is not supported") def run_method( obj: Any, method: str | bytes | Callable, args: tuple[Any, ...], kwargs: dict[str, Any], ) -> Any: """ Run a method of an object with the given arguments and keyword arguments. If the method is string, it will be converted to a method using getattr. If the method is serialized bytes and will be deserialized using cloudpickle. If the method is a callable, it will be called directly. """ if isinstance(method, bytes): func = partial(cloudpickle.loads(method), obj) elif isinstance(method, str): try: func = getattr(obj, method) except AttributeError: raise NotImplementedError( f"Method {method!r} is not implemented." ) from None else: func = partial(method, obj) # type: ignore return func(*args, **kwargs) class PydanticMsgspecMixin: @classmethod def __get_pydantic_core_schema__( cls, source_type: Any, handler: GetCoreSchemaHandler ) -> core_schema.CoreSchema: """ Make msgspec.Struct compatible with Pydantic, respecting defaults. Handle JSON=>msgspec.Struct. Used when exposing msgspec.Struct to the API as input or in `/docs`. Note this is cached by Pydantic and not called on every validation. """ msgspec_fields = {f.name: f for f in msgspec.structs.fields(source_type)} type_hints = get_type_hints(source_type) # Build the Pydantic typed_dict_field for each msgspec field fields = {} for name, hint in type_hints.items(): msgspec_field = msgspec_fields[name] # typed_dict_field using the handler to get the schema field_schema = handler(hint) # Add default value to the schema. if msgspec_field.default_factory is not msgspec.NODEFAULT: wrapped_schema = core_schema.with_default_schema( schema=field_schema, default_factory=msgspec_field.default_factory, ) fields[name] = core_schema.typed_dict_field(wrapped_schema) elif msgspec_field.default is not msgspec.NODEFAULT: wrapped_schema = core_schema.with_default_schema( schema=field_schema, default=msgspec_field.default, ) fields[name] = core_schema.typed_dict_field(wrapped_schema) else: # No default, so Pydantic will treat it as required fields[name] = core_schema.typed_dict_field(field_schema) return core_schema.no_info_after_validator_function( cls._validate_msgspec, core_schema.typed_dict_schema(fields), ) @classmethod def _validate_msgspec(cls, value: Any) -> Any: """Validate and convert input to msgspec.Struct instance.""" if isinstance(value, cls): return value if isinstance(value, dict): return cls(**value) return msgspec.convert(value, type=cls)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/kv_cache_interface.py
vllm/v1/kv_cache_interface.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import copy from dataclasses import dataclass, fields, replace from math import prod import torch from typing_extensions import Self from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.utils.math_utils import cdiv from vllm.utils.torch_utils import get_dtype_size logger = init_logger(__name__) @dataclass(frozen=True) class KVCacheSpec: """ A base class for specifying the KV cache format of one layer. """ # number of tokens in a block block_size: int @property def page_size_bytes(self) -> int: """ The size of a page with `block_size` tokens in bytes. Returns: The page size """ raise NotImplementedError def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: """ The maximum possible memory usage of this KV cache in bytes. Returns: The KV cache size in bytes """ raise NotImplementedError def copy_with_new_block_size(self, block_size: int) -> Self: """ Create a new KVCacheSpec from self but replacing the block size. """ return replace(self, block_size=block_size) @classmethod def merge(cls, specs: list[Self]) -> Self: """ Merge a list of KVCacheSpec objects into a single KVCacheSpec object. """ assert all(spec == specs[0] for spec in specs[1:]), ( "All layers in the same KV cache group must be the same." ) return copy.deepcopy(specs[0]) @dataclass(frozen=True) class AttentionSpec(KVCacheSpec): num_kv_heads: int head_size: int dtype: torch.dtype @property def page_size_bytes(self) -> int: return ( 2 * self.block_size * self.num_kv_heads * self.head_size * get_dtype_size(self.dtype) ) @dataclass(frozen=True) class FullAttentionSpec(AttentionSpec): """ When hybrid allocator is disabled and the model contains both full attention layers and sliding window attention layers, sliding window attention are regarded as full attention in KV cache manager (blocks are allocated for all tokens), while computed as sliding window attention in model runner. In this case, we use FullAttentionSpec and record the sliding window size. """ head_size_v: int | None = None sliding_window: int | None = None """ Default to None for not using sliding window attention. """ attention_chunk_size: int | None = None def __post_init__(self): if self.head_size_v is None: object.__setattr__(self, "head_size_v", self.head_size) def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: max_model_len = vllm_config.model_config.max_model_len dcp_world_size = vllm_config.parallel_config.decode_context_parallel_size pcp_world_size = vllm_config.parallel_config.prefill_context_parallel_size # Note(hc): each dcp rank only need save # (max_model_len//dcp_world_size) tokens locally. if dcp_world_size * pcp_world_size > 1: max_model_len = cdiv(max_model_len, dcp_world_size * pcp_world_size) return cdiv(max_model_len, self.block_size) * self.page_size_bytes @classmethod def merge_window_sizes(cls, window_sizes: set[int]) -> int | None: if len(window_sizes) == 0: return None elif len(window_sizes) == 1: return window_sizes.pop() else: raise ValueError( "All attention layers in the same KV cache group must have the " "same window size." ) @classmethod def merge(cls, specs: list[Self]) -> Self: """ Merge a list of FullAttentionSpec objects into a single FullAttentionSpec object. """ assert all(isinstance(spec, FullAttentionSpec) for spec in specs), ( "All attention layers in the same KV cache group must be FullAttentionSpec." ) sliding_window = set( spec.sliding_window for spec in specs if spec.sliding_window is not None ) attention_chunk_size = set( spec.attention_chunk_size for spec in specs if spec.attention_chunk_size is not None ) assert not any(isinstance(spec, MLAAttentionSpec) for spec in specs), ( "MLAAttentionSpec should be merged in MLAAttentionSpec.merge" ) merged_spec = cls( block_size=specs[0].block_size, num_kv_heads=specs[0].num_kv_heads, head_size=specs[0].head_size, head_size_v=specs[0].head_size_v, dtype=specs[0].dtype, sliding_window=cls.merge_window_sizes(sliding_window), attention_chunk_size=cls.merge_window_sizes(attention_chunk_size), ) for spec in specs: for f in fields(AttentionSpec): assert getattr(spec, f.name) == getattr(merged_spec, f.name), ( "All attention layers in the same KV cache group must have " "the same attention spec." ) assert (merged_spec.sliding_window is not None) + ( merged_spec.attention_chunk_size is not None ) <= 1, ( "Model with both sliding window layers and chunked local attention " "layers is not supported." ) return merged_spec @property def page_size_bytes(self) -> int: return ( self.block_size * self.num_kv_heads * (self.head_size + self.head_size_v) * get_dtype_size(self.dtype) ) @dataclass(frozen=True) class MLAAttentionSpec(FullAttentionSpec): # TODO(Lucas/Chen): less hacky way to do this cache_dtype_str: str | None = None @property def page_size_bytes(self) -> int: if self.cache_dtype_str == "fp8_ds_mla": # See `vllm/v1/attention/backends/mla/flashmla_sparse.py` # for details. return self.block_size * 656 return ( self.block_size * self.num_kv_heads * self.head_size * get_dtype_size(self.dtype) ) @classmethod def merge(cls, specs: list[Self]) -> Self: assert all(isinstance(spec, MLAAttentionSpec) for spec in specs), ( "All attention layers in the same KV cache group must be MLAAttentionSpec." ) cache_dtype_str_set = set(spec.cache_dtype_str for spec in specs) assert len(cache_dtype_str_set) == 1, ( "All attention layers in the same KV cache group must use the same " "quantization method." ) return cls( block_size=specs[0].block_size, num_kv_heads=specs[0].num_kv_heads, head_size=specs[0].head_size, dtype=specs[0].dtype, cache_dtype_str=cache_dtype_str_set.pop(), ) @dataclass(frozen=True) class ChunkedLocalAttentionSpec(AttentionSpec): attention_chunk_size: int def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: max_model_len = vllm_config.model_config.max_model_len max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens # During chunked prefill, we allocate KV cache for at most # `self.attention_chunk_size` computed tokens plus the newly scheduled # tokens. And we won't allocate KV cache for more than `max_model_len` # tokens. num_tokens = min( self.attention_chunk_size + max_num_batched_tokens, max_model_len ) return cdiv(num_tokens, self.block_size) * self.page_size_bytes @dataclass(frozen=True) class SlidingWindowSpec(AttentionSpec): sliding_window: int def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: assert vllm_config.parallel_config.decode_context_parallel_size == 1, ( "DCP not support sliding window." ) max_model_len = vllm_config.model_config.max_model_len max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens # During chunked prefill, we allocate KV cache for the last # `self.sliding_window-1` computed tokens plus the newly scheduled # tokens. And we won't allocate KV cache for more than `max_model_len` # tokens. num_tokens = min( self.sliding_window - 1 + max_num_batched_tokens, max_model_len ) # +1 here because the sliding window may not start from the beginning # of the block. For example, if the block size is 4 and num_token # is 4, we need two blocks [XXCD] [EF] to store the sliding # window [CDEF] of 6 tokens. return (cdiv(num_tokens, self.block_size) + 1) * self.page_size_bytes @dataclass(frozen=True) class MambaSpec(KVCacheSpec): shapes: tuple[tuple[int, ...], ...] dtypes: tuple[torch.dtype] page_size_padded: int | None = None mamba_type: str = "mamba2" num_speculative_blocks: int = 0 @property def page_size_bytes(self) -> int: page_size = sum( prod(shape) * get_dtype_size(dtype) for (shape, dtype) in zip(self.shapes, self.dtypes) ) if self.page_size_padded is not None: assert self.page_size_padded >= page_size return self.page_size_padded return page_size def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: max_model_len = vllm_config.model_config.max_model_len return cdiv(max_model_len, self.block_size) * self.page_size_bytes @dataclass(frozen=True) class EncoderOnlyAttentionSpec(AttentionSpec): def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: # Encoder-only layers do not need KV cache return 0 @dataclass(frozen=True) class CrossAttentionSpec(AttentionSpec): """ KV cache spec for cross-attention layers in encoder-decoder models. """ def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: # For cross-attention, we need to cache encoder states # Get encoder length (e.g., 1500 for Whisper). max_encoder_len = vllm_config.scheduler_config.max_num_encoder_input_tokens return cdiv(max_encoder_len, self.block_size) * self.page_size_bytes @dataclass(frozen=True) class SinkFullAttentionSpec(FullAttentionSpec): sink_len: int | None = None @classmethod def merge(cls, specs: list[Self]) -> Self: """ Merge a list of FullAttentionSpec objects into a single FullAttentionSpec object. """ assert all(isinstance(spec, FullAttentionSpec) for spec in specs), ( "All attention layers in the same KV cache group must be FullAttentionSpec." ) sliding_window = set( spec.sliding_window for spec in specs if spec.sliding_window is not None ) attention_chunk_size = set( spec.attention_chunk_size for spec in specs if spec.attention_chunk_size is not None ) assert not any(isinstance(spec, MLAAttentionSpec) for spec in specs), ( "MLAAttentionSpec should be merged in MLAAttentionSpec.merge" ) merged_spec = cls( block_size=specs[0].block_size, num_kv_heads=specs[0].num_kv_heads, head_size=specs[0].head_size, head_size_v=specs[0].head_size_v, sink_len=specs[0].sink_len, dtype=specs[0].dtype, sliding_window=cls.merge_window_sizes(sliding_window), attention_chunk_size=cls.merge_window_sizes(attention_chunk_size), ) for spec in specs: for f in fields(AttentionSpec): assert getattr(spec, f.name) == getattr(merged_spec, f.name), ( "All attention layers in the same KV cache group must have " "the same attention spec." ) assert (merged_spec.sliding_window is not None) + ( merged_spec.attention_chunk_size is not None ) <= 1, ( "Model with both sliding window layers and chunked local attention " "layers is not supported." ) return merged_spec @dataclass(frozen=True) class UniformTypeKVCacheSpecs(KVCacheSpec): """ A KV cache spec for multiple layers with the same type of attention. Here, same types means always need the same number of token slots. For example, sliding window attentions with different window sizes are not the same type and should not be merged into one UniformTypeKVCacheSpecs. """ kv_cache_specs: dict[str, KVCacheSpec] @property def page_size_bytes(self) -> int: return sum(spec.page_size_bytes for spec in self.kv_cache_specs.values()) def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: max_num_pages = max( cdiv(spec.max_memory_usage_bytes(vllm_config), spec.page_size_bytes) for spec in self.kv_cache_specs.values() ) return max_num_pages * self.page_size_bytes @classmethod def is_uniform_type(cls, kv_cache_specs: dict[str, KVCacheSpec]) -> bool: """ Whether all layers have the same type of KV cache spec. """ block_sizes = set(spec.block_size for spec in kv_cache_specs.values()) if len(block_sizes) > 1: # Different block sizes, not uniform. return False one_spec = next(iter(kv_cache_specs.values())) if isinstance(one_spec, FullAttentionSpec): return all( isinstance(spec, FullAttentionSpec) for spec in kv_cache_specs.values() ) elif isinstance(one_spec, CrossAttentionSpec): return all( isinstance(spec, CrossAttentionSpec) for spec in kv_cache_specs.values() ) elif isinstance(one_spec, SlidingWindowSpec): return all( isinstance(spec, SlidingWindowSpec) and spec.sliding_window == one_spec.sliding_window for spec in kv_cache_specs.values() ) elif isinstance(one_spec, ChunkedLocalAttentionSpec): return all( isinstance(spec, ChunkedLocalAttentionSpec) and spec.attention_chunk_size == one_spec.attention_chunk_size for spec in kv_cache_specs.values() ) elif isinstance(one_spec, MambaSpec): return all( isinstance(spec, MambaSpec) and spec.num_speculative_blocks == one_spec.num_speculative_blocks for spec in kv_cache_specs.values() ) else: # NOTE(Chen): Please add new branches for new KV cache spec types. raise NotImplementedError( f"Unsupported KV cache spec type: {type(one_spec)}" ) @classmethod def from_specs(cls, kv_cache_specs: dict[str, KVCacheSpec]) -> Self | None: """ Return a SameTypeKVCacheSpecs object if all layers have the same type of KV cache spec. Return None if not. """ if cls.is_uniform_type(kv_cache_specs): block_size = next(iter(kv_cache_specs.values())).block_size return cls(block_size=block_size, kv_cache_specs=kv_cache_specs) else: return None @dataclass class KVCacheTensor: """ A class for specifying how the workers should initialize the KV cache. """ size: int # size of the KV cache tensor in bytes shared_by: list[str] # layer names that share the same KV cache tensor @dataclass class KVCacheGroupSpec: """ Represents a group of model layers that share the same KV cache block table. These layers are regarded as one layer in the KV cache manager. """ # The names of model layers in this group layer_names: list[str] # The KV cache spec of this manager layer kv_cache_spec: KVCacheSpec @dataclass class KVCacheConfig: """ The KV cache configuration of a model. """ num_blocks: int """The number of KV cache blocks""" kv_cache_tensors: list[KVCacheTensor] """How should model runner initialize the KV cache tensors for each layer""" kv_cache_groups: list[KVCacheGroupSpec] """ The kv cache groups of the model. For models with only one type of attention, there is only one group that contains all layers. For models with multiple types of attention, there will be multiple groups, see `_get_kv_cache_config_uniform_page_size` for more details. """
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/request.py
vllm/v1/request.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import enum import time from collections.abc import Callable, Mapping from functools import partial from typing import TYPE_CHECKING, Any, Optional import torch from vllm.multimodal.inputs import MultiModalFeatureSpec from vllm.pooling_params import PoolingParams from vllm.sampling_params import SamplingParams from vllm.utils import length_from_prompt_token_ids_or_embeds from vllm.v1.engine import ( EngineCoreEvent, EngineCoreEventType, EngineCoreRequest, FinishReason, ) from vllm.v1.structured_output.request import StructuredOutputRequest from vllm.v1.utils import ConstantList if TYPE_CHECKING: from vllm.lora.request import LoRARequest from vllm.v1.core.kv_cache_utils import BlockHash class Request: def __init__( self, request_id: str, prompt_token_ids: list[int] | None, sampling_params: SamplingParams | None, pooling_params: PoolingParams | None, eos_token_id: int | None, client_index: int = 0, arrival_time: float | None = None, prompt_embeds: torch.Tensor | None = None, mm_features: list[MultiModalFeatureSpec] | None = None, lora_request: Optional["LoRARequest"] = None, cache_salt: str | None = None, priority: int = 0, trace_headers: Mapping[str, str] | None = None, block_hasher: Callable[["Request"], list["BlockHash"]] | None = None, ) -> None: self.request_id = request_id self.client_index = client_index self.priority = priority self.sampling_params = sampling_params self.pooling_params = pooling_params # Because of LoRA, the eos token id can be different for each request. self.eos_token_id = eos_token_id self.lora_request = lora_request self.structured_output_request = StructuredOutputRequest.from_sampling_params( sampling_params ) self.arrival_time = arrival_time if arrival_time is not None else time.time() self.status = RequestStatus.WAITING self.events: list[EngineCoreEvent] = [] self.stop_reason: int | str | None = None # P/D: Connector-specific KV transfer parameters. self.kv_transfer_params: dict[str, Any] | None = None if pooling_params is not None: # Pooling models. self.max_tokens = 1 elif sampling_params is not None: # Generative models. assert sampling_params.max_tokens is not None self.max_tokens = sampling_params.max_tokens if self.structured_output_request is not None: self.status = RequestStatus.WAITING_FOR_FSM if sampling_params.extra_args is not None: self.kv_transfer_params = sampling_params.extra_args.get( "kv_transfer_params" ) else: raise ValueError("sampling_params and pooling_params can't both be unset") self.prompt_token_ids = prompt_token_ids self.prompt_embeds = prompt_embeds self.num_prompt_tokens = length_from_prompt_token_ids_or_embeds( prompt_token_ids, prompt_embeds ) self._output_token_ids: list[int] = [] self._all_token_ids: list[int] = ( self.prompt_token_ids.copy() if self.prompt_token_ids is not None else [0] * self.num_prompt_tokens ) # Used in async scheduling. self.num_output_placeholders = 0 # Used in forced preemption (reset_prefix_cache) with async scheduling. self.discard_latest_async_tokens = False self.spec_token_ids: list[int] = [] self.num_computed_tokens = 0 self.cache_salt: str | None = cache_salt # Multi-modal related self.mm_features = mm_features or [] self.num_encoder_inputs = len(self.mm_features) self.has_encoder_inputs = self.num_encoder_inputs > 0 # Read-only views # Prevent directly appending to these lists since # they should also be updated simultaneously. self.output_token_ids = ConstantList(self._output_token_ids) self.all_token_ids = ConstantList(self._all_token_ids) # trace_headers self.trace_headers = trace_headers # State # The number of tokens with prefix cache hits. self.num_cached_tokens = -1 # The number of NaNs in logits. A value greater than 0 # indicates that the output is corrupted self.num_nans_in_logits = 0 # The number of requests being preempted by the scheduler self.num_preemptions = 0 # The number of tokens that have been computed remotely. self.num_external_computed_tokens = 0 self.block_hashes: list[BlockHash] = [] self.get_hash_new_full_blocks: Callable[[], list[BlockHash]] | None = None if block_hasher is not None: self.get_hash_new_full_blocks = partial(block_hasher, self) self.block_hashes = self.get_hash_new_full_blocks() self.skip_reading_prefix_cache = self.get_skip_reading_prefix_cache() @classmethod def from_engine_core_request( cls, request: EngineCoreRequest, block_hasher: Callable[["Request"], list["BlockHash"]] | None, ) -> "Request": return cls( request_id=request.request_id, client_index=request.client_index, prompt_token_ids=request.prompt_token_ids, prompt_embeds=request.prompt_embeds, mm_features=request.mm_features, sampling_params=request.sampling_params, pooling_params=request.pooling_params, eos_token_id=request.eos_token_id, arrival_time=request.arrival_time, lora_request=request.lora_request, cache_salt=request.cache_salt, priority=request.priority, trace_headers=request.trace_headers, block_hasher=block_hasher, ) def append_output_token_ids( self, token_ids: int | list[int], ) -> None: if isinstance(token_ids, int): self._output_token_ids.append(token_ids) self._all_token_ids.append(token_ids) else: self._output_token_ids.extend(token_ids) self._all_token_ids.extend(token_ids) if self.get_hash_new_full_blocks is not None: self.block_hashes.extend(self.get_hash_new_full_blocks()) @property def use_structured_output(self) -> bool: return self.structured_output_request is not None @property def num_tokens(self) -> int: return len(self._all_token_ids) @property def num_tokens_with_spec(self) -> int: return len(self._all_token_ids) + len(self.spec_token_ids) @property def num_output_tokens(self) -> int: return len(self._output_token_ids) def get_skip_reading_prefix_cache(self) -> bool: if ( self.sampling_params is not None and self.sampling_params.skip_reading_prefix_cache is not None ): return self.sampling_params.skip_reading_prefix_cache elif ( self.pooling_params is not None and self.pooling_params.skip_reading_prefix_cache is not None ): return self.pooling_params.skip_reading_prefix_cache return False def is_finished(self) -> bool: return RequestStatus.is_finished(self.status) def get_finished_reason(self) -> FinishReason | None: return RequestStatus.get_finished_reason(self.status) def get_num_encoder_embeds(self, input_id: int) -> int: assert input_id < len(self.mm_features) return self.mm_features[input_id].mm_position.get_num_embeds def record_event( self, event_type: EngineCoreEventType, timestamp: float | None = None, ) -> None: self.events.append(EngineCoreEvent.new_event(event_type, timestamp)) def take_events(self) -> list[EngineCoreEvent] | None: if not self.events: return None events, self.events = self.events, [] return events def __lt__(self, other: "Request") -> bool: """ Compare two requests based on priority, arrival time, and request ID. Used in priority scheduling. """ if self.priority != other.priority: return self.priority < other.priority if self.arrival_time != other.arrival_time: return self.arrival_time < other.arrival_time if self.request_id != other.request_id: return self.request_id < other.request_id return id(self) < id(other) class RequestStatus(enum.IntEnum): """Status of a request.""" WAITING = enum.auto() WAITING_FOR_FSM = enum.auto() WAITING_FOR_REMOTE_KVS = enum.auto() RUNNING = enum.auto() PREEMPTED = enum.auto() # Note: anything after PREEMPTED will be considered # as a finished status. FINISHED_STOPPED = enum.auto() FINISHED_LENGTH_CAPPED = enum.auto() FINISHED_ABORTED = enum.auto() FINISHED_IGNORED = enum.auto() FINISHED_ERROR = enum.auto() def __str__(self): return self.name @staticmethod def is_finished(status: "RequestStatus") -> bool: return status > RequestStatus.PREEMPTED @staticmethod def get_finished_reason(status: "RequestStatus") -> FinishReason | None: return _FINISHED_REASON_MAP.get(status) # Mapping of finished statuses to their finish reasons. # NOTE: The ignored requests are the requests whose prompt lengths # are longer than the model's length cap. Therefore, the stop # reason should also be "length" as in OpenAI API. _FINISHED_REASON_MAP = { RequestStatus.FINISHED_STOPPED: FinishReason.STOP, RequestStatus.FINISHED_LENGTH_CAPPED: FinishReason.LENGTH, RequestStatus.FINISHED_ABORTED: FinishReason.ABORT, RequestStatus.FINISHED_IGNORED: FinishReason.LENGTH, RequestStatus.FINISHED_ERROR: FinishReason.ERROR, }
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/utils.py
vllm/v1/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import argparse import contextlib import multiprocessing import time import weakref from collections.abc import Callable, Sequence from contextlib import AbstractContextManager from multiprocessing import connection from multiprocessing.process import BaseProcess from typing import ( TYPE_CHECKING, Any, Generic, Optional, TypeVar, Union, overload, ) import torch from torch.autograd.profiler import record_function import vllm.envs as envs from vllm.logger import init_logger from vllm.usage.usage_lib import UsageContext, is_usage_stats_enabled, usage_message from vllm.utils.network_utils import get_open_port, get_open_zmq_ipc_path, get_tcp_uri from vllm.utils.system_utils import kill_process_tree if TYPE_CHECKING: import numpy as np from vllm.v1.engine.coordinator import DPCoordinator from vllm.v1.engine.utils import CoreEngineActorManager, CoreEngineProcManager logger = init_logger(__name__) T = TypeVar("T") class ConstantList(Generic[T], Sequence): def __init__(self, x: list[T]) -> None: self._x = x def append(self, item): raise TypeError("Cannot append to a constant list") def extend(self, item): raise TypeError("Cannot extend a constant list") def insert(self, item): raise TypeError("Cannot insert into a constant list") def pop(self, item): raise TypeError("Cannot pop from a constant list") def remove(self, item): raise TypeError("Cannot remove from a constant list") def clear(self): raise TypeError("Cannot clear a constant list") def index(self, item: T, start: int = 0, stop: int | None = None) -> int: return self._x.index(item, start, stop if stop is not None else len(self._x)) @overload def __getitem__(self, item: int) -> T: ... @overload def __getitem__(self, s: slice, /) -> list[T]: ... def __getitem__(self, item: int | slice) -> T | list[T]: return self._x[item] @overload def __setitem__(self, item: int, value: T): ... @overload def __setitem__(self, s: slice, value: T, /): ... def __setitem__(self, item: int | slice, value: T | list[T]): raise TypeError("Cannot set item in a constant list") def __delitem__(self, item): raise TypeError("Cannot delete item from a constant list") def __iter__(self): return iter(self._x) def __contains__(self, item): return item in self._x def __len__(self): return len(self._x) def __repr__(self): return f"ConstantList({self._x})" def copy(self) -> list[T]: return self._x.copy() class CpuGpuBuffer: """Buffer to easily copy tensors between CPU and GPU.""" def __init__( self, *size: int | torch.SymInt, dtype: torch.dtype, device: torch.device, pin_memory: bool, with_numpy: bool = True, ) -> None: self.cpu = torch.zeros(*size, dtype=dtype, device="cpu", pin_memory=pin_memory) self.gpu = torch.zeros_like(self.cpu, device=device) self.np: np.ndarray # To keep type hints simple (avoiding generics and subclasses), we # only conditionally create the numpy array attribute. This can cause # AttributeError if `self.np` is accessed when `with_numpy=False`. if with_numpy: if dtype == torch.bfloat16: raise ValueError( "Bfloat16 torch tensors cannot be directly cast to a " "numpy array, so call CpuGpuBuffer with with_numpy=False" ) self.np = self.cpu.numpy() def copy_to_gpu(self, n: int | None = None) -> torch.Tensor: if n is None: return self.gpu.copy_(self.cpu, non_blocking=True) return self.gpu[:n].copy_(self.cpu[:n], non_blocking=True) def copy_to_cpu(self, n: int | None = None) -> torch.Tensor: """NOTE: Because this method is non-blocking, explicit synchronization is needed to ensure the data is copied to CPU.""" if n is None: return self.cpu.copy_(self.gpu, non_blocking=True) return self.cpu[:n].copy_(self.gpu[:n], non_blocking=True) def get_engine_client_zmq_addr(local_only: bool, host: str, port: int = 0) -> str: """Assign a new ZMQ socket address. If local_only is True, participants are colocated and so a unique IPC address will be returned. Otherwise, the provided host and port will be used to construct a TCP address (port == 0 means assign an available port).""" return ( get_open_zmq_ipc_path() if local_only else (get_tcp_uri(host, port or get_open_port())) ) class APIServerProcessManager: """Manages a group of API server processes. Handles creation, monitoring, and termination of API server worker processes. Also monitors extra processes to check if they are healthy. """ def __init__( self, target_server_fn: Callable, listen_address: str, sock: Any, args: argparse.Namespace, num_servers: int, input_addresses: list[str], output_addresses: list[str], stats_update_address: str | None = None, ): """Initialize and start API server worker processes. Args: target_server_fn: Function to call for each API server process listen_address: Address to listen for client connections sock: Socket for client connections args: Command line arguments num_servers: Number of API server processes to start input_addresses: Input addresses for each API server output_addresses: Output addresses for each API server stats_update_address: Optional stats update address """ self.listen_address = listen_address self.sock = sock self.args = args # Start API servers spawn_context = multiprocessing.get_context("spawn") self.processes: list[BaseProcess] = [] for i, in_addr, out_addr in zip( range(num_servers), input_addresses, output_addresses ): client_config = { "input_address": in_addr, "output_address": out_addr, "client_count": num_servers, "client_index": i, } if stats_update_address is not None: client_config["stats_update_address"] = stats_update_address proc = spawn_context.Process( target=target_server_fn, name=f"ApiServer_{i}", args=(listen_address, sock, args, client_config), ) self.processes.append(proc) proc.start() logger.info("Started %d API server processes", len(self.processes)) # Shutdown only the API server processes on garbage collection # The extra processes are managed by their owners self._finalizer = weakref.finalize(self, shutdown, self.processes) def close(self) -> None: self._finalizer() def wait_for_completion_or_failure( api_server_manager: APIServerProcessManager, engine_manager: Union["CoreEngineProcManager", "CoreEngineActorManager"] | None = None, coordinator: Optional["DPCoordinator"] = None, ) -> None: """Wait for all processes to complete or detect if any fail. Raises an exception if any process exits with a non-zero status. Args: api_server_manager: The manager for API servers. engine_manager: The manager for engine processes. If CoreEngineProcManager, it manages local engines; if CoreEngineActorManager, it manages all engines. coordinator: The coordinator for data parallel. """ from vllm.v1.engine.utils import CoreEngineActorManager, CoreEngineProcManager try: logger.info("Waiting for API servers to complete ...") # Create a mapping of sentinels to their corresponding processes # for efficient lookup sentinel_to_proc: dict[Any, BaseProcess] = { proc.sentinel: proc for proc in api_server_manager.processes } if coordinator: sentinel_to_proc[coordinator.proc.sentinel] = coordinator.proc actor_run_refs = [] if isinstance(engine_manager, CoreEngineProcManager): for proc in engine_manager.processes: sentinel_to_proc[proc.sentinel] = proc elif isinstance(engine_manager, CoreEngineActorManager): actor_run_refs = engine_manager.get_run_refs() # Check if any process terminates while sentinel_to_proc or actor_run_refs: # Wait for any process to terminate ready_sentinels: list[Any] = connection.wait(sentinel_to_proc, timeout=5) # Process any terminated processes for sentinel in ready_sentinels: proc = sentinel_to_proc.pop(sentinel) # Check if process exited with error if proc.exitcode != 0: raise RuntimeError( f"Process {proc.name} (PID: {proc.pid}) " f"died with exit code {proc.exitcode}" ) if actor_run_refs: import ray _, actor_run_refs = ray.wait(actor_run_refs, timeout=5) except KeyboardInterrupt: logger.info("Received KeyboardInterrupt, shutting down API servers...") except Exception as e: logger.exception("Exception occurred while running API servers: %s", str(e)) raise finally: logger.info("Terminating remaining processes ...") api_server_manager.close() if coordinator: coordinator.close() if engine_manager: engine_manager.close() # Note(rob): shutdown function cannot be a bound method, # else the gc cannot collect the object. def shutdown(procs: list[BaseProcess]): # Shutdown the process. for proc in procs: if proc.is_alive(): proc.terminate() # Allow 5 seconds for remaining procs to terminate. deadline = time.monotonic() + 5 for proc in procs: remaining = deadline - time.monotonic() if remaining <= 0: break if proc.is_alive(): proc.join(remaining) for proc in procs: if proc.is_alive() and (pid := proc.pid) is not None: kill_process_tree(pid) def copy_slice( from_tensor: torch.Tensor, to_tensor: torch.Tensor, length: int ) -> torch.Tensor: """ Copy the first length elements of a tensor into another tensor in a non-blocking manner. Used to copy pinned CPU tensor data to pre-allocated GPU tensors. Returns the sliced target tensor. """ return to_tensor[:length].copy_(from_tensor[:length], non_blocking=True) def report_usage_stats( vllm_config, usage_context: UsageContext = UsageContext.ENGINE_CONTEXT ) -> None: """Report usage statistics if enabled.""" if not is_usage_stats_enabled(): return from vllm.model_executor.model_loader import get_architecture_class_name parallel_config = vllm_config.parallel_config # Prepare KV connector string if applicable kv_connector = None if vllm_config.kv_transfer_config is not None: kv_connector = vllm_config.kv_transfer_config.kv_connector usage_message.report_usage( get_architecture_class_name(vllm_config.model_config), usage_context, extra_kvs={ # Common configuration "dtype": str(vllm_config.model_config.dtype), "block_size": vllm_config.cache_config.block_size, "gpu_memory_utilization": vllm_config.cache_config.gpu_memory_utilization, "kv_cache_memory_bytes": vllm_config.cache_config.kv_cache_memory_bytes, # Quantization "quantization": vllm_config.model_config.quantization, "kv_cache_dtype": str(vllm_config.cache_config.cache_dtype), # Feature flags "enable_lora": bool(vllm_config.lora_config), "enable_prefix_caching": vllm_config.cache_config.enable_prefix_caching, "enforce_eager": vllm_config.model_config.enforce_eager, "disable_custom_all_reduce": parallel_config.disable_custom_all_reduce, # Distributed parallelism settings "tensor_parallel_size": parallel_config.tensor_parallel_size, "data_parallel_size": parallel_config.data_parallel_size, "pipeline_parallel_size": parallel_config.pipeline_parallel_size, "enable_expert_parallel": parallel_config.enable_expert_parallel, # All2All backend for MoE expert parallel "all2all_backend": parallel_config.all2all_backend, # KV connector used "kv_connector": kv_connector, }, ) _PROFILER_FUNC = None def record_function_or_nullcontext(name: str) -> AbstractContextManager: global _PROFILER_FUNC # fast path assume it is set if _PROFILER_FUNC is not None: return _PROFILER_FUNC(name) func = contextlib.nullcontext if envs.VLLM_CUSTOM_SCOPES_FOR_PROFILING: func = record_function elif envs.VLLM_NVTX_SCOPES_FOR_PROFILING: import nvtx func = nvtx.annotate _PROFILER_FUNC = func return func(name) def tensor_data(tensor: torch.Tensor) -> memoryview: """Get the raw data of a tensor as a uint8 memoryview, useful for serializing and hashing. Args: tensor: The input tensor. Returns: A memoryview of the tensor data as uint8. """ return tensor.flatten().contiguous().view(torch.uint8).numpy().data
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/cudagraph_dispatcher.py
vllm/v1/cudagraph_dispatcher.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from itertools import product from vllm.config import CUDAGraphMode, VllmConfig from vllm.forward_context import BatchDescriptor from vllm.logger import init_logger logger = init_logger(__name__) class CudagraphDispatcher: """ Runtime cudagraph dispatcher to dispatch keys for multiple set of cudagraphs. The dispatcher stores two sets of dispatch keys, one for PIECEWISE and one for FULL cudagraph runtime mode. The keys are initialized depending on attention support and what cudagraph mode is set in CompilationConfig. The keys stored in dispatcher are the only source of truth for valid cudagraphs that can be dispatched at runtime. At runtime, the dispatch method generates the runtime cudagraph mode (FULL, PIECEWISE, or NONE for no cudagraph) and the valid key (batch descriptor) based on the input key. After dispatching (communicated via forward context), the cudagraph wrappers will trust the dispatch key to either capture or replay (if the mode matches), or pass through to the underlying runnable without cudagraph (if the mode does not match or mode is NONE). """ def __init__(self, vllm_config: VllmConfig): self.vllm_config = vllm_config self.compilation_config = vllm_config.compilation_config self.uniform_decode_query_len = ( 1 if not self.vllm_config.speculative_config else 1 + self.vllm_config.speculative_config.num_speculative_tokens ) # Dict to store valid cudagraph dispatching keys. self.cudagraph_keys: dict[CUDAGraphMode, set[BatchDescriptor]] = { CUDAGraphMode.PIECEWISE: set(), CUDAGraphMode.FULL: set(), } assert ( not self.compilation_config.cudagraph_mode.requires_piecewise_compilation() or self.compilation_config.is_attention_compiled_piecewise() ), ( "Compilation mode should be CompilationMode.VLLM_COMPILE when " "cudagraph_mode piecewise cudagraphs is used, " "and attention should be in splitting_ops or " "inductor splitting should be used. " f"cudagraph_mode={self.compilation_config.cudagraph_mode}, " f"compilation_mode={self.compilation_config.mode}, " f"splitting_ops={self.compilation_config.splitting_ops}" ) self.keys_initialized = False def _create_padded_batch_descriptor( self, num_tokens: int, uniform_decode: bool, has_lora: bool ) -> BatchDescriptor: max_num_seqs = self.vllm_config.scheduler_config.max_num_seqs uniform_decode_query_len = self.uniform_decode_query_len num_tokens_padded = self.vllm_config.pad_for_cudagraph(num_tokens) if uniform_decode and self.cudagraph_mode.has_mode(CUDAGraphMode.FULL): num_reqs = num_tokens_padded // uniform_decode_query_len assert num_tokens_padded % uniform_decode_query_len == 0 else: uniform_decode = False num_reqs = min(num_tokens_padded, max_num_seqs) return BatchDescriptor( num_tokens=num_tokens_padded, num_reqs=num_reqs, uniform=uniform_decode, has_lora=has_lora, ) def add_cudagraph_key( self, runtime_mode: CUDAGraphMode, batch_descriptor: BatchDescriptor ): assert runtime_mode in [CUDAGraphMode.PIECEWISE, CUDAGraphMode.FULL], ( f"Invalid cudagraph runtime mode for keys: {runtime_mode}" ) self.cudagraph_keys[runtime_mode].add(batch_descriptor) def initialize_cudagraph_keys( self, cudagraph_mode: CUDAGraphMode, uniform_decode_query_len: int ): # This should be called only after attention backend is initialized. So we can # get the correct cudagraph mode after backend support is resolved. self.cudagraph_mode = cudagraph_mode # LoRA activation cases to specialize the cuda graphs on if self.vllm_config.lora_config: if self.compilation_config.cudagraph_specialize_lora: lora_cases = [True, False] else: lora_cases = [True] else: lora_cases = [False] # Note: we create all valid keys for cudagraph here but do not # guarantee all keys would be used. For example, if we allow lazy # capturing in future PR, some keys may never be triggered. if cudagraph_mode.mixed_mode() != CUDAGraphMode.NONE: for bs, has_lora in product( self.compilation_config.cudagraph_capture_sizes, lora_cases ): self.add_cudagraph_key( cudagraph_mode.mixed_mode(), self._create_padded_batch_descriptor( bs, False, has_lora ).relax_for_mixed_batch_cudagraphs(), ) # if decode cudagraph mode is FULL, and we don't already have mixed # mode full cudagraphs then add them here. if ( cudagraph_mode.decode_mode() == CUDAGraphMode.FULL and cudagraph_mode.separate_routine() ): max_num_tokens = ( uniform_decode_query_len * self.vllm_config.scheduler_config.max_num_seqs ) cudagraph_capture_sizes_for_decode = [ x for x in self.compilation_config.cudagraph_capture_sizes if x <= max_num_tokens and x >= uniform_decode_query_len ] for bs, has_lora in product(cudagraph_capture_sizes_for_decode, lora_cases): self.add_cudagraph_key( CUDAGraphMode.FULL, self._create_padded_batch_descriptor(bs, True, has_lora), ) self.keys_initialized = True def dispatch( self, num_tokens: int, uniform_decode: bool, has_lora: bool, disable_full: bool = False, ) -> tuple[CUDAGraphMode, BatchDescriptor]: """ Given conditions(e.g.,batch descriptor and if using cascade attention), dispatch to a cudagraph runtime mode and the valid batch descriptor. A new batch descriptor is returned as we might dispatch a uniform batch to a graph that supports a more general batch (uniform to non-uniform). """ if ( not self.keys_initialized or self.cudagraph_mode == CUDAGraphMode.NONE or num_tokens > self.compilation_config.max_cudagraph_capture_size ): return CUDAGraphMode.NONE, BatchDescriptor(num_tokens) batch_desc = self._create_padded_batch_descriptor( num_tokens, uniform_decode, has_lora ) relaxed_batch_desc = batch_desc.relax_for_mixed_batch_cudagraphs() if not disable_full: # check if key exists for full cudagraph if batch_desc in self.cudagraph_keys[CUDAGraphMode.FULL]: return CUDAGraphMode.FULL, batch_desc # otherwise, check if the relaxed key exists if relaxed_batch_desc in self.cudagraph_keys[CUDAGraphMode.FULL]: return CUDAGraphMode.FULL, relaxed_batch_desc # also check if the relaxed key exists for more "general" # piecewise cudagraph if relaxed_batch_desc in self.cudagraph_keys[CUDAGraphMode.PIECEWISE]: return CUDAGraphMode.PIECEWISE, relaxed_batch_desc # finally, just return no cudagraphs and a trivial batch descriptor return CUDAGraphMode.NONE, BatchDescriptor(num_tokens)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/__init__.py
vllm/v1/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/outputs.py
vllm/v1/outputs.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import TYPE_CHECKING, NamedTuple import numpy as np import torch from vllm.compilation.cuda_graph import CUDAGraphStat from vllm.v1.core.sched.output import SchedulerOutput if TYPE_CHECKING: from vllm.distributed.kv_events import KVConnectorKVEvents from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorStats else: KVConnectorStats = object KVConnectorKVEvents = object class LogprobsLists(NamedTuple): # [num_reqs x num_generated_tokens, max_num_logprobs + 1] logprob_token_ids: np.ndarray # [num_reqs x num_generated_tokens, max_num_logprobs + 1] logprobs: np.ndarray # [num_reqs x num_generated_tokens] sampled_token_ranks: np.ndarray # [num_reqs] # Used for slicing the logprobs in cases like speculative # decoding where the number of generated tokens may be # different for each request. cu_num_generated_tokens: list[int] | None = None def slice_request(self, req_idx: int, num_positions: int): if self.cu_num_generated_tokens is not None: req_idx = self.cu_num_generated_tokens[req_idx] end_idx = req_idx + num_positions return LogprobsLists( self.logprob_token_ids[req_idx:end_idx], self.logprobs[req_idx:end_idx], self.sampled_token_ranks[req_idx:end_idx], None, ) class LogprobsTensors(NamedTuple): # [num_reqs x num_generated_tokens, max_num_logprobs + 1] logprob_token_ids: torch.Tensor # [num_reqs x num_generated_tokens, max_num_logprobs + 1] logprobs: torch.Tensor # [num_reqs x num_generated_tokens] selected_token_ranks: torch.Tensor def tolists(self, cu_num_generated_tokens: list[int] | None = None): return LogprobsLists( self.logprob_token_ids.cpu().numpy(), self.logprobs.cpu().numpy(), self.selected_token_ranks.cpu().numpy(), cu_num_generated_tokens, ) def to_cpu_nonblocking(self) -> "LogprobsTensors": if self.logprob_token_ids.device.type == "cpu": return self return LogprobsTensors( self.logprob_token_ids.to("cpu", non_blocking=True), self.logprobs.to("cpu", non_blocking=True), self.selected_token_ranks.to("cpu", non_blocking=True), ) @staticmethod def empty_cpu( num_positions: int, num_tokens_per_position: int ) -> "LogprobsTensors": """Create empty LogprobsTensors on CPU.""" logprob_token_ids = torch.empty( (num_positions, num_tokens_per_position), dtype=torch.int32, device="cpu" ) logprobs = torch.empty_like(logprob_token_ids, dtype=torch.float32) selected_token_ranks = torch.empty( num_positions, dtype=torch.int32, device="cpu" ) return LogprobsTensors( logprob_token_ids=logprob_token_ids, logprobs=logprobs, selected_token_ranks=selected_token_ranks, ) # [num_reqs, <dynamic>] # The shape of each element depends on the pooler used PoolerOutput = list[torch.Tensor | None] | torch.Tensor | None @dataclass class SamplerOutput: # [num_reqs, max_num_generated_tokens] # Different requests can have different number of generated tokens. # All requests are padded to max_num_generated_tokens. # PLACEHOLDER_TOKEN_ID (-1 by default) is used for padding. sampled_token_ids: torch.Tensor logprobs_tensors: LogprobsTensors | None @dataclass class KVConnectorOutput: # [req_ids] finished_sending: set[str] | None = None finished_recving: set[str] | None = None kv_connector_stats: KVConnectorStats | None = None kv_cache_events: KVConnectorKVEvents | None = None # IDs of externally computed KV blocks that failed to load. # Requests referencing these blocks should be rescheduled to recompute them invalid_block_ids: set[int] = field(default_factory=set) # Configuration describing how many finished sending/receiving # notifications should be expected for each request. This allows # handshake-based connectors like Nixl to update the KVOutputAggregator. # It captures a static setup info and should almost always remain constant # for a given connector after discovery. Default value entails no change. expected_finished_count: int = 0 def is_empty(self): return ( not self.finished_sending and not self.finished_recving and not self.kv_connector_stats and not self.kv_cache_events and not self.invalid_block_ids ) @dataclass class ECConnectorOutput: # [mm_hash] finished_sending: set[str] | None = None finished_recving: set[str] | None = None # ModelRunnerOutput is serialized and sent to the scheduler process. # This is expensive for torch.Tensor so prefer to use list instead. @dataclass class ModelRunnerOutput: # [num_reqs] req_ids: list[str] # req_id -> index req_id_to_index: dict[str, int] # num_reqs x num_generated_tokens # num_generated_tokens is the number of tokens # generated in the current step. It can be different for # each request due to speculative/jump decoding. sampled_token_ids: list[list[int]] = field(default_factory=list) # [num_reqs, max_num_logprobs + 1] # [num_reqs, max_num_logprobs + 1] # [num_reqs] logprobs: LogprobsLists | None = None # req_id -> (token_ids, logprobs, ranks) # [prompt_len, num_prompt_logprobs] # [prompt_len, num_prompt_logprobs] # [prompt_len] prompt_logprobs_dict: dict[str, LogprobsTensors | None] = field( default_factory=dict ) # [num_reqs, hidden_size] pooler_output: list[torch.Tensor | None] | None = None kv_connector_output: KVConnectorOutput | None = None ec_connector_output: ECConnectorOutput | None = None # req_id -> num_nans_in_logits num_nans_in_logits: dict[str, int] | None = None # information related to cudagraph execution cudagraph_stats: CUDAGraphStat | None = None # ModelRunnerOutput wrapper for async scheduling. class AsyncModelRunnerOutput(ABC): @abstractmethod def get_output(self) -> ModelRunnerOutput: """Get the ModelRunnerOutput for this async output. This is a blocking call that waits until the results are ready, which might involve copying device tensors to the host. This method should only be called once per AsyncModelRunnerOutput. """ pass @dataclass class DraftTokenIds: # [num_reqs] req_ids: list[str] # num_reqs x num_draft_tokens draft_token_ids: list[list[int]] def make_empty_encoder_model_runner_output( scheduler_output: "SchedulerOutput", ) -> ModelRunnerOutput: """ Create a ModelRunnerOutput stub that contains the correct per-request bookkeeping but no generated data yet. """ if not scheduler_output.num_scheduled_tokens: return EMPTY_MODEL_RUNNER_OUTPUT # Convert to list so we get a deterministic, indexable sequence req_ids: list[str] = list(scheduler_output.num_scheduled_tokens.keys()) # Give every request its own contiguous index req_id_to_index: dict[str, int] = {rid: idx for idx, rid in enumerate(req_ids)} # No tokens generated yet ⇒ one empty list per request sampled_token_ids: list[list[int]] = [[0] for _ in req_ids] # Pooler outputs are not available yet ⇒ use None placeholders pooler_output: list[torch.Tensor | None] = [None for _ in req_ids] return ModelRunnerOutput( req_ids=req_ids, req_id_to_index=req_id_to_index, sampled_token_ids=sampled_token_ids, pooler_output=pooler_output, ) EMPTY_MODEL_RUNNER_OUTPUT = ModelRunnerOutput(req_ids=[], req_id_to_index={})
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/__init__.py
vllm/v1/attention/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/rocm_attn.py
vllm/v1/attention/backends/rocm_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with PagedAttention and Triton prefix prefill.""" from dataclasses import dataclass from typing import ClassVar import torch from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionType, ) from vllm.attention.ops.chunked_prefill_paged_decode import chunked_prefill_paged_decode from vllm.attention.ops.paged_attn import PagedAttention from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.model_executor.layers.quantization.utils.quant_utils import ( QuantKey, kFp8StaticTensorSym, ) from vllm.platforms import current_platform from vllm.v1.attention.backends.flash_attn import FlashAttentionMetadata from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, ) from vllm.v1.kv_cache_interface import AttentionSpec logger = init_logger(__name__) @dataclass class RocmAttentionMetadata: # NOTE(sang): Definition of context_len, query_len, and seq_len. # |---------- N-1 iteration --------| # |---------------- N iteration ---------------------| # |- tokenA -|......................|-- newTokens ---| # |---------- context_len ----------| # |-------------------- seq_len ---------------------| # |-- query_len ---| num_actual_tokens: int # Number of tokens excluding padding. max_query_len: int query_start_loc: torch.Tensor max_seq_len: int seq_lens: torch.Tensor block_table: torch.Tensor slot_mapping: torch.Tensor # For cascade attention. use_cascade: bool common_prefix_len: int cu_prefix_query_lens: torch.Tensor | None prefix_kv_lens: torch.Tensor | None suffix_kv_lens: torch.Tensor | None # Optional aot scheduling scheduler_metadata: torch.Tensor | None = None prefix_scheduler_metadata: torch.Tensor | None = None class RocmAttentionMetadataBuilder(AttentionMetadataBuilder[RocmAttentionMetadata]): _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.block_size = kv_cache_spec.block_size model_config = vllm_config.model_config self.num_heads_q = model_config.get_num_attention_heads( vllm_config.parallel_config ) self.num_heads_kv = model_config.get_num_kv_heads(vllm_config.parallel_config) self.headdim = model_config.get_head_size() def build_for_cudagraph_capture( self, common_attn_metadata: CommonAttentionMetadata ) -> RocmAttentionMetadata: attn_metadata = self.build(0, common_attn_metadata) # When doing full graph capture, setting seq_lens to # max_model_len will cause graph capture to be extremely # slow, so here we set it to 1. attn_metadata.seq_lens.fill_(1) # Here we set the query start locs to 0. This is to # cover up an invalid memory access in the prefix_prefil kernel # that we run into during graph capture (#25985) common_attn_metadata.query_start_loc.zero_() common_attn_metadata.query_start_loc_cpu.zero_() return attn_metadata def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> RocmAttentionMetadata: num_actual_tokens = common_attn_metadata.num_actual_tokens max_query_len = common_attn_metadata.max_query_len max_seq_len = common_attn_metadata.max_seq_len query_start_loc = common_attn_metadata.query_start_loc seq_lens = common_attn_metadata.seq_lens block_table_tensor = common_attn_metadata.block_table_tensor slot_mapping = common_attn_metadata.slot_mapping use_cascade = common_prefix_len > 0 if use_cascade: cu_prefix_query_lens = torch.tensor( [0, num_actual_tokens], dtype=torch.int32, device=self.device ) prefix_kv_lens = torch.tensor( [common_prefix_len], dtype=torch.int32, device=self.device ) suffix_kv_lens = common_attn_metadata.seq_lens_cpu - common_prefix_len suffix_kv_lens = suffix_kv_lens.to(self.device) else: cu_prefix_query_lens = None prefix_kv_lens = None suffix_kv_lens = None prefix_scheduler_metadata = None attn_metadata = RocmAttentionMetadata( num_actual_tokens=num_actual_tokens, max_query_len=max_query_len, query_start_loc=query_start_loc, max_seq_len=max_seq_len, seq_lens=seq_lens, block_table=block_table_tensor, slot_mapping=slot_mapping, use_cascade=use_cascade, common_prefix_len=common_prefix_len, cu_prefix_query_lens=cu_prefix_query_lens, prefix_kv_lens=prefix_kv_lens, suffix_kv_lens=suffix_kv_lens, prefix_scheduler_metadata=prefix_scheduler_metadata, ) return attn_metadata class RocmAttentionBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [ torch.float16, torch.bfloat16, torch.float32, ] @classmethod def get_supported_head_sizes(cls) -> list[int]: return [32, 64, 96, 128, 160, 192, 224, 256] @classmethod def validate_head_size(cls, head_size: int) -> None: if not cls.supports_head_size(head_size): attn_type = cls.__name__.removesuffix("Backend") raise ValueError( f"Head size {head_size} is not supported by {attn_type}. " f"Supported head sizes are: {cls.get_supported_head_sizes()}. " "Set --attention-backend=FLEX_ATTENTION to use " "FlexAttention backend which supports all head sizes." ) @staticmethod def get_name() -> str: return "ROCM_ATTN" @staticmethod def get_impl_cls() -> type["RocmAttentionImpl"]: return RocmAttentionImpl @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 class RocmAttentionImpl(AttentionImpl): 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: self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_kv_heads if alibi_slopes is not None: alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32) self.alibi_slopes = alibi_slopes if sliding_window is None: self.sliding_window = (-1, -1) else: self.sliding_window = (sliding_window - 1, 0) self.kv_cache_dtype = kv_cache_dtype if logits_soft_cap is None: # In flash-attn, setting logits_soft_cap as 0 means no soft cap. logits_soft_cap = 0 self.logits_soft_cap = logits_soft_cap self.kv_sharing_target_layer_name = kv_sharing_target_layer_name self.num_queries_per_kv = self.num_heads // self.num_kv_heads RocmAttentionBackend.validate_head_size(head_size) if attn_type not in [AttentionType.DECODER, AttentionType.ENCODER_DECODER]: raise NotImplementedError( "Encoder self-attention is not implemented for RocmAttentionImpl" ) self.fp8_dtype = current_platform.fp8_dtype() self.sinks = sinks if sinks is not None: assert sinks.shape[0] == num_heads, ( "Sinks must have the same number of heads as the number of " f"heads in the layer. Sinks shape: {sinks.shape}, " f"num_heads: {num_heads}." ) 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 key_cache, value_cache = PagedAttention.split_kv_cache( kv_cache, self.num_kv_heads, self.head_size ) if self.kv_sharing_target_layer_name is None: # Reshape the input keys and values and store them in the cache. # Skip this if sharing KV cache with an earlier attention layer. PagedAttention.write_to_paged_cache( key, value, key_cache, value_cache, attn_metadata.slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) 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 # Compute attention and update output up to `num_actual_tokens`. chunked_prefill_paged_decode( query=query[:num_actual_tokens], key=key[:num_actual_tokens], value=value[:num_actual_tokens], output=output[:num_actual_tokens], kv_cache_dtype=self.kv_cache_dtype, key_cache=key_cache, value_cache=value_cache, block_table=block_table, query_start_loc=cu_seqlens_q, seq_lens=seqused_k, max_seq_len=max_seqlen_k, max_query_len=max_seqlen_q, k_scale=layer._k_scale, v_scale=layer._v_scale, alibi_slopes=self.alibi_slopes, sliding_window=self.sliding_window[0], sm_scale=self.scale, output_scale=output_scale, sinks=self.sinks, ) return output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/flash_attn_diffkv.py
vllm/v1/attention/backends/flash_attn_diffkv.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with FlashAttention.""" import torch from vllm.attention.backends.abstract import AttentionType from vllm.attention.ops.triton_reshape_and_cache_flash import ( triton_reshape_and_cache_flash_diffkv, ) from vllm.attention.utils.fa_utils import is_flash_attn_varlen_func_available if is_flash_attn_varlen_func_available(): from vllm.attention.utils.fa_utils import flash_attn_varlen_func from vllm.logger import init_logger from vllm.v1.attention.backends.utils import get_kv_cache_layout from .flash_attn import ( FlashAttentionBackend, FlashAttentionImpl, FlashAttentionMetadata, cascade_attention, ) logger = init_logger(__name__) class FlashAttentionDiffKVBackend(FlashAttentionBackend): # Default to 128 for this backend head_size_v: int = 128 @classmethod def set_head_size_v(cls, head_size_v: int) -> None: cls.head_size_v = head_size_v @staticmethod def get_name() -> str: return "FLASH_ATTN_DIFFKV" @staticmethod def get_impl_cls() -> type["FlashAttentionImpl"]: return FlashAttentionDiffKVImpl # Do not modify the interface of get_kv_cache_shape, # but consider head_size_v when returning result. @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 ( num_blocks, block_size, num_kv_heads, head_size + FlashAttentionDiffKVBackend.head_size_v, ) @staticmethod def get_kv_cache_stride_order( include_num_layers_dimension: bool = False, ) -> tuple[int, ...]: # `stride_order` indicates the permutation that gets # us from `get_kv_cache_shape` to the actual memory layout we want. cache_layout = get_kv_cache_layout() if cache_layout == "NHD" and include_num_layers_dimension: # (num_blocks, num_layers, block_size, # num_kv_heads, head_size + head_size_v) return (1, 0, 2, 3, 4) elif cache_layout == "NHD": stride_order = (0, 1, 2, 3) elif cache_layout == "HND" and include_num_layers_dimension: # (num_blocks, num_kv_heads, num_layers, # block_size, head_size + head_size_v) return (1, 3, 0, 2, 4) elif cache_layout == "HND": stride_order = (0, 2, 1, 3) else: raise ValueError(f"Unknown cache layout format {cache_layout}.") return stride_order class FlashAttentionDiffKVImpl(FlashAttentionImpl): 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_v] kv_cache: shape = [num_blocks, block_size, num_kv_heads, head_size + head_size_v] attn_metadata: Metadata for attention. Returns: shape = [num_tokens, num_heads * head_size_v] NOTE: FP8 quantization, flash-attn expect the size of {q,k,v}_descale to be (num_sequences, num_kv_heads). We use torch's .expand() to avoid duplicating values """ assert output is not None, "Output tensor must be provided." if output_scale is not None or output_block_scale is not None: raise NotImplementedError( "fused output quantization is not yet supported for FlashAttentionImpl" ) if attn_metadata is None: # Profiling run. return output.fill_(0) attn_type = self.attn_type # 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 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, ) # For decoder and cross-attention, use KV cache as before # Different head_size for K and V key_cache = kv_cache[..., : self.head_size] value_cache = kv_cache[..., self.head_size :] # key and value may be None in the case of cross attention. They are # calculated once based on the output from the encoder and then cached # in KV cache. if ( self.kv_sharing_target_layer_name is None and key is not None and value is not None ): # Reshape the input keys and values and store them in the cache. # Skip this if sharing KV cache with an earlier attention layer. # NOTE(woosuk): Here, key and value are padded while slot_mapping is # not padded. However, we don't need to do key[:num_actual_tokens] # and value[:num_actual_tokens] because the reshape_and_cache_flash # op uses the slot_mapping's shape to determine the number of # actual tokens. # kv_cache update for different head_size K and V triton_reshape_and_cache_flash_diffkv( key, value, kv_cache, attn_metadata.slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) if self.kv_cache_dtype.startswith("fp8"): # queries are quantized in the attention layer dtype = FlashAttentionBackend.get_fp8_dtype_for_flashattn( self.kv_cache_dtype ) key_cache = key_cache.view(dtype) value_cache = value_cache.view(dtype) if not attn_metadata.use_cascade: 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 scheduler_metadata = attn_metadata.scheduler_metadata descale_shape = (cu_seqlens_q.shape[0] - 1, self.num_kv_heads) if self.dcp_world_size > 1: self._forward_with_dcp( query[:num_actual_tokens], key[:num_actual_tokens], value[:num_actual_tokens], key_cache, value_cache, output[:num_actual_tokens], attn_metadata, q_descale=layer._q_scale.expand(descale_shape), k_descale=layer._k_scale.expand(descale_shape), v_descale=layer._v_scale.expand(descale_shape), ) return output else: flash_attn_varlen_func( 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=attn_metadata.causal, alibi_slopes=self.alibi_slopes, window_size=self.sliding_window, block_table=block_table, softcap=self.logits_soft_cap, scheduler_metadata=scheduler_metadata, fa_version=self.vllm_flash_attn_version, q_descale=layer._q_scale.expand(descale_shape), k_descale=layer._k_scale.expand(descale_shape), v_descale=layer._v_scale.expand(descale_shape), num_splits=attn_metadata.max_num_splits, s_aux=self.sinks, ) return output # Cascade attention (rare case). cascade_attention( output[:num_actual_tokens], query[:num_actual_tokens], key_cache, value_cache, cu_query_lens=attn_metadata.query_start_loc, max_query_len=attn_metadata.max_query_len, cu_prefix_query_lens=attn_metadata.cu_prefix_query_lens, prefix_kv_lens=attn_metadata.prefix_kv_lens, suffix_kv_lens=attn_metadata.suffix_kv_lens, max_kv_len=attn_metadata.max_seq_len, softmax_scale=self.scale, alibi_slopes=self.alibi_slopes, sliding_window=self.sliding_window, logits_soft_cap=self.logits_soft_cap, block_table=attn_metadata.block_table, common_prefix_len=attn_metadata.common_prefix_len, max_num_splits=attn_metadata.max_num_splits, fa_version=self.vllm_flash_attn_version, prefix_scheduler_metadata=attn_metadata.prefix_scheduler_metadata, suffix_scheduler_metadata=attn_metadata.scheduler_metadata, q_descale=layer._q_scale, k_descale=layer._k_scale, v_descale=layer._v_scale, s_aux=self.sinks, ) return output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/cpu_attn.py
vllm/v1/attention/backends/cpu_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import ClassVar import torch from vllm import _custom_ops as ops from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionLayer, AttentionType, is_quantized_kv_cache, ) from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.platforms import CpuArchEnum, current_platform from vllm.v1.attention.backends.utils import ( AttentionMetadataBuilder, CommonAttentionMetadata, split_decodes_and_prefills, ) from vllm.v1.kv_cache_interface import AttentionSpec, CrossAttentionSpec logger = init_logger(__name__) _CPU_ARCH_PREFER_MIXED_BATCH = (CpuArchEnum.X86, CpuArchEnum.ARM) class CPUAttentionBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [ torch.float16, torch.bfloat16, torch.float32, ] @classmethod def get_supported_dtypes(cls) -> list[torch.dtype]: return [torch.float16, torch.bfloat16, torch.float32] @classmethod def get_supported_head_sizes(cls) -> list[int]: return [32, 64, 96, 128, 160, 192, 224, 256] @staticmethod def get_name() -> str: return "CPU_ATTN" @classmethod def supports_attn_type(cls, attn_type: str) -> bool: """CPU attention supports decoder, encoder-only and encoder-decoder attention.""" return attn_type in ( AttentionType.DECODER, AttentionType.ENCODER, AttentionType.ENCODER_ONLY, AttentionType.ENCODER_DECODER, ) @staticmethod def get_impl_cls() -> type["CPUAttentionBackendImpl"]: return CPUAttentionBackendImpl @staticmethod def get_builder_cls() -> type["CPUAttentionMetadataBuilder"]: return CPUAttentionMetadataBuilder @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, ...]: return 2, num_blocks, num_kv_heads, block_size, head_size @staticmethod def use_cascade_attention(*args, **kwargs) -> bool: return False @dataclass class CPUAttentionMetadata: isa: str num_actual_tokens: int # Number of tokens excluding padding. max_query_len: int query_start_loc: torch.Tensor max_seq_len: int seq_lens: torch.Tensor block_table: torch.Tensor slot_mapping: torch.Tensor scheduler_metadata: torch.Tensor | None causal: bool = True # can be removed after deprecate sdpa use_sdpa_prefill: bool = False num_decode_tokens: int = 0 sdpa_attn_masks: list[torch.Tensor | None] | None = None sdpa_start_loc: torch.Tensor | None = None class CPUAttentionMetadataBuilder(AttentionMetadataBuilder[CPUAttentionMetadata]): def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ) -> None: super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.use_sdpa_prefill = False reorder_batch_threshold = None if current_platform.get_cpu_architecture() not in _CPU_ARCH_PREFER_MIXED_BATCH: # in this case, decode seqs are reordered to the front of prefill seqs # to split decode and prefill. Then use SDPA for prefill and # cpu_attention_with_kv_cache for decode reorder_batch_threshold = 1 self.use_sdpa_prefill = True self._init_reorder_batch_threshold(reorder_batch_threshold, False) self.kv_cache_spec = kv_cache_spec self.vllm_config = vllm_config parallel_config = vllm_config.parallel_config self.num_kv_heads = vllm_config.model_config.get_num_kv_heads(parallel_config) self.num_heads = vllm_config.model_config.get_num_attention_heads( parallel_config ) self.head_dim = kv_cache_spec.head_size self.dtype = vllm_config.model_config.dtype self.window_size = getattr(kv_cache_spec, "sliding_window", -1) if self.window_size is None: self.window_size = -1 self.block_size = vllm_config.cache_config.block_size self.isa = _get_attn_isa(self.dtype, self.block_size) self.is_cross_attention = isinstance(kv_cache_spec, CrossAttentionSpec) def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> CPUAttentionMetadata: num_reqs = common_attn_metadata.num_reqs num_actual_tokens = common_attn_metadata.num_actual_tokens max_query_len = common_attn_metadata.max_query_len max_seq_len = common_attn_metadata.max_seq_len query_start_loc = common_attn_metadata.query_start_loc seq_lens = common_attn_metadata.seq_lens block_table_tensor = common_attn_metadata.block_table_tensor slot_mapping = common_attn_metadata.slot_mapping causal = False if self.is_cross_attention else common_attn_metadata.causal sdpa_start_loc = query_start_loc num_decode_tokens = 0 if self.use_sdpa_prefill and causal: # Decoder, need reorder and truncate assert self.reorder_batch_threshold (num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens) = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=self.reorder_batch_threshold, require_uniform=True, ) ) num_reqs = num_decodes sdpa_start_loc = sdpa_start_loc[num_decodes:] - num_decode_tokens seq_lens = seq_lens[:num_decodes] query_start_loc = query_start_loc[: num_decodes + 1] block_table_tensor = block_table_tensor[:num_decodes] sheduler_metadata = ops.cpu_attn_get_scheduler_metadata( num_reqs=num_reqs, num_heads=self.num_heads, num_kv_heads=self.num_kv_heads, head_dim=self.head_dim, seq_lens=seq_lens, dtype=self.dtype, query_start_loc=query_start_loc, causal=causal, sliding_window_size=self.window_size, isa=self.isa, enable_kv_split=True, ) attn_metadata = CPUAttentionMetadata( isa=self.isa, num_actual_tokens=num_actual_tokens, max_query_len=max_query_len, query_start_loc=query_start_loc, max_seq_len=max_seq_len, seq_lens=seq_lens, block_table=block_table_tensor, slot_mapping=slot_mapping, scheduler_metadata=sheduler_metadata, causal=causal, use_sdpa_prefill=self.use_sdpa_prefill, num_decode_tokens=num_decode_tokens, sdpa_start_loc=sdpa_start_loc, ) return attn_metadata class CPUAttentionBackendImpl(AttentionImpl): 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: str = AttentionType.DECODER, kv_sharing_target_layer_name: str | None = None, sinks: torch.Tensor | None = None, ) -> None: self.kv_sharing_target_layer_name = kv_sharing_target_layer_name self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) if logits_soft_cap is not None and attn_type in ( AttentionType.ENCODER, AttentionType.ENCODER_ONLY, ): logger.warning_once( "CPU_ATTN does not support logits softcap for" " ENCODER and ENCODER_ONLY, outputs may be slightly off" ) if logits_soft_cap is None: logits_soft_cap = 0 self.logits_soft_cap = logits_soft_cap self.num_kv_heads = num_kv_heads if alibi_slopes is not None: alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32) self.alibi_slopes = alibi_slopes if sliding_window is None: self.sliding_window = (-1, -1) elif attn_type == AttentionType.ENCODER_ONLY: self.sliding_window = (sliding_window - 1, sliding_window - 1) else: self.sliding_window = (sliding_window - 1, 0) self.kv_cache_dtype = kv_cache_dtype self.num_queries_per_kv = self.num_heads // self.num_kv_heads if is_quantized_kv_cache(kv_cache_dtype): raise NotImplementedError("FP8 KV cache is unsupported in CPU_ATTN") self.attn_type = attn_type self.sinks = sinks if self.sinks is not None: assert self.sinks.shape[0] == num_heads, ( "Sinks must have the same number of heads as the number of " "heads in the layer" ) def forward( self, layer: AttentionLayer, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, attn_metadata: CPUAttentionMetadata | None, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Forward pass for CPU attention backend. 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, num_kv_heads, block_size, 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_scale is not None or output_block_scale is not None: raise NotImplementedError( "fused output quantization is not yet supported" " for CPUAttentionBackendImpl" ) # For warming-up if attn_metadata is None: return output 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, return self._run_sdpa_forward( query[:num_actual_tokens], key[:num_actual_tokens], value[:num_actual_tokens], output[:num_actual_tokens], attn_metadata, self.attn_type, ) # For decoder and cross-attention, use KV cache, size are # [num_blocks, num_kv_heads, block_size, head_size] key_cache, value_cache = kv_cache.unbind(0) # key and value may be None in the case of cross attention. They are # calculated once based on the output from the encoder and then cached # in KV cache. if ( self.kv_sharing_target_layer_name is None and key is not None and value is not None ): ops.cpu_attn_reshape_and_cache( key, value, key_cache, value_cache, attn_metadata.slot_mapping, attn_metadata.isa, ) if attn_metadata.use_sdpa_prefill: assert self.sinks is None, "Attention sink is unsupported in SDPA prefill" num_decode_tokens = attn_metadata.num_decode_tokens self._run_sdpa_forward( query[num_decode_tokens:num_actual_tokens], key[num_decode_tokens:num_actual_tokens], value[num_decode_tokens:num_actual_tokens], output[num_decode_tokens:num_actual_tokens], attn_metadata, self.attn_type, ) num_actual_tokens = num_decode_tokens if num_actual_tokens > 0: ops.cpu_attention_with_kv_cache( query=query[:num_actual_tokens], key_cache=key_cache, value_cache=value_cache, output=output[:num_actual_tokens], # type: ignore query_start_loc=attn_metadata.query_start_loc, seq_lens=attn_metadata.seq_lens, scale=self.scale, causal=attn_metadata.causal, alibi_slopes=self.alibi_slopes, # type: ignore sliding_window=self.sliding_window, block_table=attn_metadata.block_table, softcap=self.logits_soft_cap, scheduler_metadata=attn_metadata.scheduler_metadata, s_aux=self.sinks, ) return output def _run_sdpa_forward( self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, output: torch.Tensor, attn_metadata: CPUAttentionMetadata, attn_type: str, ) -> torch.Tensor: attn_masks = attn_metadata.sdpa_attn_masks if attn_masks is None: if self.alibi_slopes is not None: attn_masks = _make_alibi_bias( self.alibi_slopes, query.dtype, attn_metadata.sdpa_start_loc, ) elif self.sliding_window[0] != -1 or self.sliding_window[1] != -1: assert attn_metadata.seq_lens is not None attn_masks = _make_sliding_window_bias( attn_metadata.sdpa_start_loc, self.sliding_window[0], self.sliding_window[1], query.dtype, ) else: attn_masks = [None] * (attn_metadata.sdpa_start_loc.size(0) - 1) # type: ignore attn_metadata.sdpa_attn_masks = attn_masks query = query.movedim(0, query.dim() - 2) key = key.movedim(0, key.dim() - 2) value = value.movedim(0, value.dim() - 2) if self.num_kv_heads != self.num_heads: key = key.repeat_interleave(self.num_queries_per_kv, dim=-3) value = value.repeat_interleave(self.num_queries_per_kv, dim=-3) causal_attn = attn_type == AttentionType.DECODER sdpa_start_loc = attn_metadata.sdpa_start_loc.numpy() # type: ignore for i in range(len(attn_masks)): mask = attn_masks[i] start_q = sdpa_start_loc[i] end_q = sdpa_start_loc[i + 1] sub_out = ( torch.nn.functional.scaled_dot_product_attention( query[None, :, start_q:end_q, :], key[None, :, start_q:end_q, :], value[None, :, start_q:end_q, :], attn_mask=mask, dropout_p=0.0, is_causal=causal_attn and mask is None, scale=self.scale, ) .squeeze(0) .movedim(query.dim() - 2, 0) ) output[start_q:end_q, :, :] = sub_out return output def _make_alibi_bias( alibi_slopes: torch.Tensor, dtype: torch.dtype, sdpa_start_loc: torch.Tensor, ) -> list[torch.Tensor]: attn_biases: list[torch.Tensor] = [] seq_num = sdpa_start_loc.size(0) - 1 sdpa_start_loc = sdpa_start_loc.numpy() # type: ignore for i in range(seq_num): seq_len = sdpa_start_loc[i + 1] - sdpa_start_loc[i] bias = torch.arange(seq_len, dtype=dtype) # type: ignore # NOTE(zhuohan): HF uses # `bias = bias[None, :].repeat(seq_len, 1)` # here. We find that both biases give the same results, but # the bias below more accurately follows the original ALiBi # paper. bias = bias[None, :] - bias[:, None] num_heads = alibi_slopes.shape[0] bias = bias[None, :].repeat((num_heads, 1, 1)) bias.mul_(alibi_slopes[:, None, None]).unsqueeze_(0) inf_mask = ( torch.empty((1, seq_len, seq_len), dtype=bias.dtype) # type: ignore .fill_(-torch.inf) .triu_(diagonal=1) ) attn_biases.append((bias + inf_mask).to(dtype)) return attn_biases def _make_sliding_window_bias( sdpa_start_loc: torch.Tensor, left_window_size: int, right_window_size: int, dtype: torch.dtype, ) -> list[torch.Tensor]: attn_biases: list[torch.Tensor] = [] seq_num = sdpa_start_loc.size(0) - 1 sdpa_start_loc = sdpa_start_loc.numpy() # type: ignore for i in range(seq_num): seq_len = sdpa_start_loc[i + 1] - sdpa_start_loc[i] mask = torch.full( # type: ignore (1, seq_len, seq_len), # type: ignore fill_value=1, dtype=dtype, ) if right_window_size != -1: mask = torch.tril(mask, diagonal=right_window_size) if left_window_size != -1: mask = torch.triu(mask, diagonal=-left_window_size) mask = torch.log(mask) attn_biases.append(mask) return attn_biases def _get_attn_isa(dtype: torch.dtype, block_size: int) -> str: supports_amx = torch._C._cpu._is_amx_tile_supported() if supports_amx and dtype in (torch.bfloat16,) and block_size % 32 == 0: return "amx" elif block_size % 32 == 0: if current_platform.get_cpu_architecture() == CpuArchEnum.ARM: return "neon" else: return "vec" else: return "vec16"
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/short_conv_attn.py
vllm/v1/attention/backends/short_conv_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from vllm.attention.backends.abstract import AttentionBackend from vllm.v1.attention.backends.mamba_attn import ( BaseMambaAttentionMetadata, BaseMambaAttentionMetadataBuilder, ) class ShortConvAttentionBackend(AttentionBackend): @staticmethod def get_builder_cls() -> type["ShortConvAttentionMetadataBuilder"]: return ShortConvAttentionMetadataBuilder @dataclass class ShortConvAttentionMetadata(BaseMambaAttentionMetadata): pass class ShortConvAttentionMetadataBuilder( BaseMambaAttentionMetadataBuilder[ShortConvAttentionMetadata] ): metadata_cls = ShortConvAttentionMetadata
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/rocm_aiter_unified_attn.py
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.attention.backends.abstract import AttentionType from vllm.logger import init_logger from vllm.model_executor.layers.quantization.utils.quant_utils import ( QuantKey, kFp8StaticTensorSym, ) 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 @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 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 key_cache, value_cache = kv_cache.unbind(0) # key and value may be None in the case of cross attention. They are # calculated once based on the output from the encoder and then cached # in KV cache. if ( self.kv_sharing_target_layer_name is None and key is not None and value is not None ): # Reshape the input keys and values and store them in the cache. # Skip this if sharing KV cache with an earlier attention layer. ops.reshape_and_cache_flash( key, value, key_cache, value_cache, attn_metadata.slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) 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
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/gdn_attn.py
vllm/v1/attention/backends/gdn_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Backend for GatedDeltaNet attention.""" from dataclasses import dataclass import torch from vllm.attention.backends.abstract import AttentionBackend from vllm.attention.backends.utils import PAD_SLOT_ID from vllm.config import VllmConfig from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, compute_causal_conv1d_metadata, split_decodes_and_prefills, ) from vllm.v1.kv_cache_interface import AttentionSpec, MambaSpec class GDNAttentionBackend(AttentionBackend): @staticmethod def get_builder_cls() -> type["GDNAttentionMetadataBuilder"]: return GDNAttentionMetadataBuilder @dataclass class GDNAttentionMetadata: num_prefills: int num_prefill_tokens: int num_decodes: int num_decode_tokens: int num_spec_decodes: int num_spec_decode_tokens: int num_actual_tokens: int has_initial_state: torch.Tensor | None = None spec_query_start_loc: torch.Tensor | None = None # shape: [num_spec_decodes + 1,] non_spec_query_start_loc: torch.Tensor | None = ( None # shape: [batch - num_spec_decodes + 1,] ) spec_state_indices_tensor: torch.Tensor | None = None # shape: [batch, num_spec] non_spec_state_indices_tensor: torch.Tensor | None = ( None # shape: [batch - num_spec_decodes,] ) spec_sequence_masks: torch.Tensor | None = None # shape: [batch,] spec_token_indx: torch.Tensor | None = None non_spec_token_indx: torch.Tensor | None = None num_accepted_tokens: torch.Tensor | None = None # shape: [batch,] # The following attributes are for triton implementation of causal_conv1d nums_dict: dict | None = None batch_ptr: torch.Tensor | None = None token_chunk_offset_ptr: torch.Tensor | None = None class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]): _cudagraph_support = AttentionCGSupport.UNIFORM_BATCH reorder_batch_threshold: int = 1 def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): assert isinstance(kv_cache_spec, MambaSpec) self.vllm_config = vllm_config self.compilation_config = vllm_config.compilation_config self.speculative_config = vllm_config.speculative_config self.kv_cache_spec = kv_cache_spec if self.speculative_config: self.num_spec = self.speculative_config.num_speculative_tokens else: self.num_spec = 0 self.use_spec_decode = self.num_spec > 0 self._init_reorder_batch_threshold(1, self.use_spec_decode) self.use_full_cuda_graph = ( self.compilation_config.cudagraph_mode.has_full_cudagraphs() ) self.decode_cudagraph_max_bs = min( self.vllm_config.scheduler_config.max_num_seqs * (self.num_spec + 1), self.compilation_config.max_cudagraph_capture_size, ) self.spec_state_indices_tensor = torch.empty( (self.decode_cudagraph_max_bs, self.num_spec + 1), dtype=torch.int32, device=device, ) self.non_spec_state_indices_tensor = torch.empty( (self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device, ) self.spec_sequence_masks = torch.empty( (self.decode_cudagraph_max_bs,), dtype=torch.bool, device=device, ) self.spec_token_indx = torch.empty( (self.decode_cudagraph_max_bs * (self.num_spec + 1),), dtype=torch.int32, device=device, ) self.non_spec_token_indx = torch.empty( (self.decode_cudagraph_max_bs * (self.num_spec + 1),), dtype=torch.int32, device=device, ) self.spec_query_start_loc = torch.empty( (self.decode_cudagraph_max_bs + 1,), dtype=torch.int32, device=device, ) self.non_spec_query_start_loc = torch.empty( (self.decode_cudagraph_max_bs + 1,), dtype=torch.int32, device=device, ) self.num_accepted_tokens = torch.empty( (self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device, ) def build( # type: ignore[override] self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, num_accepted_tokens: torch.Tensor | None = None, num_decode_draft_tokens_cpu: torch.Tensor | None = None, fast_build: bool = False, ) -> GDNAttentionMetadata: m = common_attn_metadata query_start_loc = m.query_start_loc context_lens = m.num_computed_tokens_cpu context_lens_tensor = context_lens.to(query_start_loc.device, non_blocking=True) nums_dict, batch_ptr, token_chunk_offset_ptr = None, None, None if ( not self.use_spec_decode or num_decode_draft_tokens_cpu is None or num_decode_draft_tokens_cpu[num_decode_draft_tokens_cpu >= 0] .sum() .item() == 0 ): spec_sequence_masks = None num_spec_decodes = 0 else: spec_sequence_masks = num_decode_draft_tokens_cpu >= 0 num_spec_decodes = spec_sequence_masks.sum().item() if num_spec_decodes == 0: spec_sequence_masks = None else: spec_sequence_masks = spec_sequence_masks.to( query_start_loc.device, non_blocking=True ) if spec_sequence_masks is None: num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( split_decodes_and_prefills(m, decode_threshold=1) ) num_spec_decode_tokens = 0 spec_token_indx = None non_spec_token_indx = None spec_state_indices_tensor = None non_spec_state_indices_tensor = m.block_table_tensor[:, 0] spec_query_start_loc = None non_spec_query_start_loc = query_start_loc num_accepted_tokens = None else: query_lens = query_start_loc[1:] - query_start_loc[:-1] non_spec_query_lens = query_lens[~spec_sequence_masks] num_decodes = (non_spec_query_lens == 1).sum().item() num_prefills = non_spec_query_lens.size(0) - num_decodes num_decode_tokens = num_decodes num_prefill_tokens = non_spec_query_lens.sum().item() - num_decode_tokens num_spec_decode_tokens = ( query_lens.sum().item() - num_prefill_tokens - num_decode_tokens ) if num_prefills == 0 and num_decodes == 0: spec_token_size = min( num_spec_decodes * (self.num_spec + 1), query_start_loc[-1].item(), ) spec_token_indx = torch.arange( spec_token_size, dtype=torch.int32, device=query_start_loc.device, ) non_spec_token_indx = torch.empty( 0, dtype=torch.int32, device=query_start_loc.device ) spec_state_indices_tensor = m.block_table_tensor[:, : self.num_spec + 1] non_spec_state_indices_tensor = None spec_query_start_loc = query_start_loc non_spec_query_start_loc = None else: spec_token_masks = torch.repeat_interleave( spec_sequence_masks, query_lens ) index = torch.argsort(spec_token_masks, stable=True) num_non_spec_tokens = num_prefill_tokens + num_decode_tokens non_spec_token_indx = index[:num_non_spec_tokens] spec_token_indx = index[num_non_spec_tokens:] spec_state_indices_tensor = m.block_table_tensor[ spec_sequence_masks, : self.num_spec + 1 ] non_spec_state_indices_tensor = m.block_table_tensor[ ~spec_sequence_masks, 0 ] spec_query_start_loc = torch.zeros( num_spec_decodes + 1, dtype=torch.int32, device=query_start_loc.device, ) torch.cumsum( query_lens[spec_sequence_masks], dim=0, out=spec_query_start_loc[1:] ) non_spec_query_start_loc = torch.zeros( query_lens.size(0) - num_spec_decodes + 1, dtype=torch.int32, device=query_start_loc.device, ) torch.cumsum( query_lens[~spec_sequence_masks], dim=0, out=non_spec_query_start_loc[1:], ) assert num_accepted_tokens is not None num_accepted_tokens = num_accepted_tokens[spec_sequence_masks] if num_prefills > 0: has_initial_state = context_lens_tensor > 0 if spec_sequence_masks is not None: has_initial_state = has_initial_state[~spec_sequence_masks] nums_dict, batch_ptr, token_chunk_offset_ptr = ( compute_causal_conv1d_metadata(non_spec_query_start_loc) ) else: has_initial_state = None # Prepare tensors for cudagraph # Note: m.num_actual_tokens is already padded by the model runner for CUDAGraph batch_size = m.num_actual_tokens if ( self.use_full_cuda_graph and num_prefills == 0 and num_decodes == 0 and num_spec_decodes <= self.decode_cudagraph_max_bs and num_spec_decode_tokens <= self.decode_cudagraph_max_bs ): self.spec_state_indices_tensor[:num_spec_decodes].copy_( spec_state_indices_tensor, non_blocking=True ) spec_state_indices_tensor = self.spec_state_indices_tensor[:batch_size] spec_state_indices_tensor[num_spec_decodes:].fill_(PAD_SLOT_ID) self.spec_sequence_masks[:num_spec_decodes].copy_( spec_sequence_masks, non_blocking=True ) spec_sequence_masks = self.spec_sequence_masks[:batch_size] spec_sequence_masks[num_spec_decodes:].fill_(False) assert non_spec_token_indx is not None and spec_token_indx is not None self.non_spec_token_indx[: non_spec_token_indx.size(0)].copy_( non_spec_token_indx, non_blocking=True ) non_spec_token_indx = self.non_spec_token_indx[ : non_spec_token_indx.size(0) ] self.spec_token_indx[: spec_token_indx.size(0)].copy_( spec_token_indx, non_blocking=True ) spec_token_indx = self.spec_token_indx[: spec_token_indx.size(0)] self.spec_query_start_loc[: num_spec_decodes + 1].copy_( spec_query_start_loc, non_blocking=True ) spec_num_query_tokens = spec_query_start_loc[-1] # type: ignore[index] spec_query_start_loc = self.spec_query_start_loc[: batch_size + 1] spec_query_start_loc[num_spec_decodes + 1 :].fill_(spec_num_query_tokens) self.num_accepted_tokens[:num_spec_decodes].copy_( num_accepted_tokens, non_blocking=True ) num_accepted_tokens = self.num_accepted_tokens[:batch_size] num_accepted_tokens[num_spec_decodes:].fill_(1) if ( self.use_full_cuda_graph and num_prefills == 0 and num_spec_decodes == 0 and num_decodes <= self.decode_cudagraph_max_bs ): self.non_spec_state_indices_tensor[:num_decodes].copy_( non_spec_state_indices_tensor, non_blocking=True ) non_spec_state_indices_tensor = self.non_spec_state_indices_tensor[ :batch_size ] non_spec_state_indices_tensor[num_decodes:].fill_(PAD_SLOT_ID) self.non_spec_query_start_loc[: num_decodes + 1].copy_( non_spec_query_start_loc, non_blocking=True ) non_spec_num_query_tokens = non_spec_query_start_loc[-1] # type: ignore[index] non_spec_query_start_loc = self.non_spec_query_start_loc[: batch_size + 1] non_spec_query_start_loc[num_decodes + 1 :].fill_(non_spec_num_query_tokens) attn_metadata = GDNAttentionMetadata( num_prefills=num_prefills, num_prefill_tokens=num_prefill_tokens, num_decodes=num_decodes, num_decode_tokens=num_decode_tokens, num_spec_decodes=num_spec_decodes, num_spec_decode_tokens=num_spec_decode_tokens, num_actual_tokens=m.num_actual_tokens, has_initial_state=has_initial_state, spec_query_start_loc=spec_query_start_loc, non_spec_query_start_loc=non_spec_query_start_loc, spec_state_indices_tensor=spec_state_indices_tensor, non_spec_state_indices_tensor=non_spec_state_indices_tensor, spec_sequence_masks=spec_sequence_masks, spec_token_indx=spec_token_indx, non_spec_token_indx=non_spec_token_indx, num_accepted_tokens=num_accepted_tokens, nums_dict=nums_dict, batch_ptr=batch_ptr, token_chunk_offset_ptr=token_chunk_offset_ptr, ) return attn_metadata def build_for_cudagraph_capture( self, common_attn_metadata: CommonAttentionMetadata ): """ This method builds the metadata for full cudagraph capture. Currently, only decode is supported for full cudagraphs with Mamba. """ m = common_attn_metadata assert ( m.num_reqs <= self.decode_cudagraph_max_bs and m.num_actual_tokens <= self.decode_cudagraph_max_bs ), ( f"GDN only supports decode-only full CUDAGraph capture. " f"Make sure batch size ({m.num_reqs}) <= " f"cudagraph capture sizes ({self.decode_cudagraph_max_bs}), " f"and number of tokens ({m.num_actual_tokens}) <= " f"cudagraph capture sizes ({self.decode_cudagraph_max_bs})." ) num_accepted_tokens = torch.diff(m.query_start_loc) num_decode_draft_tokens_cpu = (num_accepted_tokens - 1).cpu() m._num_computed_tokens_cpu = m.seq_lens_cpu - num_accepted_tokens.cpu() return self.build(0, m, num_accepted_tokens, num_decode_draft_tokens_cpu)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mamba2_attn.py
vllm/v1/attention/backends/mamba2_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import itertools from dataclasses import dataclass, replace import torch from vllm.attention.backends.abstract import AttentionBackend from vllm.config import VllmConfig from vllm.utils.math_utils import cdiv from vllm.v1.attention.backends.mamba_attn import ( BaseMambaAttentionMetadata, BaseMambaAttentionMetadataBuilder, ) from vllm.v1.attention.backends.utils import ( CommonAttentionMetadata, ) from vllm.v1.kv_cache_interface import AttentionSpec def compute_varlen_chunk_metadata( query_start_loc: torch.Tensor, chunk_size: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Build chunk-aligned, variable-length metadata used by Mamba2 SSD kernels. Given per-sequence cumulative token starts `query_start_loc` of shape [B+1] and a physical `chunk_size`, returns three tensors on the same device: - cu_chunk_seqlens: (nchunks+1,) int32 exclusive prefix-sum of logical-chunk lengths (each logical chunk never crosses a sequence or physical-chunk boundary). - last_chunk_indices: (B,) int32 index of the last logical chunk for each sequence (=-1 for empty sequences). - seq_idx_chunks: (nchunks,) int32 sequence index for each logical chunk in order. This is intentionally lightweight and CPU-side; it mirrors the metadata produced by the V1 Mamba2 meta-data builder and is exported so tests (and other callers) can avoid duplicating the logic. """ assert query_start_loc.ndim == 1, "query_start_loc must be 1-D [B+1]" assert int(query_start_loc[0].item()) == 0, "query_start_loc[0] must be 0" device = query_start_loc.device qsl64 = query_start_loc.to(torch.int64) starts = qsl64[:-1].tolist() ends = qsl64[1:].tolist() total = int(qsl64[-1].item()) chunk_lens: list[int] = [] seq_idx_chunks: list[int] = [] last_chunk_indices: list[int] = [-1] * len(starts) for b, (s, e) in enumerate(zip(starts, ends)): if e <= s: # empty sequence continue pos = s while pos < e: # split at both sequence boundaries and physical chunk boundaries room = chunk_size - (pos % chunk_size) take = min(room, e - pos) chunk_lens.append(int(take)) seq_idx_chunks.append(b) last_chunk_indices[b] = len(chunk_lens) - 1 pos += take # Exclusive prefix sum over logical-chunk lengths if chunk_lens: cu_chunk_seqlens = torch.tensor( [0] + list(itertools.accumulate(chunk_lens)), device=device, dtype=torch.int32, ) # Final boundary must equal total tokens assert int(cu_chunk_seqlens[-1].item()) == total else: cu_chunk_seqlens = torch.tensor([0], device=device, dtype=torch.int32) last_chunk_indices_t = ( torch.tensor(last_chunk_indices, device=device, dtype=torch.int32) if len(starts) > 0 else torch.empty((0,), device=device, dtype=torch.int32) ) seq_idx_chunks_t = torch.tensor(seq_idx_chunks, device=device, dtype=torch.int32) return cu_chunk_seqlens, last_chunk_indices_t, seq_idx_chunks_t class Mamba2AttentionBackend(AttentionBackend): @staticmethod def get_builder_cls() -> type["Mamba2AttentionMetadataBuilder"]: return Mamba2AttentionMetadataBuilder @dataclass class Mamba2AttentionMetadata(BaseMambaAttentionMetadata): prep_initial_states: bool = False chunk_size: int = 0 # Chunk-related metadata (only for prefill) seq_idx_p: torch.Tensor | None = None # cu_chunk_seqlen_p is a tensor of shape (nchunks+1,) that contains, for # each chunk, its offests into the varlen sequence dimension. It is defined # such that the i-th chunk contains tokens from cu_chunk_seqlen_p[i] to # cu_chunk_seqlen_p[i+1]. cu_chunk_seqlen_p: torch.Tensor | None = None # last_chunk_indices_p is a tensor of shape (batch,) that contains the # index of the last chunk for every sequence in the (prefill) batch. last_chunk_indices_p: torch.Tensor | None = None class Mamba2AttentionMetadataBuilder( BaseMambaAttentionMetadataBuilder[Mamba2AttentionMetadata] ): metadata_cls = Mamba2AttentionMetadata def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.chunk_size = vllm_config.model_config.get_mamba_chunk_size() assert self.chunk_size is not None, ( "chunk_size needs to be set in the model config for Mamba2 models" ) def _compute_chunk_metadata( self, num_prefills: int, num_computed_tokens_p_cpu: torch.Tensor, query_start_loc_p_cpu: torch.Tensor, ) -> tuple[list[int], list[int], list[int]]: """ Compute chunk-specific metadata for Mamba2. The code below carefully constructs the chunks such that: 1. Chunks contain tokens from a *single* sequence only. 2. For every sequence, we are guaranteed that we can retrieve the mamba state *every* chunk_size tokens. Constraint (1) dramatically simplifies the mamba2 kernels. Constraint (2) dramatically simplifies the implementation of prefix caching for mamba2 (wip). We need to take care of the interaction with chunked prefill in order to satisfy constraint (2). """ # TODO (tdoublep): This code could probably be optimized. cu_chunk_seqlen = [] seq_idx = [] last_chunk_indices = [] seqlen_pos = 0 for req_idx in range(num_prefills): this_num_computed = num_computed_tokens_p_cpu[req_idx].item() this_new_tokens = ( query_start_loc_p_cpu[req_idx + 1].item() - query_start_loc_p_cpu[req_idx].item() ) # if computed tokens are not chunk-aligned, use the first # chunk to finish it off if this_num_computed % self.chunk_size != 0: seq_idx.append(req_idx) cu_chunk_seqlen.append(seqlen_pos) # how many tokens to finish the chunk? chunk_len = ( cdiv(this_num_computed, self.chunk_size) * self.chunk_size - this_num_computed ) # we can only use at most this_new_tokens chunk_len = min(chunk_len, this_new_tokens) seqlen_pos += chunk_len this_new_tokens -= chunk_len n_chunks = cdiv(this_new_tokens, self.chunk_size) for chunk in range(n_chunks): seq_idx.append(req_idx) cu_chunk_seqlen.append(seqlen_pos) chunk_len = min(self.chunk_size, this_new_tokens) seqlen_pos += chunk_len this_new_tokens -= chunk_len assert this_new_tokens == 0 last_chunk_indices.append(len(cu_chunk_seqlen) - 1) cu_chunk_seqlen.append(seqlen_pos) return cu_chunk_seqlen, seq_idx, last_chunk_indices def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> Mamba2AttentionMetadata: common = self._compute_common_metadata(common_attn_metadata) seq_idx_p = None cu_chunk_seqlen_p = None last_chunk_indices_p = None prep_initial_states = False # Compute seq_idx for prefill only if common.num_prefills > 0: prep_initial_states = ( torch.any(common.has_initial_states_p).item() if common.has_initial_states_p is not None else False ) num_reqs = common.num_reqs num_prefills = common.num_prefills num_decode_tokens = common.num_decode_tokens num_computed_tokens_p_cpu = common_attn_metadata.num_computed_tokens_cpu[ num_reqs - num_prefills : num_reqs ] query_start_loc_p_cpu = ( common_attn_metadata.query_start_loc_cpu[-num_prefills - 1 :] - num_decode_tokens ) cu_chunk_seqlen, seq_idx, last_chunk_indices = self._compute_chunk_metadata( num_prefills, num_computed_tokens_p_cpu, query_start_loc_p_cpu, ) seq_idx_p = torch.as_tensor( seq_idx, device=common_attn_metadata.query_start_loc.device, dtype=torch.int32, ) cu_chunk_seqlen_p = torch.as_tensor( cu_chunk_seqlen, device=common_attn_metadata.query_start_loc.device, dtype=torch.int32, ) last_chunk_indices_p = torch.as_tensor( last_chunk_indices, device=common_attn_metadata.query_start_loc.device, dtype=torch.int32, ) return replace( common, prep_initial_states=prep_initial_states, chunk_size=self.chunk_size, seq_idx_p=seq_idx_p, cu_chunk_seqlen_p=cu_chunk_seqlen_p, last_chunk_indices_p=last_chunk_indices_p, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/triton_attn.py
vllm/v1/attention/backends/triton_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """High-Performance Triton-only Attention layer.""" from dataclasses import dataclass from typing import ClassVar import torch from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionType, MultipleOf, ) from vllm.attention.ops.triton_reshape_and_cache_flash import ( triton_reshape_and_cache_flash, ) from vllm.attention.ops.triton_unified_attention import unified_attention from vllm.config import CUDAGraphMode, VllmConfig from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.model_executor.layers.quantization.utils.quant_utils import ( QuantKey, kFp8StaticTensorSym, ) from vllm.platforms import current_platform from vllm.platforms.interface import DeviceCapability from vllm.utils.math_utils import next_power_of_2 from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, ) from vllm.v1.kv_cache_interface import AttentionSpec logger = init_logger(__name__) # constants MIN_LAUNCH_GRID_SIZE_2D = 128 # Minimum launch grid size of 2D kernel NUM_PAR_SOFTMAX_SEGMENTS = 16 # Number of parallel tiled softmax segments @dataclass class TritonAttentionMetadata: # NOTE(sang): Definition of context_len, query_len, and seq_len. # |---------- N-1 iteration --------| # |---------------- N iteration ---------------------| # |- tokenA -|......................|-- newTokens ---| # |---------- context_len ----------| # |-------------------- seq_len ---------------------| # |-- query_len ---| num_actual_tokens: int # Number of tokens excluding padding. max_query_len: int query_start_loc: torch.Tensor max_seq_len: int seq_lens: torch.Tensor block_table: torch.Tensor slot_mapping: torch.Tensor seq_threshold_3D: int num_par_softmax_segments: int softmax_segm_output: torch.Tensor softmax_segm_max: torch.Tensor softmax_segm_expsum: torch.Tensor # For cascade attention. use_cascade: bool common_prefix_len: int cu_prefix_query_lens: torch.Tensor | None prefix_kv_lens: torch.Tensor | None suffix_kv_lens: torch.Tensor | None # Optional aot scheduling scheduler_metadata: torch.Tensor | None = None prefix_scheduler_metadata: torch.Tensor | None = None mm_prefix_range: dict[int, list[tuple[int, int]]] | None = None @property def mm_prefix_range_tensor(self) -> torch.Tensor | None: """Convert mm_prefix_range dict to padded tensor for Triton kernel. Returns shape: (num_seqs, max_ranges, 2) with 0-padding for empty ranges. Empty ranges have start==end==0, which kernel skips via is_valid check. """ # TODO(Isotr0py): Move to model runner's attention metadata # preparation to avoid duplicate computation. if self.mm_prefix_range is None: return None num_seqs = self.seq_lens.shape[0] device = self.seq_lens.device # Collect ranges, using [(0,0)] for empty sequences to ensure uniform dims range_lists = [ self.mm_prefix_range.get(i, [(0, 0)]) or [(0, 0)] for i in range(num_seqs) ] # Return None if all ranges are trivial (only (0,0) placeholders) if all(r == [(0, 0)] for r in range_lists): return None # Create 2D tensors with shape (num_ranges, 2) for each sequence range_tensors = [ torch.tensor(r, dtype=torch.int32, device=device).view(-1, 2) for r in range_lists ] return torch.nested.nested_tensor(range_tensors).to_padded_tensor(0) class TritonAttentionMetadataBuilder(AttentionMetadataBuilder[TritonAttentionMetadata]): _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.block_size = kv_cache_spec.block_size model_config = vllm_config.model_config self.num_heads_q = model_config.get_num_attention_heads( vllm_config.parallel_config ) self.num_heads_kv = model_config.get_num_kv_heads(vllm_config.parallel_config) self.headdim = model_config.get_head_size() # Check if CUDA Graphs are enabled for decode self.decode_cudagraph_enabled = ( self.vllm_config.compilation_config.cudagraph_mode in ( CUDAGraphMode.FULL_AND_PIECEWISE, CUDAGraphMode.FULL_DECODE_ONLY, CUDAGraphMode.FULL, ) ) # The launch grid for the 2D kernel is defined as (num_q_blocks, num_heads_kv). # A lower bound for num_q_blocks is the number of sequences. # To ensure the minimum launch grid size is achieved, the number of sequences # must be at least equal to the threshold below. # If this threshold is not reached (i.e., the batch size is not large enough), # the 3D kernel will be selected instead. self.seq_threshold_3D = MIN_LAUNCH_GRID_SIZE_2D // self.num_heads_kv # Modify the threshold if needed. if self.decode_cudagraph_enabled: capture_sizes = self.vllm_config.compilation_config.cudagraph_capture_sizes assert capture_sizes, "CUDA Graphs enabled but no capture sizes specified." # Select the CUDA Graph capture size closest to self.seq_threshold_3D # as threshold. This ensures that each captured graph covers the # correct execution path. self.seq_threshold_3D = min( capture_sizes, key=lambda x: abs(x - self.seq_threshold_3D), ) self.num_par_softmax_segments = NUM_PAR_SOFTMAX_SEGMENTS headdim_padded = next_power_of_2(self.headdim) self.softmax_segm_output = torch.empty( ( self.seq_threshold_3D, self.num_heads_q, self.num_par_softmax_segments, headdim_padded, ), dtype=torch.float32, device=device, ) self.softmax_segm_max = torch.empty( (self.seq_threshold_3D, self.num_heads_q, self.num_par_softmax_segments), dtype=torch.float32, device=device, ) self.softmax_segm_expsum = torch.empty( (self.seq_threshold_3D, self.num_heads_q, self.num_par_softmax_segments), dtype=torch.float32, device=device, ) def build_for_cudagraph_capture( self, common_attn_metadata: CommonAttentionMetadata ) -> TritonAttentionMetadata: attn_metadata = self.build(0, common_attn_metadata) # When doing full graph capture, setting seq_lens to # max_model_len will cause graph capture to be extremely # slow, so here we set it to 1. attn_metadata.seq_lens.fill_(1) return attn_metadata def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> TritonAttentionMetadata: num_actual_tokens = common_attn_metadata.num_actual_tokens max_query_len = common_attn_metadata.max_query_len max_seq_len = common_attn_metadata.max_seq_len query_start_loc = common_attn_metadata.query_start_loc seq_lens = common_attn_metadata.seq_lens block_table_tensor = common_attn_metadata.block_table_tensor slot_mapping = common_attn_metadata.slot_mapping use_cascade = common_prefix_len > 0 if use_cascade: cu_prefix_query_lens = torch.tensor( [0, num_actual_tokens], dtype=torch.int32, device=self.device ) prefix_kv_lens = torch.tensor( [common_prefix_len], dtype=torch.int32, device=self.device ) suffix_kv_lens = common_attn_metadata.seq_lens_cpu - common_prefix_len suffix_kv_lens = suffix_kv_lens.to(self.device) else: cu_prefix_query_lens = None prefix_kv_lens = None suffix_kv_lens = None prefix_scheduler_metadata = None attn_metadata = TritonAttentionMetadata( num_actual_tokens=num_actual_tokens, max_query_len=max_query_len, query_start_loc=query_start_loc, max_seq_len=max_seq_len, seq_lens=seq_lens, block_table=block_table_tensor, slot_mapping=slot_mapping, use_cascade=use_cascade, common_prefix_len=common_prefix_len, cu_prefix_query_lens=cu_prefix_query_lens, prefix_kv_lens=prefix_kv_lens, suffix_kv_lens=suffix_kv_lens, prefix_scheduler_metadata=prefix_scheduler_metadata, seq_threshold_3D=self.seq_threshold_3D, num_par_softmax_segments=self.num_par_softmax_segments, softmax_segm_output=self.softmax_segm_output, softmax_segm_max=self.softmax_segm_max, softmax_segm_expsum=self.softmax_segm_expsum, ) return attn_metadata class TritonAttentionBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [ torch.float16, torch.bfloat16, torch.float32, ] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ "auto", "fp8", "fp8_e4m3", "fp8_e5m2", ] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [MultipleOf(16)] @staticmethod def get_name() -> str: return "TRITON_ATTN" @staticmethod def get_impl_cls() -> type["TritonAttentionImpl"]: return TritonAttentionImpl @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 (num_blocks, 2, block_size, num_kv_heads, head_size) @staticmethod def use_cascade_attention(*args, **kwargs) -> bool: return False @staticmethod def get_builder_cls() -> type["TritonAttentionMetadataBuilder"]: return TritonAttentionMetadataBuilder @classmethod def supports_head_size(cls, head_size: int) -> bool: return head_size >= 32 @classmethod def supports_mm_prefix(cls) -> bool: return True @classmethod def supports_sink(cls) -> bool: return True @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return True class TritonAttentionImpl(AttentionImpl): 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: self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_kv_heads if alibi_slopes is not None: alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32) self.alibi_slopes = alibi_slopes if sliding_window is None: self.sliding_window = (-1, -1) else: self.sliding_window = (sliding_window - 1, 0) self.kv_cache_dtype = kv_cache_dtype if logits_soft_cap is None: # In flash-attn, setting logits_soft_cap as 0 means no soft cap. logits_soft_cap = 0 self.logits_soft_cap = logits_soft_cap self.kv_sharing_target_layer_name = kv_sharing_target_layer_name self.num_queries_per_kv = self.num_heads // self.num_kv_heads if attn_type not in [AttentionType.DECODER, AttentionType.ENCODER_DECODER]: raise NotImplementedError( "Encoder self-attention is not implemented for TritonAttentionImpl" ) self.attn_type = attn_type self.fp8_dtype = current_platform.fp8_dtype() self.sinks = sinks if sinks is not None: assert sinks.shape[0] == num_heads, ( "Sinks must have the same number of heads as the number of " f"heads in the layer. Sinks shape: {sinks.shape}, " f"num_heads: {num_heads}." ) self.supports_quant_query_input = current_platform.is_cuda() def forward( self, layer: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, attn_metadata: TritonAttentionMetadata, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Forward pass with Paged Attention impl. in Triton. 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 = [num_blocks, 2, 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 TritonAttentionImpl" ) 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 key_cache, value_cache = kv_cache.unbind(1) if ( self.kv_sharing_target_layer_name is None and key is not None and value is not None ): # Reshape the input keys and values and store them in the cache. # Skip this if sharing KV cache with an earlier attention layer. if self.kv_cache_dtype.startswith("fp8"): key_cache = key_cache.view(self.fp8_dtype) value_cache = value_cache.view(self.fp8_dtype) # triton kernel does not support uint8 kv_cache # (because some explicit casts (e.g. float8_e4m3fnuz) # are not supported) triton_reshape_and_cache_flash( key, value, key_cache, value_cache, attn_metadata.slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) if self.kv_cache_dtype.startswith("fp8"): if key_cache.dtype != self.fp8_dtype: 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 seq_threshold_3D = attn_metadata.seq_threshold_3D num_par_softmax_segments = attn_metadata.num_par_softmax_segments softmax_segm_output = attn_metadata.softmax_segm_output softmax_segm_max = attn_metadata.softmax_segm_max softmax_segm_expsum = attn_metadata.softmax_segm_expsum descale_shape = (cu_seqlens_q.shape[0] - 1, key_cache.shape[2]) mm_prefix_range_tensor = attn_metadata.mm_prefix_range_tensor 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), seq_threshold_3D=seq_threshold_3D, num_par_softmax_segments=num_par_softmax_segments, softmax_segm_output=softmax_segm_output, softmax_segm_max=softmax_segm_max, softmax_segm_expsum=softmax_segm_expsum, sinks=self.sinks, output_scale=output_scale, mm_prefix_range=mm_prefix_range_tensor, ) return output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/pallas.py
vllm/v1/attention/backends/pallas.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass import torch from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionLayer, AttentionType, ) from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.utils.math_utils import cdiv, next_power_of_2 logger = init_logger(__name__) # TPU requires the head size to be a multiple of 128. TPU_HEAD_SIZE_ALIGNMENT = 128 # Note: TPU can fp8 as storage dtype but doesn't support converting from uint8 # from to fp32 directly. That's why it has a dtype mapping different from GPU TPU_STR_DTYPE_TO_TORCH_DTYPE = { "half": torch.half, "bfloat16": torch.bfloat16, "float": torch.float, "fp8": torch.float8_e4m3fn, "fp8_e4m3": torch.float8_e4m3fn, "fp8_e5m2": torch.float8_e5m2, "int8": torch.int8, "uint8": torch.uint8, } try: import tpu_inference # noqa: F401 except ImportError: # Lazy import torch_xla import torch_xla.core.xla_builder as xb import torch_xla.experimental.custom_kernel # noqa: F401 from torch.library import impl from torch_xla._internal.jax_workarounds import requires_jax from torch_xla.experimental.custom_kernel import XLA_LIB @requires_jax def kv_cache_update_op_impl( kv: torch.Tensor, slot_mapping: torch.Tensor, kv_cache: torch.Tensor, num_kv_update_slices: torch.Tensor, page_size: int, num_slices_per_block: int, ): from vllm.attention.ops.pallas_kv_cache_update import kv_cache_update new_kv_cache = xb.call_jax( kv_cache_update, (kv, slot_mapping, kv_cache, num_kv_update_slices), {"page_size": page_size, "num_slices_per_block": num_slices_per_block}, ) return new_kv_cache XLA_LIB.define( "kv_cache_update_op(Tensor kv, Tensor slot_mapping," "Tensor kv_cache, Tensor num_kv_update_slices, int page_size," "int num_slices_per_block)" "-> Tensor", ) @impl(XLA_LIB, "kv_cache_update_op", "XLA") def kv_cache_update_op_xla( kv: torch.Tensor, slot_mapping: torch.Tensor, kv_cache: torch.Tensor, num_kv_update_slices: torch.Tensor, page_size: int, num_slices_per_block: int, ) -> torch.Tensor: new_kv_cache = kv_cache_update_op_impl( kv, slot_mapping, kv_cache, num_kv_update_slices, page_size, num_slices_per_block, ) return new_kv_cache @impl(XLA_LIB, "kv_cache_update_op", "CompositeExplicitAutograd") def kv_cache_update_op_non_xla( kv: torch.Tensor, slot_mapping: torch.Tensor, kv_cache: torch.Tensor, num_kv_update_slices: torch.Tensor, page_size: int, num_slices_per_block: int, ) -> torch.Tensor: return kv_cache class PallasAttentionBackend(AttentionBackend): @staticmethod def get_name() -> str: return "PALLAS" @staticmethod def get_impl_cls() -> type["PallasAttentionBackendImpl"]: return PallasAttentionBackendImpl @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, ...]: padded_head_size = ( cdiv(head_size, TPU_HEAD_SIZE_ALIGNMENT) * TPU_HEAD_SIZE_ALIGNMENT ) return (num_blocks, block_size, num_kv_heads * 2, padded_head_size) @staticmethod def swap_blocks( src_kv_cache: torch.Tensor, dst_kv_cache: torch.Tensor, src_to_dst: torch.Tensor, ) -> None: raise RuntimeError("swap_blocks is not used for the TPU backend.") # In recent TPU generations, up to v6e, the SMEM size is 1MB. The # block_tables within the PallasMetadata constitute almost the entire SMEM # requirement. Its size is max_num_seqs * num_page_per_seq * 4 (Int). Here # we simply make sure that the size is smaller than half of SMEM capacity. @staticmethod def get_min_page_size(vllm_config: VllmConfig) -> int: max_num_page_per_req = ( 1024 * 1024 // 2 // vllm_config.scheduler_config.max_num_seqs // 4 ) min_page_size = cdiv( vllm_config.model_config.max_model_len, max_num_page_per_req ) min_page_size = 1 << (min_page_size - 1).bit_length() return min_page_size @staticmethod def get_max_num_seqs(model_len: int, page_size: int) -> int: num_page_per_req = cdiv(model_len, page_size) return 1024 * 1024 // 2 // num_page_per_req // 4 # TPU has limited SREGs (scalar registers), if page_size is too small, we # can spill SREGs easily which leads to bad performance. The strategy we # apply here is trying to split max-model-len to 16 pages which make the # spill less likely. Meanwhile we make sure the page size is in [16, 256]. @staticmethod def get_page_size(vllm_config: VllmConfig) -> int: # TODO: This is a temporary fix for vmem OOM. # For long model length, we use 16 page-size to avoid too much # VMEM spill. A more robust solution should be implemented to # handle VREG spills. if vllm_config.model_config.max_model_len > 8192: return 16 page_size = next_power_of_2(vllm_config.model_config.max_model_len) // 16 if page_size <= 16: return 16 if page_size >= 256: return 256 return page_size @dataclass class PallasMetadata: # NOTE(sang): Definition of context_len, query_len, and seq_len. # |---------- N-1 iteration --------| # |---------------- N iteration ---------------------| # |- tokenA -|......................|-- newTokens ---| # |---------- context_len ----------| # |-------------------- seq_len ---------------------| # |-- query_len ---| # Used in the PallasAttentionBackendImpl slot_mapping: torch.Tensor block_tables: torch.Tensor context_lens: torch.Tensor query_start_loc: torch.Tensor num_seqs: torch.Tensor num_kv_update_slices: torch.Tensor num_slices_per_kv_cache_update_block: int class PallasAttentionBackendImpl(AttentionImpl): 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: str = AttentionType.DECODER, kv_sharing_target_layer_name: int | None = None, ) -> None: self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_kv_heads self.sliding_window = sliding_window self.logits_soft_cap = logits_soft_cap self.kv_sharing_target_layer_name = kv_sharing_target_layer_name self.num_queries_per_kv = self.num_heads // self.num_kv_heads if alibi_slopes is not None: raise NotImplementedError("Alibi slopes is not supported.") if attn_type != AttentionType.DECODER: raise NotImplementedError( "Encoder self-attention and " "encoder/decoder cross-attention " "are not implemented for " "PallasAttentionBackendImpl" ) self.kv_cache_quantized_dtype = None if kv_cache_dtype != "auto": self.kv_cache_quantized_dtype = TPU_STR_DTYPE_TO_TORCH_DTYPE.get( kv_cache_dtype.lower().strip() ) def forward( self, layer: AttentionLayer, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, attn_metadata: PallasMetadata, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Forward pass with Pallas attention. 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 = [num_blocks, block_size, num_kv_heads * 2, head_size] attn_metadata: Metadata for attention. Returns: shape = [num_tokens, num_heads * head_size] """ if output_scale is not None or output_block_scale is not None: raise NotImplementedError( "fused output quantization is not yet supported" " for PallasAttentionBackendImpl" ) # For determine_available_memory case. if kv_cache.numel() == 0: if output is None: output = torch.ones_like(query) return output num_tokens, hidden_size = query.shape query = query.view(num_tokens, self.num_heads, self.head_size) key = key.view(-1, self.num_kv_heads, self.head_size) value = value.view(-1, self.num_kv_heads, self.head_size) if self.head_size % TPU_HEAD_SIZE_ALIGNMENT != 0: padded_head_size = ( cdiv(self.head_size, TPU_HEAD_SIZE_ALIGNMENT) * TPU_HEAD_SIZE_ALIGNMENT ) query = torch.nn.functional.pad( query, (0, padded_head_size - self.head_size), value=0.0 ) key = torch.nn.functional.pad( key, (0, padded_head_size - self.head_size), value=0.0 ) value = torch.nn.functional.pad( value, (0, padded_head_size - self.head_size), value=0.0 ) if self.kv_sharing_target_layer_name is None and kv_cache.numel() > 0: # Write input keys and values to the KV cache. # Skip this if sharing KV cache with an earlier attention layer. slot_mapping = attn_metadata.slot_mapping write_to_kv_cache( key, value, kv_cache, slot_mapping, attn_metadata.num_slices_per_kv_cache_update_block, attn_metadata.num_kv_update_slices, self.kv_cache_quantized_dtype, layer._k_scale_float, layer._v_scale_float, ) if self.kv_cache_quantized_dtype is not None and ( layer._k_scale_float == 0.0 or layer._v_scale_float == 0.0 ): raise ValueError("k_scale_float and v_scale_float must be non-zero") output = torch.ops.xla.ragged_paged_attention( query, kv_cache, attn_metadata.context_lens, attn_metadata.block_tables, attn_metadata.query_start_loc, attn_metadata.num_seqs, # By default, the system utilizes optimized block size and # vmem_limit_bytes parameters from the kernel repository. However, # these can be manually adjusted for debugging if necessary. num_kv_pages_per_block=None, num_queries_per_block=None, vmem_limit_bytes=None, use_kernel=True, sm_scale=self.scale, sliding_window=self.sliding_window, soft_cap=self.logits_soft_cap, k_scale=layer._k_scale_float, v_scale=layer._v_scale_float, ) if self.head_size % TPU_HEAD_SIZE_ALIGNMENT != 0: output = output[:, :, : self.head_size] return output.reshape(num_tokens, hidden_size) def write_to_kv_cache( key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, slot_mapping: torch.Tensor, num_slices_per_kv_cache_update_block: int, num_kv_update_slices: torch.Tensor, kv_cache_quantized_dtype: torch.dtype | None = None, k_scale: float = 1.0, v_scale: float = 1.0, ) -> None: """Write the key and values to the KV cache. Args: key: shape = [num_tokens, num_kv_heads, head_size] value: shape = [num_tokens, num_kv_heads, head_size] kv_cache: shape = [num_blocks, block_size, num_kv_heads * 2, head_size] num_slices_per_kv_cache_update_block: int """ _, page_size, num_combined_kv_heads, head_size = kv_cache.shape head_size = cdiv(head_size, TPU_HEAD_SIZE_ALIGNMENT) * TPU_HEAD_SIZE_ALIGNMENT if kv_cache_quantized_dtype is not None: dtype_info = torch.finfo(kv_cache_quantized_dtype) key = key.to(torch.float32) / k_scale # NOTE: clamp is added here to avoid out of range of quantized dtype key = torch.clamp(key, dtype_info.min, dtype_info.max) key = key.to(kv_cache_quantized_dtype) value = value.to(torch.float32) / v_scale value = torch.clamp(value, dtype_info.min, dtype_info.max) value = value.to(kv_cache_quantized_dtype) kv = torch.cat([key, value], axis=-1).reshape(-1, num_combined_kv_heads, head_size) torch.ops.xla.dynamo_set_buffer_donor_(kv_cache, True) kv_cache = kv_cache.flatten(0, 1) new_kv_cache = torch.ops.xla.kv_cache_update_op( kv, slot_mapping, kv_cache, num_kv_update_slices, page_size, num_slices_per_kv_cache_update_block, ) # NOTE: the in-place copy will be optimized away by XLA compiler. kv_cache.copy_(new_kv_cache) # We can move this function to a common utils file if it's also useful for other # hardware. def dtype_bits(dtype: torch.dtype): if dtype.is_floating_point: try: return torch.finfo(dtype).bits except TypeError: pass elif dtype.is_complex: if dtype is torch.complex32: return 32 elif dtype is torch.complex64: return 64 elif dtype is torch.complex128: return 128 else: try: return torch.iinfo(dtype).bits # torch.iinfo cannot support int4, int2, bits8... except TypeError: pass str_dtype = str(dtype) # support torch.int4, torch.int5, torch.uint5... if str_dtype.startswith("torch.int") or str_dtype.startswith("torch.uint"): return int(str_dtype[-1]) raise TypeError(f"Getting the bit width of {dtype} is not supported") def get_dtype_packing(dtype): bits = dtype_bits(dtype) if 32 % bits != 0: raise ValueError( f"The bit width must be divisible by 32, but got bits={bits}, " "dtype={dtype}" ) return 32 // bits def get_page_size_bytes( block_size: int, num_kv_heads: int, head_size: int, kv_cache_dtype: torch.dtype ) -> int: """Returns the size in bytes of one page of the KV cache.""" padded_head_size = ( cdiv(head_size, TPU_HEAD_SIZE_ALIGNMENT) * TPU_HEAD_SIZE_ALIGNMENT ) num_combined_kv_heads = num_kv_heads * 2 # NOTE: for the implicit padding in XLA packing = get_dtype_packing(kv_cache_dtype) num_combined_kv_heads = cdiv(num_combined_kv_heads, packing) * packing kv_cache_dtype_bits = dtype_bits(kv_cache_dtype) return ( block_size * num_combined_kv_heads * padded_head_size * kv_cache_dtype_bits // 8 )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/flex_attention.py
vllm/v1/attention/backends/flex_attention.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with FlexAttention.""" import math from dataclasses import dataclass from functools import cached_property from typing import ClassVar import torch import torch._dynamo.decorators import torch.nn.functional as F from torch.nn.attention.flex_attention import ( BlockMask, _mask_mod_signature, _score_mod_signature, and_masks, create_block_mask, flex_attention, or_masks, ) from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionType, is_quantized_kv_cache, ) from vllm.config import VllmConfig from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.platforms import current_platform from vllm.utils.math_utils import cdiv from vllm.utils.torch_utils import is_torch_equal_or_newer from vllm.v1.attention.backends.utils import ( AttentionMetadataBuilder, CommonAttentionMetadata, ) from vllm.v1.kv_cache_interface import AttentionSpec logger = init_logger(__name__) torch._dynamo.config.recompile_limit = 16 create_block_mask_compiled = torch.compile( create_block_mask, fullgraph=True, mode="reduce-overhead" ) flex_attention_compiled = torch.compile(flex_attention, fullgraph=True) def _offsets_to_doc_ids_tensor(offsets: torch.Tensor) -> torch.Tensor: device = offsets.device counts = offsets[1:] - offsets[:-1] return torch.repeat_interleave( torch.arange(len(counts), device=device, dtype=torch.int32), counts ) def pad_to_multiple(x: torch.Tensor, multiple: int, dim: int): difference = (multiple - (x.shape[dim] % multiple)) % multiple if difference == 0: return x dim = dim if dim >= 0 else x.ndim + dim pad_list = [] for i in range(x.ndim - 1, dim - 1, -1): if i == dim: pad_list.extend([0, difference]) else: pad_list.extend([0, 0]) return F.pad(x, pad_list, mode="constant", value=0) class FlexAttentionBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [ torch.float16, torch.bfloat16, torch.float32, ] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto"] @staticmethod def get_name() -> str: return "FLEX_ATTENTION" @classmethod def supports_attn_type(cls, attn_type: str) -> bool: """FlexAttention supports both decoder and encoder-only attention.""" return attn_type in (AttentionType.DECODER, AttentionType.ENCODER_ONLY) @classmethod def supports_mm_prefix(cls) -> bool: """FlexAttention supports full attention for image tokens.""" return True @staticmethod def get_impl_cls() -> type["FlexAttentionImpl"]: return FlexAttentionImpl @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, ...]: return (2, num_blocks, block_size, num_kv_heads, head_size) @staticmethod def get_builder_cls() -> type["FlexAttentionMetadataBuilder"]: return FlexAttentionMetadataBuilder @staticmethod def use_cascade_attention(*args, **kwargs) -> bool: return False @classmethod def get_supported_head_sizes(cls) -> list[int]: return [] # @torch.compile(fullgraph=True, mode="reduce-overhead") def physical_to_logical_mapping( block_table: torch.Tensor, seq_lens: torch.Tensor, block_size: int, total_blocks: int, ) -> torch.Tensor: """ Creates an inverse mapping from physical block locations to logical indices. The original block_table maps from logical blocks to physical locations: Logical to Physical (Original block_table): ┌───────────────────────────────────────────┐ │ Request 0: │ │ │ │ Logical Blocks: 0 1 2 3 4 5 6 7 │ │ │ │ │ │ │ │ │ │ │ │ v v v v v v v v │ │ Physical Blocks: 3 5 1 7 4 2 0 6 │ └───────────────────────────────────────────┘ This function creates the inverse mapping: Physical to Logical (Inverse mapping): ┌───────────────────────────────────────────┐ │ Request 0: │ │ │ │ Physical Blocks: 0 1 2 3 4 5 6 7 │ │ │ │ │ │ │ │ │ │ │ │ v v v v v v v v │ │ Logical Blocks: 6 2 5 0 4 1 7 3 │ └───────────────────────────────────────────┘ If multiple logical blocks map to the same physical block, this function returns the latest (maximum) logical block index. If a physical block is not mapped to by any logical block, its value in the result will be -1. IMPORTANT: Garbage Value Protection ──────────────────────────────────── The block_table tensor may contain garbage values in unused positions (beyond the actual sequence length). For example, if a sequence only needs 3 blocks but the table has space for 8: block_table[0] = [10, 25, 7, 999, 1234, 888, ...] ^^^^^^^^^^^^^^^^^^^^ garbage values These garbage values can cause issues because: 1. They may map to valid physical blocks by coincidence 2. The scatter_ operation will assign them logical indices 3. Later attention computations may incorrectly access these blocks To prevent this, we use seq_lens and block_size to mask out unused entries, ensuring only valid block references are processed. IMPORTANT: Reused physical blocks (sliding-window / hybrid attention) ──────────────────────────────────────────────────────────────────── For some attention types, physical cache blocks can be reused over time. This can cause the same physical block id to appear multiple times in a row of `block_table` at different logical block indices. In that case, only the latest logical block index corresponds to the current contents of that physical block. Therefore, the inverse mapping must pick the maximum logical block index for each physical block id. Args: block_table: Tensor of shape [max_reqs, max_num_blocks] mapping logical blocks to physical locations. May contain garbage values in unused positions. seq_lens: Tensor of sequence lengths for each request. Used to determine how many blocks are actually needed per sequence. block_size: Size of each block in tokens. Used with seq_lens to compute the number of valid blocks per sequence. total_blocks: Total number of physical blocks available Returns: A tensor of shape [max_reqs, total_blocks] where each entry physical_to_logical[req_id, physical_block] contains the logical block index for that physical block, or -1 if unused. """ max_reqs, max_num_blocks = block_table.shape device = block_table.device physical_to_logical = torch.full( (max_reqs, total_blocks), -1, dtype=torch.long, device=device ) # Only process valid blocks to avoid garbage values num_blocks_per_seq = cdiv(seq_lens, block_size) mask = ( torch.arange(max_num_blocks, device=device)[None, :] < num_blocks_per_seq[:, None] ) valid_block_table = torch.where(mask, block_table, 0) valid_logical_indices = torch.where( mask, torch.arange(max_num_blocks, device=device)[None, :], 0 ) physical_to_logical.scatter_reduce_( -1, valid_block_table.to(torch.int64), valid_logical_indices, reduce="amax" ) # NB - Seems like block 0 is always empty so we reset it manually physical_to_logical[:, 0] = -1 return physical_to_logical def unique_static_unsorted( x: torch.Tensor, *, M: int, # maximum positive value (0 is “skip me”) dim: int = -1, # axis along which to deduplicate ignored_val: int = 0, # value to ignore pad_val: int = -1, # sentinel for unused slots ) -> torch.Tensor: """ - Keeps the first occurrence of each non-zero value while preserving order, then left-packs those uniques and fills the rest with `pad_val`. - Returns (packed, keep_mask) with the *same shape* as `x`. - Requires that all values be in the range [0, M] - Skips ignored_val Works on CPU or GPU, no Python loops, O(B·N) time / O(B·M) memory. Example: x =[3, 1, 0, 1, 2], M=3, ignored_val=0 => [3, 1, 2, -1, -1] """ if not (-1 <= pad_val <= M): raise ValueError("`pad_val` must lie in [-1, M]") # ── move `dim` to the end so we can treat tensor as [B, N] ────────── dim = dim % x.ndim x_perm = x.movedim(dim, -1) # shape [..., N] B, N = x_perm.numel() // x_perm.shape[-1], x_perm.shape[-1] x_flat = x_perm.reshape(B, N) # [B, N] device = x.device idx = torch.arange(N, device=device).expand(B, N) # per-row indices # ── build first-occurrence table for every v ∈ [0, M] ─────────────── first_idx = torch.full((B, M + 1), N, device=device) # “∞” # scatter_reduce_: first_idx[b, v] = min(first_idx[b, v], i) for each i first_idx.scatter_reduce_(1, x_flat, idx, reduce="amin") # ── keep mask: first occurrence *and* value ≠ 0 ───────────────────── keep = (x_flat != ignored_val) & (idx == first_idx.gather(1, x_flat)) # [B, N] # ── left-pack uniques into a fresh tensor ─────────────────────────── dest_pos = torch.cumsum(keep.to(torch.long), dim=1) - 1 # where to go packed_flat = torch.full_like(x_flat, pad_val) rows, src_cols = torch.nonzero(keep, as_tuple=True) packed_flat[rows, dest_pos[rows, src_cols]] = x_flat[rows, src_cols] # ── restore original layout ───────────────────────────────────────── packed = packed_flat.reshape(x_perm.shape).movedim(-1, dim) return packed def causal_mask_mod( b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, kv_idx: torch.Tensor ): return q_idx >= kv_idx @dataclass class FlexAttentionMetadata: causal: bool num_actual_tokens: int # Number of tokens excluding padding. max_query_len: int query_start_loc: torch.Tensor max_seq_len: int seq_lens: torch.Tensor block_table: torch.Tensor slot_mapping: torch.Tensor use_cascade: bool common_prefix_len: int cu_prefix_query_lens: torch.Tensor | None prefix_kv_lens: torch.Tensor | None suffix_kv_lens: torch.Tensor | None # Block info total_cache_tokens: int block_size: int max_possible_sequence_length: int num_reqs: int physical_to_logical: torch.Tensor decode_offset: torch.Tensor num_blocks_per_seq: torch.Tensor # For logging. num_input_tokens: int = 0 # Number of tokens including padding. # Flex Metadata num_blocks = 0 block_mask: BlockMask | None = None score_mod: _score_mod_signature | None = None logical_mask_mod: _mask_mod_signature = causal_mask_mod doc_ids: torch.Tensor | None = None direct_build: bool = True q_block_size: int = 16 kv_block_size: int = 16 transformed_score_mod: _score_mod_signature | None = None sliding_window: int | None = None mm_prefix_range: dict[int, list[tuple[int, int]]] | None = None @cached_property def logical_block_ids(self): return torch.arange( cdiv(self.max_seq_len, self.block_size), device=self.block_table.device, dtype=torch.long, ) def _convert_physical_to_logical( self, request_lookup: torch.Tensor, q_idx: torch.Tensor, physical_kv_idx: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Convert physical indices to logical indices for both query and kv. NB is_within_lower_bound: do sequences start on block_boundaries? Returns: tuple of (is_valid, logical_q_idx, logical_kv_idx) """ # Map query indices to corresponding request indices q_req = request_lookup[q_idx] # Convert physical KV indices to logical indices physical_kv_block = physical_kv_idx // self.block_size physical_kv_offset = physical_kv_idx % self.block_size logical_block_idx = self.physical_to_logical[q_req, physical_kv_block] logical_kv_idx = logical_block_idx * self.block_size + physical_kv_offset # Determine valid kv indices live_block = logical_block_idx >= 0 within_upper_bound = logical_kv_idx < self.seq_lens[q_req] within_lower_bound = logical_kv_idx >= 0 is_valid = live_block & within_upper_bound & within_lower_bound # Convert physical query indices to logical indices local_q_idx = q_idx - self.query_start_loc[q_req] logical_q_idx = local_q_idx + self.decode_offset[q_req] return is_valid, logical_q_idx, logical_kv_idx def get_causal_mask_mod(self) -> _mask_mod_signature: """Creates the mask_mod function for FlexAttention. This function creates the combined mask mod function that handles: 1. The paged attention block mapping 2. The mapping from packed query sequences to logical query entries It also by defaults adds the decoding offset to the query indices. With this info we create the "logical" indices that are passed to mask_mod functions. This allows mask mod functions to be agnostic to layout of the query and key/value tensors. """ assert self.doc_ids is not None def final_mask_mod( b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, physical_kv_idx: torch.Tensor, ) -> torch.Tensor: (is_valid, logical_q_idx, logical_kv_idx) = ( self._convert_physical_to_logical(self.doc_ids, q_idx, physical_kv_idx) ) # Apply mask modification only for valid indices return torch.where( is_valid, self.logical_mask_mod(b, h, logical_q_idx, logical_kv_idx), False, ) return final_mask_mod def get_bidirectional_mask_mod(self) -> _mask_mod_signature: """Creates the encoder mask_mod function for FlexAttention. Since the encoder bidirectional attention doesn't run with KV cache, this function creates a mask based on the packed query sequences. """ # Create a lookup mapping from query indices -> request number request_lookup = _offsets_to_doc_ids_tensor(self.query_start_loc) def final_mask_mod( b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, kv_idx: torch.Tensor, ) -> torch.Tensor: return request_lookup[q_idx] == request_lookup[kv_idx] return final_mask_mod def get_sliding_window_mask_mod(self) -> _mask_mod_signature: """Creates the sliding window mask_mod function for FlexAttention. Note that the sliding window mask here is bidirectional, we need to mask it with the bidirectional/causal mask for encoder/decoder. """ if self.sliding_window is None: raise ValueError("sliding_window must be set for sliding window attention") def sliding_window_mask_mod( b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, kv_idx: torch.Tensor ): return torch.abs(q_idx - kv_idx) < self.sliding_window def final_mask_mod( b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, physical_kv_idx: torch.Tensor, ) -> torch.Tensor: (is_valid, logical_q_idx, logical_kv_idx) = ( self._convert_physical_to_logical(self.doc_ids, q_idx, physical_kv_idx) ) return torch.where( is_valid, sliding_window_mask_mod(b, h, logical_q_idx, logical_kv_idx), False, ) return final_mask_mod if self.causal else sliding_window_mask_mod def get_prefix_lm_mask_mod(self) -> _mask_mod_signature: """Creates the prefix LM mask_mod function for FlexAttention.""" assert self.doc_ids is not None request_lookup = self.doc_ids def prefix_lm_mask_mod( b: torch.Tensor, h: torch.Tensor, cu_q_idx: torch.Tensor, q_idx: torch.Tensor, kv_idx: torch.Tensor, ): mask = torch.zeros_like(q_idx, dtype=torch.bool) for req, doc_range_lst in (self.mm_prefix_range or {}).items(): req_mask = request_lookup[cu_q_idx] == req for start, end in doc_range_lst: doc_mask_q = (q_idx >= start) & (q_idx <= end) doc_mask_kv = (kv_idx >= start) & (kv_idx <= end) mask = mask | (req_mask & doc_mask_q & doc_mask_kv) return mask def final_mask_mod( b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, physical_kv_idx: torch.Tensor, ) -> torch.Tensor: (is_valid, logical_q_idx, logical_kv_idx) = ( self._convert_physical_to_logical(self.doc_ids, q_idx, physical_kv_idx) ) return torch.where( is_valid, prefix_lm_mask_mod(b, h, q_idx, logical_q_idx, logical_kv_idx), False, ) return final_mask_mod def get_mask_mod(self): # Stage-1: initialize the base mask_mod # (causal mask for decoder or bidirectional mask for encoder) if self.causal: mask_mod = self.get_causal_mask_mod() else: mask_mod = self.get_bidirectional_mask_mod() # stage-2: add external mask_mod for special attention during # forwarding runtime to create the combined mask_mod. if self.sliding_window is not None: # Add sliding window mask for sliding window attention sliding_window_mask_mod = self.get_sliding_window_mask_mod() mask_mod = and_masks(mask_mod, sliding_window_mask_mod) if self.mm_prefix_range: # Add prefix LM mask for vision-language prefix LM attention prefix_lm_mask_mod = self.get_prefix_lm_mask_mod() mask_mod = or_masks(mask_mod, prefix_lm_mask_mod) return mask_mod def get_transformed_score_mod(self) -> _score_mod_signature | None: """Creates the transformed score_mod function for FlexAttention. This function wraps the user's score_mod to handle physical-to-logical index conversion, similar to how get_mask_mod works for mask functions. """ if self.score_mod is None: return None # Create a lookup mapping from query indices -> request number request_lookup = _offsets_to_doc_ids_tensor(self.query_start_loc) user_score_mod = self.score_mod def transformed_score_mod( score: torch.Tensor, b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, physical_kv_idx: torch.Tensor, ) -> torch.Tensor: (is_valid, logical_q_idx, logical_kv_idx) = ( self._convert_physical_to_logical( request_lookup, q_idx, physical_kv_idx ) ) return torch.where( is_valid, user_score_mod( score, b, h, logical_q_idx, logical_kv_idx, physical_q=q_idx ), -float("inf"), ) return transformed_score_mod def _build_block_mask_direct(self) -> BlockMask: """Direct block mask construction for standard causal attention. This method constructs the block mask directly using BlockMask.from_kv_blocks which is much more efficient than the generic create_block_mask approach. The direct path works as follows: 1. For each query token, fetch blocks from block_table using max_seq_len and exclude out of sliding window blocks if needed. (this fetches more blocks than needed for shorter sequences) 2. Group query tokens into chunks of q_block_size 3. For each group, deduplicate the blocks using unique_static_unsorted 4. Create BlockMask using the deduplicated block indices Over-estimation occurs when a group of q_block_size tokens contains multiple sequence IDs (doc_ids). In this case, we fetch ALL blocks for each sequence represented in the group, even though individual query tokens may only need a subset of those blocks based on causal masking and their position. """ page_to_block_ratio = self.kv_block_size // self.block_size if page_to_block_ratio != 1: raise ValueError( f"FlexAttention currently requires the cache block size " f"({self.block_size}) to be equal to the kv_block_size " f"({self.kv_block_size}). Please check your model's " f"configuration." ) used_pages = self.block_table[ self.doc_ids, : cdiv(self.max_seq_len, self.block_size) ] if self.sliding_window and self.causal: device = used_pages.device assert self.doc_ids is not None token_indices = torch.arange( self.doc_ids.shape[0], device=device, dtype=torch.long ) logical_q_idx = ( token_indices - self.query_start_loc[self.doc_ids] + self.decode_offset[self.doc_ids] ) min_kv_idx = torch.clamp(logical_q_idx - (self.sliding_window - 1), min=0) min_block_idx = min_kv_idx // self.block_size sliding_mask = self.logical_block_ids >= min_block_idx[:, None] used_pages.masked_fill_(~sliding_mask, 0) used_pages_padded = pad_to_multiple( used_pages, multiple=self.q_block_size, dim=0 ) used_pages_padded = used_pages_padded.reshape( used_pages_padded.shape[0] // self.q_block_size, -1 ) used_pages_padded = used_pages_padded // page_to_block_ratio kv_indices = unique_static_unsorted( (used_pages_padded.long()), M=self.num_blocks ).to(torch.int32) kv_num_blocks = (kv_indices >= 0).sum(dim=-1).to(torch.int32) block_mask_kwargs = { "seq_lengths": (self.num_actual_tokens, self.total_cache_tokens), "kv_num_blocks": kv_num_blocks[None, None], "kv_indices": kv_indices[None, None], "full_kv_num_blocks": None, "full_kv_indices": None, "BLOCK_SIZE": (self.q_block_size, self.kv_block_size), "mask_mod": self.mask_mod, } # compute_q_blocks parameter is available in PyTorch 2.9+ if is_torch_equal_or_newer("2.9.0.dev0"): block_mask_kwargs["compute_q_blocks"] = False return BlockMask.from_kv_blocks(**block_mask_kwargs) def build_block_mask(self) -> BlockMask: mask_mod = self.get_mask_mod() kv_len = self.total_cache_tokens if self.causal else self.num_actual_tokens return create_block_mask_compiled( mask_mod, None, None, self.num_actual_tokens, kv_len, device=self.block_table.device, BLOCK_SIZE=(self.q_block_size, self.kv_block_size), ) def __post_init__(self): assert self.use_cascade is False, "Not implemented yet." assert self.common_prefix_len == 0, "Not implemented yet." assert self.cu_prefix_query_lens is None, "Not implemented yet." assert self.prefix_kv_lens is None, "Not implemented yet." assert self.suffix_kv_lens is None, "Not implemented yet." # Create a lookup mapping from query indices -> request number self.doc_ids = _offsets_to_doc_ids_tensor(self.query_start_loc) self.num_blocks = self.total_cache_tokens // self.block_size self.mask_mod = self.get_mask_mod() self.transformed_score_mod = self.get_transformed_score_mod() if self.direct_build and self.causal: self.block_mask = self._build_block_mask_direct() else: self.block_mask = self.build_block_mask() class FlexAttentionMetadataBuilder(AttentionMetadataBuilder[FlexAttentionMetadata]): def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.model_config = vllm_config.model_config self.parallel_config = vllm_config.parallel_config self.cache_config = vllm_config.cache_config self.num_heads_q = self.model_config.get_num_attention_heads( self.parallel_config ) self.num_heads_kv = self.model_config.get_num_kv_heads(self.parallel_config) self.headdim = self.model_config.get_head_size() self.block_size = kv_cache_spec.block_size self.kv_cache_spec = kv_cache_spec supports_small_blocks = is_torch_equal_or_newer("2.9.0.dev0") self.direct_build: bool = supports_small_blocks self.q_block_size: int = 16 if supports_small_blocks else 128 self.kv_block_size: int = self.block_size if supports_small_blocks else 128 def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> FlexAttentionMetadata: num_reqs = common_attn_metadata.num_reqs num_actual_tokens = common_attn_metadata.num_actual_tokens max_query_len = common_attn_metadata.max_query_len max_seq_len = common_attn_metadata.max_seq_len query_start_loc = common_attn_metadata.query_start_loc seq_lens = common_attn_metadata.seq_lens block_table_tensor = common_attn_metadata.block_table_tensor slot_mapping = common_attn_metadata.slot_mapping num_blocks_per_seq = cdiv(seq_lens, self.block_size) use_cascade = common_prefix_len > 0 cu_prefix_query_lens = None prefix_kv_lens = None suffix_kv_lens = None if use_cascade: raise NotImplementedError("Not yet my friend") block_size = self.kv_cache_spec.block_size max_possible_seq_len = self.model_config.max_model_len num_gpu_blocks = self.cache_config.num_gpu_blocks assert num_gpu_blocks is not None, ( "FlexAttention requires num_gpu_blocks to be set" ) total_cache_tokens = num_gpu_blocks * block_size inverse_block_table = physical_to_logical_mapping( block_table_tensor, seq_lens, block_size, num_gpu_blocks ) offset_tensor = common_attn_metadata.num_computed_tokens_cpu.to( self.device, non_blocking=True ) out = FlexAttentionMetadata( causal=common_attn_metadata.causal, num_actual_tokens=num_actual_tokens, max_query_len=max_query_len, query_start_loc=query_start_loc, max_seq_len=max_seq_len, seq_lens=seq_lens, block_table=block_table_tensor, slot_mapping=slot_mapping, use_cascade=use_cascade, common_prefix_len=common_prefix_len, cu_prefix_query_lens=cu_prefix_query_lens, prefix_kv_lens=prefix_kv_lens, suffix_kv_lens=suffix_kv_lens, block_size=block_size, max_possible_sequence_length=max_possible_seq_len, num_reqs=num_reqs, physical_to_logical=inverse_block_table, total_cache_tokens=total_cache_tokens, decode_offset=offset_tensor, num_blocks_per_seq=num_blocks_per_seq, # FIXME(Isotr0py): direct build has issue to build bidirectional # attention block mask for encoder-only models, disable it temporarily. # see: https://github.com/vllm-project/vllm/pull/27329#issuecomment-3431484053 direct_build=(self.direct_build and common_attn_metadata.causal), q_block_size=self.q_block_size, kv_block_size=self.kv_block_size, ) return out def use_cascade_attention(self, *args, **kwargs) -> bool: return False class FlexAttentionImpl(AttentionImpl): sliding_window: int | None alibi_slopes: torch.Tensor | None logits_soft_cap: float | None mm_prefix_range: dict[int, list[tuple[int, int]]] | None = None 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: str | None = None, **kwargs, ) -> None: self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_kv_heads self.attn_type = attn_type if attn_type not in (AttentionType.ENCODER_ONLY, AttentionType.DECODER): raise NotImplementedError( f"FlexAttention does not support {attn_type} attention" ) if alibi_slopes is not None: raise NotImplementedError( "FlexAttention does not support alibi slopes yet." ) else: self.alibi_slopes = None self.sliding_window = sliding_window self.kv_cache_dtype = kv_cache_dtype self.logits_soft_cap = logits_soft_cap if self.logits_soft_cap is not None: raise NotImplementedError( "FlexAttention does not support logits soft cap yet." ) assert self.num_heads % self.num_kv_heads == 0 self.num_queries_per_kv = self.num_heads // self.num_kv_heads if kv_sharing_target_layer_name is not None: raise NotImplementedError("FlexAttention does not support kv sharing yet.") if is_quantized_kv_cache(self.kv_cache_dtype): raise NotImplementedError( "FlexAttention does not support quantized kv-cache. Yet" ) @staticmethod def view_as_4d(tensor: torch.Tensor) -> torch.Tensor: """View a 3d tensor as 4D.""" if tensor.ndim == 4: return tensor assert tensor.ndim == 3 return tensor[None, :, :, :] def forward( self, layer: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, attn_metadata: FlexAttentionMetadata, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Forward pass with FLexAttention.
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/utils.py
vllm/v1/attention/backends/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import abc import enum import functools from abc import abstractmethod from collections.abc import Callable from dataclasses import dataclass, field, fields, make_dataclass from typing import ( TYPE_CHECKING, Any, ClassVar, Generic, Literal, Protocol, TypeVar, get_args, ) import numpy as np import torch from typing_extensions import deprecated, runtime_checkable from vllm.config import VllmConfig, get_layers_from_vllm_config from vllm.utils.math_utils import cdiv if TYPE_CHECKING: from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.worker.gpu_input_batch import InputBatch import vllm.envs as envs from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionMetadata, ) from vllm.distributed.kv_transfer.kv_connector.utils import ( get_kv_connector_cache_layout, ) from vllm.logger import init_logger from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase from vllm.v1.kv_cache_interface import AttentionSpec from vllm.v1.worker.ubatch_utils import UBatchSlice logger = init_logger(__name__) KVCacheLayoutType = Literal["NHD", "HND"] _KV_CACHE_LAYOUT_OVERRIDE: KVCacheLayoutType | None = None PAD_SLOT_ID = -1 def is_valid_kv_cache_layout(value: str) -> bool: return value in get_args(KVCacheLayoutType) @dataclass class CommonAttentionMetadata: """ Per-batch attention metadata, shared across layers and backends. AttentionMetadataBuilder instances use it to construct per-layer metadata. For many of the tensors we keep both GPU and CPU versions. """ query_start_loc: torch.Tensor query_start_loc_cpu: torch.Tensor """(batch_size + 1,), the start location of each request in query Tensor""" seq_lens: torch.Tensor """(batch_size,), the number of computed tokens for each request""" num_reqs: int """Number of requests""" # TODO(lucas): rename to num_tokens since it may be padded and this is misleading num_actual_tokens: int """Total number of tokens in batch""" max_query_len: int """Longest query in batch""" max_seq_len: int """Longest context length (may be an upper bound)""" block_table_tensor: torch.Tensor slot_mapping: torch.Tensor causal: bool = True # Needed by FastPrefillAttentionBuilder logits_indices_padded: torch.Tensor | None = None num_logits_indices: int | None = None # Needed by CrossAttentionBuilder encoder_seq_lens: torch.Tensor | None = None encoder_seq_lens_cpu: np.ndarray | None = None dcp_local_seq_lens: torch.Tensor | None = None dcp_local_seq_lens_cpu: torch.Tensor | None = None """Sequence lengths of the local rank in decode context parallelism world""" # WARNING: Deprecated fields. Will be removed in a future release (v0.14.0) _seq_lens_cpu: torch.Tensor | None = None _num_computed_tokens_cpu: torch.Tensor | None = None @property @deprecated( """ Prefer using device seq_lens directly to avoid implicit H<>D sync. If a CPU copy is needed, use `seq_lens.cpu()` instead. Will be removed in a future release (v0.14.0) """ ) def seq_lens_cpu(self) -> torch.Tensor: if self._seq_lens_cpu is None: self._seq_lens_cpu = self.seq_lens.to("cpu") return self._seq_lens_cpu @property @deprecated( """ Prefer using device seq_lens directly to avoid implicit H<>D sync which breaks full async scheduling. If a CPU copy is needed, it can be derived from query_start_loc_cpu and seq_lens. Will be removed in a future release (v0.14.0) """ ) def num_computed_tokens_cpu(self) -> torch.Tensor: if self._num_computed_tokens_cpu is None: query_seq_lens = ( self.query_start_loc_cpu[1:] - self.query_start_loc_cpu[:-1] ) self._num_computed_tokens_cpu = self.seq_lens_cpu - query_seq_lens return self._num_computed_tokens_cpu # TODO(lucas): remove once we have FULL-CG spec-decode support def unpadded( self, num_actual_tokens: int, num_actual_reqs: int ) -> "CommonAttentionMetadata": maybe_slice_reqs = lambda x: x[:num_actual_reqs] if x is not None else None return CommonAttentionMetadata( query_start_loc=self.query_start_loc[: num_actual_reqs + 1], query_start_loc_cpu=self.query_start_loc_cpu[: num_actual_reqs + 1], seq_lens=self.seq_lens[:num_actual_reqs], _seq_lens_cpu=self._seq_lens_cpu[:num_actual_reqs] if self._seq_lens_cpu is not None else None, _num_computed_tokens_cpu=self._num_computed_tokens_cpu[:num_actual_reqs] if self._num_computed_tokens_cpu is not None else None, num_reqs=num_actual_reqs, num_actual_tokens=num_actual_tokens, max_query_len=self.max_query_len, max_seq_len=self.max_seq_len, block_table_tensor=self.block_table_tensor[:num_actual_reqs], slot_mapping=self.slot_mapping[:num_actual_tokens], causal=self.causal, logits_indices_padded=self.logits_indices_padded, num_logits_indices=self.num_logits_indices, encoder_seq_lens=maybe_slice_reqs(self.encoder_seq_lens), encoder_seq_lens_cpu=maybe_slice_reqs(self.encoder_seq_lens_cpu), dcp_local_seq_lens=maybe_slice_reqs(self.dcp_local_seq_lens), dcp_local_seq_lens_cpu=maybe_slice_reqs(self.dcp_local_seq_lens_cpu), ) def slice_query_start_locs( query_start_loc: torch.Tensor, request_slice: slice, ) -> torch.Tensor: """ Creates a new query_start_loc that corresponds to the requests in request_slice. Note: This function creates a new tensor to hold the new query_start_locs. This will break cudagraph compatibility. """ return ( query_start_loc[request_slice.start : request_slice.stop + 1] - query_start_loc[request_slice.start] ) def _make_metadata_with_slice( ubatch_slice: UBatchSlice, attn_metadata: CommonAttentionMetadata ) -> CommonAttentionMetadata: """ This function creates a new CommonAttentionMetadata that corresponds to the requests included in ubatch_slice """ assert not ubatch_slice.is_empty(), f"Ubatch slice {ubatch_slice} is empty" request_slice = ubatch_slice.request_slice token_slice = ubatch_slice.token_slice start_locs = attn_metadata.query_start_loc_cpu first_req = request_slice.start first_tok = token_slice.start last_req = request_slice.stop - 1 last_tok = token_slice.stop - 1 assert start_locs[first_req] <= first_tok < start_locs[first_req + 1], ( "Token slice start outside of first request" ) # NOTE: last token can be outside of the last request if we have CG padding. # If the request is split across ubatches, we have to adjust the metadata. # splits_first_request: The first request in this slice is the continuation of # a request that started in a previous slice. # splits_last_request: The last request in this slice continues into the # next slice. splits_first_request = first_tok > start_locs[first_req] splits_last_request = last_tok < start_locs[last_req + 1] - 1 query_start_loc_cpu = slice_query_start_locs(start_locs, request_slice) query_start_loc = slice_query_start_locs( attn_metadata.query_start_loc, request_slice ) assert len(query_start_loc) >= 2, ( f"query_start_loc must have at least 2 elements, got {len(query_start_loc)}" ) if splits_first_request: tokens_skipped = first_tok - start_locs[first_req] query_start_loc[1:] -= tokens_skipped query_start_loc_cpu[1:] -= tokens_skipped seq_lens = attn_metadata.seq_lens[request_slice] seq_lens_cpu = attn_metadata.seq_lens_cpu[request_slice] if splits_last_request: # NOTE: We use start_locs (the original query_start_loc_cpu) to calculate # the tokens skipped because query_start_loc_cpu might have been modified # if splits_first_request is True. tokens_skipped = start_locs[last_req + 1] - token_slice.stop query_start_loc[-1] -= tokens_skipped query_start_loc_cpu[-1] -= tokens_skipped # Make sure we don't modify the seq_lens tensors # (not cudagraph compatible) seq_lens = seq_lens.clone() seq_lens_cpu = seq_lens_cpu.clone() seq_lens[-1] -= tokens_skipped seq_lens_cpu[-1] -= tokens_skipped max_seq_len = int(seq_lens_cpu.max()) num_computed_tokens_cpu = attn_metadata.num_computed_tokens_cpu[request_slice] num_requests = request_slice.stop - request_slice.start num_actual_tokens = token_slice.stop - token_slice.start max_query_len = int( torch.max(torch.abs(query_start_loc_cpu[1:] - query_start_loc_cpu[:-1])).item() ) # This is to account for the case where we are in a dummy # run and query_start_loc_cpu is full of 0s if max_query_len == 0: max_query_len = attn_metadata.max_query_len block_table_tensor = attn_metadata.block_table_tensor[request_slice] slot_mapping = attn_metadata.slot_mapping[token_slice] return CommonAttentionMetadata( query_start_loc=query_start_loc, query_start_loc_cpu=query_start_loc_cpu, seq_lens=seq_lens, num_reqs=num_requests, num_actual_tokens=num_actual_tokens, max_query_len=max_query_len, max_seq_len=max_seq_len, block_table_tensor=block_table_tensor, slot_mapping=slot_mapping, _seq_lens_cpu=seq_lens_cpu, _num_computed_tokens_cpu=num_computed_tokens_cpu, ) def split_attn_metadata( ubatch_slices: list[UBatchSlice], common_attn_metadata: CommonAttentionMetadata, ) -> list[CommonAttentionMetadata]: """ Creates a new CommonAttentionMetadata instance that corresponds to the requests for each UBatchSlice in ubatch_slices. Note: This function does not modify common_attn_metadata """ results = [] for ubatch_slice in ubatch_slices: results.append(_make_metadata_with_slice(ubatch_slice, common_attn_metadata)) return results M = TypeVar("M") class AttentionCGSupport(enum.Enum): """Constants for the cudagraph support of the attention backend Here we do not consider the cascade attention, as currently it is never cudagraph supported.""" ALWAYS = 3 """Cudagraph always supported; supports mixed-prefill-decode""" UNIFORM_BATCH = 2 """Cudagraph supported for batches the only contain query lengths that are the same, this can be used for spec-decode i.e. "decodes" are 1 + num_speculative_tokens""" UNIFORM_SINGLE_TOKEN_DECODE = 1 """Cudagraph supported for batches the only contain query_len==1 decodes""" NEVER = 0 """NO cudagraph support""" class AttentionMetadataBuilder(abc.ABC, Generic[M]): # Does this backend/builder support CUDA Graphs for attention (default: no). # Do not access directly. Call get_cudagraph_support() instead. _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.NEVER # Does this backend/builder reorder the batch? # If not, set this to None. Otherwise set it to the query # length that will be pulled into the front of the batch. reorder_batch_threshold: int | None = None # Does this backend/builder support updating the block table in existing # metadata supports_update_block_table: bool = False @abstractmethod def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): self.kv_cache_spec = kv_cache_spec self.layer_names = layer_names self.vllm_config = vllm_config self.device = device @classmethod def get_cudagraph_support( cls: type["AttentionMetadataBuilder"], vllm_config: VllmConfig, kv_cache_spec: AttentionSpec, ) -> AttentionCGSupport: """Get the cudagraph support level of this builder class.""" return cls._cudagraph_support def _init_reorder_batch_threshold( self, reorder_batch_threshold: int | None = 1, supports_spec_as_decode: bool = False, supports_dcp_with_varlen: bool = False, ) -> None: self.reorder_batch_threshold = reorder_batch_threshold if self.reorder_batch_threshold is not None and supports_spec_as_decode: # If the backend supports spec-as-decode kernels, then we can set # the reorder_batch_threshold based on the number of speculative # tokens from the config. speculative_config = self.vllm_config.speculative_config if ( speculative_config is not None and speculative_config.num_speculative_tokens is not None ): self.reorder_batch_threshold = max( self.reorder_batch_threshold, 1 + speculative_config.num_speculative_tokens, ) if ( self.vllm_config.parallel_config.decode_context_parallel_size > 1 and not supports_dcp_with_varlen ): self.reorder_batch_threshold = 1 @abstractmethod def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> M: """ Central method that builds attention metadata. Some builders (MLA) require reorder_batch to be called prior to build. Args: common_prefix_len: The length of the common prefix of the batch. common_attn_metadata: The common attention metadata. fast_build: The meta-data will prioritize speed of building over then speed at execution. Can be used for spec-decode where the result of a build call may only be used for few layers/iters. """ raise NotImplementedError def update_block_table( self, metadata: M, blk_table: torch.Tensor, slot_mapping: torch.Tensor, ) -> M: """ Update the block table for the attention metadata. Faster when theres multiple kv-cache groups that create virtually the same metadata but just with different block tables. Only needs to be implemented if supports_update_block_table is True. """ raise NotImplementedError def build_for_cudagraph_capture( self, common_attn_metadata: CommonAttentionMetadata ) -> M: """ Build attention metadata for CUDA graph capture. Uses build by default. Subclasses that override this method should call self.build or super().build_for_cudagraph_capture. """ return self.build( common_prefix_len=0, common_attn_metadata=common_attn_metadata ) def build_for_drafting( self, common_attn_metadata: CommonAttentionMetadata, draft_index: int, ) -> M: """ Build attention metadata for draft model. Uses build by default. Args: common_attn_metadata: The common attention metadata. draft_index: The index of the current draft operation. When speculating a chain of tokens, this index refers to the draft attempt for the i-th token. For tree-based attention, this index instead refers to the draft attempt for the i-th level in the tree of tokens. """ return self.build( common_prefix_len=0, common_attn_metadata=common_attn_metadata, fast_build=True, ) def use_cascade_attention( self, common_prefix_len: int, query_lens: np.ndarray, num_query_heads: int, num_kv_heads: int, use_alibi: bool, use_sliding_window: bool, use_local_attention: bool, num_sms: int, dcp_world_size: int, ) -> bool: return False @functools.lru_cache def get_kv_cache_layout(): # Format specified by the code. global _KV_CACHE_LAYOUT_OVERRIDE if _KV_CACHE_LAYOUT_OVERRIDE is not None: cache_layout = _KV_CACHE_LAYOUT_OVERRIDE logger.info_once( "`_KV_CACHE_LAYOUT_OVERRIDE` variable detected. " "Setting KV cache layout to %s.", cache_layout, ) return cache_layout # Format specified by the user. cache_layout = envs.VLLM_KV_CACHE_LAYOUT # When neither the user nor the override specified a layout, get default if cache_layout is None: cache_layout = get_kv_connector_cache_layout() else: assert is_valid_kv_cache_layout(cache_layout) logger.info_once( "`VLLM_KV_CACHE_LAYOUT` environment variable " "detected. Setting KV cache layout to %s.", cache_layout, ) return cache_layout def set_kv_cache_layout(cache_layout: KVCacheLayoutType): global _KV_CACHE_LAYOUT_OVERRIDE _KV_CACHE_LAYOUT_OVERRIDE = cache_layout @dataclass class PerLayerParameters: """ Currently, FlashInfer backend only support models in which all layers share the same values for the following hyperparameters. Should not be used for trtllm-gen backend since it supports different values for the following hyperparameters. """ window_left: int logits_soft_cap: float | None sm_scale: float has_sinks: bool = False # has same params for all layers has_same_window_lefts: bool | None = field(default=None, compare=False) has_same_all_params: bool | None = field(default=None, compare=False) def get_per_layer_parameters( vllm_config: VllmConfig, layer_names: list[str], cls_: type["AttentionImpl"] ) -> dict[str, PerLayerParameters]: """ Scan layers in `layer_names` and determine some hyperparameters to use during `plan`. """ layers = get_layers_from_vllm_config(vllm_config, AttentionLayerBase, layer_names) per_layer_params: dict[str, PerLayerParameters] = {} for key, layer in layers.items(): impl = layer.impl assert isinstance(impl, cls_) # Infer hyperparameters from the attention layer window_size = getattr(impl, "sliding_window", None) window_left = window_size[0] if window_size is not None else -1 logits_soft_cap = getattr(impl, "logits_soft_cap", None) sm_scale = impl.scale has_sinks = getattr(impl, "sinks", None) is not None per_layer_params[key] = PerLayerParameters( window_left, logits_soft_cap, sm_scale, has_sinks ) return per_layer_params def infer_global_hyperparameters( per_layer_params: dict[str, PerLayerParameters], ) -> PerLayerParameters: """ Currently, FlashInfer backend other than trtllm-gen only support models in which all layers share the same values for the following hyperparameters: - `window_left` - `logits_soft_cap` - `sm_scale` So this function asserts that all layers share the same values for these hyperparameters and returns the global values. """ assert len(per_layer_params) > 0, "No attention layers found in the model." param_sets = list(per_layer_params.values()) global_params = param_sets[0] global_params.has_same_window_lefts = all( params.window_left == global_params.window_left for params in param_sets ) global_params.has_same_all_params = all( params == global_params for params in param_sets ) return global_params # # Take in `query_start_loc_np` and `seq_lens_np` and break the sequences into # local attention blocks, where each block is passed to the attention kernel # as an independent local ("virtual") batch item. # # For example, if are performing a chunked prefill a batch of 3 sequences: # q_seqlens = [4, 10, 5] # kv_seqlens = [6, 17, 9] # Then normally for regular attention we would compute with an attention mask # for batch idx 0 (q_seqlens = 4, kv_seqlens = 6) like: # batch idx: 0 (q_seqlens = 4, kv_seqlens = 6) # k_toks > 0 1 2 3 4 5 # q_toks v _____________ # 0 | 1 1 1 # 1 | 1 1 1 1 # 2 | 1 1 1 1 1 # 3 | 1 1 1 1 1 1 # # for local attention (with attn_chunk_size = 4) we would compute with an # attention mask like: # batch idx: 0 (q_seqlens = 4, kv_seqlens = 6, attn_chunk_size = 4) # k_toks > 0 1 2 3 4 5 # q_toks v _____________ # 0 | 1 1 1 # 1 | 1 1 1 1 # 2 | 1 # 3 | 1 1 # # We can simulate this mask using standard flash-attention by breaking the # sequences into local ("virtual") batches, where each local batch item is a # local attention block, so in this case batch idx 0 would be broken up into: # # local-batch idx: 0 (q_seqlens = 2, kv_seqlens = 4) (batch 0) # k_toks > 0 1 2 3 # q_toks v _____________ # 0 | 1 1 1 # 1 | 1 1 1 1 # local-batch idx: 1 (q_seqlens = 2, kv_seqlens = 2) (batch 0) # k_toks > 4 5 # q_toks v _____________ # 2 | 1 # 3 | 1 1 # # e.g. if we have: # attn_chunk_size = 4 # query_start_loc_np = [0, 4, 14, 19] (q_seqlens = [4, 10, 5]) # Then this function would return: # __b0__ ______b1______ __b2__ < orig batch indices # q_seqlens_local = [ 2, 2, 1, 4, 4, 1, 4, 1] # cu_seqlens_q_local = [0, 4, 6, 10, 14, 18, 19, 23, 24] # seqlens_k_local = [ 4, 2, 4, 4, 4, 1, 4, 1] # block_table_local : shape[local_virtual_batches, pages_per_local_batch] def make_local_attention_virtual_batches( attn_chunk_size: int, common_attn_metadata: CommonAttentionMetadata, block_size: int = 0, ) -> tuple[CommonAttentionMetadata, Callable[[torch.Tensor], torch.Tensor]]: query_start_loc_np = common_attn_metadata.query_start_loc_cpu.numpy() seq_lens_np = common_attn_metadata.seq_lens_cpu.numpy() block_table = common_attn_metadata.block_table_tensor device = common_attn_metadata.query_start_loc.device q_seqlens = query_start_loc_np[1:] - query_start_loc_np[:-1] actual_batch_size = seq_lens_np.shape[0] # Handle if we are starting in the middle of a local attention block, # we assume q_seqlens > 0 (for all elements), for each batch idx we compute # the number of tokens that are not in the first local attention block and # then we can simply use a cdiv for the rest. # For example if we have: # attn_chunk_size = 4 # q_seqlens = [4, 10, 5] # k_seqlens = [6, 17, 9] # Then we would get: # new_tokens_in_first_block = [2, 1, 4] # local_blocks = [2, 4, 2] q_tokens_in_first_block = np.minimum( attn_chunk_size - ((seq_lens_np - q_seqlens) % attn_chunk_size), q_seqlens ).astype(np.int32) tokens_in_last_block = attn_chunk_size + (seq_lens_np % -attn_chunk_size) local_blocks = 1 + cdiv(q_seqlens - q_tokens_in_first_block, attn_chunk_size) # Once we know the number of local blocks we can compute the request spans # for each batch idx, we can figure out the number of "virtual" requests we # have to make, # For the above example we would get: # seqlens_q_local = [2, 2, 1, 4, 4, 1, 4, 1] # # First Get batched arange. (E.g., [2, 4, 2] -> [0, 1, 0, 1, 2, 3, 0, 1]) # (TODO: max a utility to share this code with _prepare_inputs) # arange step 1. [2, 4, 2] -> [2, 6, 8] cu_num_blocks = np.cumsum(local_blocks) virtual_batches = cu_num_blocks[-1] # arange step 2. [2, 6, 8] -> [0, 0, 2, 2, 2, 2, 6, 6] block_offsets = np.repeat(cu_num_blocks - local_blocks, local_blocks) # arange step 3. [0, 1, 0, 1, 2, 3, 0, 1] arange = np.arange(virtual_batches, dtype=np.int32) - block_offsets # also compute reverse arange (i.e. [1, 0, 3, 2, 1, 0, 1, 0]) rarange = np.repeat(local_blocks, local_blocks) - arange - 1 # Then we can compute the seqlens_q_local, handling the fact that the # first and last blocks could be partial seqlens_q_local = np.repeat(q_seqlens - q_tokens_in_first_block, local_blocks) # set the first block since this may be a partial block seqlens_q_local[arange == 0] = q_tokens_in_first_block # set the remaining blocks seqlens_q_local[arange > 0] = np.minimum( seqlens_q_local - attn_chunk_size * (arange - 1), attn_chunk_size )[arange > 0] # convert from q_seqlens to cu_seqlens_q cu_seqlens_q_local = np.empty(virtual_batches + 1, dtype=np.int32) np.cumsum(seqlens_q_local, out=cu_seqlens_q_local[1:]) cu_seqlens_q_local[0] = 0 # compute the seqlens_k_local, # basically a full local attention block for all but the last block in each # batch # For our example this will be: # seqlens_k_local = [4, 2, 4, 4, 4, 1, 4, 1] seqlens_k_local = np.full(cu_num_blocks[-1], attn_chunk_size, dtype=np.int32) seqlens_k_local[cu_num_blocks - 1] = tokens_in_last_block num_computed_tokens_local = seqlens_k_local - seqlens_q_local k_seqstarts_absolute = np.repeat(seq_lens_np, local_blocks) - ( rarange * attn_chunk_size + np.repeat(tokens_in_last_block, local_blocks) ) # For the example the local attention blocks start at: # _b0_ _____b1_____ _b2_ # k_seqstarts_absolute = [0, 4, 4, 8, 12, 16, 4, 8] block_starts = k_seqstarts_absolute // block_size assert attn_chunk_size % block_size == 0, ( f"attn_chunk_size {attn_chunk_size} is not divisible by block_size {block_size}" ) pages_per_local_batch = attn_chunk_size // block_size # Create a block_table for the local attention blocks # For out example if we have a block-table like (assuming block_size=2): # block_table = [ # [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], < batch 0 # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], < batch 1 # [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], < batch 2 # ] # Then for the local batches we would want a block-table like # block_table_local = [ # [ 0, 1 ], < local-batch 0, (batch 0, starting from k[0]) # [ 2, 3 ], < local-batch 1, (batch 0, starting from k[4]) # [ 12, 13 ], < local-batch 2, (batch 1, starting from k[4]) # [ 14, 15 ], < local-batch 3, (batch 1, starting from k[8]) # [ 16, 17 ], < local-batch 4, (batch 1, starting from k[12]) # [ 18, 19 ], < local-batch 5, (batch 1, starting from k[16]) # [ 22, 23 ], < local-batch 6, (batch 2, starting from k[4]) # [ 24, 25 ], < local-batch 7, (batch 2, starting from k[8]) # ] block_indices = block_starts[:, None] + np.arange( pages_per_local_batch, dtype=np.int32 ) block_indices = block_indices.reshape(-1).clip(max=block_table.shape[1] - 1) batch_indices = np.repeat( np.arange(actual_batch_size, dtype=np.int32), local_blocks * pages_per_local_batch, ) # NOTE: https://github.com/pytorch/pytorch/pull/160256 causes performance # regression when using numpy arrays (batch and block indices) to index into # torch tensor (block_table). As a workaround, convert numpy arrays to torch # tensor first, which recovers perf. batch_indices_torch = torch.from_numpy(batch_indices) block_indices_torch = torch.from_numpy(block_indices) # Save as a lambda so we can return this for update_block_table make_block_table = lambda block_table: block_table[ batch_indices_torch, block_indices_torch ].view(virtual_batches, -1) block_table_local = make_block_table(block_table) query_start_loc_cpu = torch.from_numpy(cu_seqlens_q_local) seq_lens_cpu = torch.from_numpy(seqlens_k_local) max_seq_len = int(seq_lens_cpu.max()) return CommonAttentionMetadata( query_start_loc_cpu=query_start_loc_cpu, query_start_loc=query_start_loc_cpu.to(device=device, non_blocking=True), seq_lens=seq_lens_cpu.to(device=device, non_blocking=True), num_reqs=len(seq_lens_cpu), num_actual_tokens=common_attn_metadata.num_actual_tokens, max_query_len=seqlens_q_local.max(), max_seq_len=max_seq_len, block_table_tensor=block_table_local, slot_mapping=common_attn_metadata.slot_mapping, causal=True, _seq_lens_cpu=seq_lens_cpu, _num_computed_tokens_cpu=torch.from_numpy(num_computed_tokens_local), ), make_block_table def make_kv_sharing_fast_prefill_common_attn_metadata( common_attn_metadata: CommonAttentionMetadata, ) -> CommonAttentionMetadata: if common_attn_metadata.max_query_len == 1: # All requests are decode (assume 1 token for now) # Skip computing fast prefill path return common_attn_metadata assert common_attn_metadata.logits_indices_padded is not None assert common_attn_metadata.num_logits_indices is not None logits_indices_padded = common_attn_metadata.logits_indices_padded num_logits_indices = common_attn_metadata.num_logits_indices # Get rid of CUDAGraph padding, if any logits_indices = logits_indices_padded[:num_logits_indices] num_reqs = common_attn_metadata.num_reqs query_start_loc = common_attn_metadata.query_start_loc # Example inputs # num_reqs: 3 # generation_indices: [14, 18, 19, 27] # query_start_loc: [0, 15, 20, 28] # seq_lens: [41, 31, 40] # Find how many decode indices belong to each request # request_ids: [0, 1, 1, 2] request_ids = torch.bucketize(logits_indices, query_start_loc[1:], right=True) # Figure out how many tokens are in each request # num_decode_tokens: [1, 2, 1] num_decode_tokens = torch.bincount(request_ids, minlength=num_reqs) # Calculate new query_start_loc with tokens in generation_indices # decode_query_start_loc: [0, 1, 3, 4] decode_query_start_loc = torch.empty( num_reqs + 1, device=query_start_loc.device, dtype=query_start_loc.dtype ) decode_query_start_loc[0] = 0 decode_query_start_loc[1:] = torch.cumsum(num_decode_tokens, dim=0) decode_max_query_len = int(num_decode_tokens.max().item()) total_num_decode_tokens = int(num_decode_tokens.sum().item()) common_attn_metadata = CommonAttentionMetadata( query_start_loc=decode_query_start_loc, query_start_loc_cpu=decode_query_start_loc.to("cpu", non_blocking=True), seq_lens=common_attn_metadata.seq_lens, num_reqs=num_reqs, num_actual_tokens=total_num_decode_tokens, max_query_len=decode_max_query_len, max_seq_len=common_attn_metadata.max_seq_len, block_table_tensor=common_attn_metadata.block_table_tensor, slot_mapping=common_attn_metadata.slot_mapping, causal=True, _seq_lens_cpu=common_attn_metadata._seq_lens_cpu, _num_computed_tokens_cpu=common_attn_metadata._num_computed_tokens_cpu, ) return common_attn_metadata def subclass_attention_backend( name_prefix: str, attention_backend_cls: type[AttentionBackend], builder_cls: type[AttentionMetadataBuilder[M]], ) -> type[AttentionBackend]: """ Return a new subclass where `get_builder_cls` returns `builder_cls`. """ name: str = name_prefix + attention_backend_cls.__name__ # type: ignore return type( name, (attention_backend_cls,), {"get_builder_cls": lambda: builder_cls} ) def subclass_attention_backend_with_overrides( name_prefix: str, attention_backend_cls: type[AttentionBackend], overrides: dict[str, Any], ) -> type[AttentionBackend]: name: str = name_prefix + attention_backend_cls.__name__ # type: ignore return type(name, (attention_backend_cls,), overrides) def split_decodes_prefills_and_extends( common_attn_metadata: CommonAttentionMetadata, decode_threshold: int = 1, ) -> tuple[int, int, int, int, int, int]: """ Assuming a reordered batch, finds the boundary between prefill and decode requests. Args: common_attn_metadata: CommonAttentionMetadata object containing the batch metadata.
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/linear_attn.py
vllm/v1/attention/backends/linear_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass import torch from vllm.attention.backends.abstract import AttentionBackend from vllm.config import VllmConfig from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, split_decodes_and_prefills, ) from vllm.v1.kv_cache_interface import AttentionSpec, MambaSpec class LinearAttentionBackend(AttentionBackend): @staticmethod def get_builder_cls() -> type["LinearAttentionMetadataBuilder"]: return LinearAttentionMetadataBuilder @dataclass class LinearAttentionMetadata: num_prefills: int num_prefill_tokens: int num_decodes: int num_decode_tokens: int query_start_loc: torch.Tensor seq_lens: torch.Tensor state_indices_tensor: torch.Tensor # shape: [batch,] class LinearAttentionMetadataBuilder(AttentionMetadataBuilder[LinearAttentionMetadata]): reorder_batch_threshold: int = 1 _cudagraph_support = AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) assert isinstance(kv_cache_spec, MambaSpec) def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> LinearAttentionMetadata: query_start_loc = common_attn_metadata.query_start_loc seq_lens = common_attn_metadata.seq_lens state_indices_tensor = common_attn_metadata.block_table_tensor[:, 0] num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=self.reorder_batch_threshold ) ) attn_metadata = LinearAttentionMetadata( num_prefills=num_prefills, num_prefill_tokens=num_prefill_tokens, num_decodes=num_decodes, num_decode_tokens=num_decode_tokens, query_start_loc=query_start_loc, seq_lens=seq_lens, state_indices_tensor=state_indices_tensor, ) return attn_metadata
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/flashinfer.py
vllm/v1/attention/backends/flashinfer.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with FlashInfer.""" from dataclasses import dataclass from typing import ClassVar import numpy as np import torch from flashinfer import ( BatchDecodeWithPagedKVCacheWrapper, BatchPrefillWithPagedKVCacheWrapper, BatchPrefillWithRaggedKVCacheWrapper, MultiLevelCascadeAttentionWrapper, ) from flashinfer.decode import _get_range_buf, trtllm_batch_decode_with_kv_cache from flashinfer.prefill import trtllm_batch_context_with_kv_cache from flashinfer.utils import FP4Tensor from typing_extensions import override from vllm import envs from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionType, MultipleOf, ) from vllm.attention.ops.common import cp_lse_ag_out_rs from vllm.attention.ops.merge_attn_states import merge_attn_states from vllm.config import CUDAGraphMode, VllmConfig, get_current_vllm_config from vllm.config.cache import CacheDType from vllm.distributed.parallel_state import get_dcp_group from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.model_executor.layers.quantization.utils.quant_utils import ( QuantKey, kFp8StaticTensorSym, kNvfp4Quant, ) from vllm.platforms import current_platform from vllm.platforms.interface import DeviceCapability from vllm.triton_utils import tl, triton from vllm.utils.flashinfer import ( can_use_trtllm_attention, use_trtllm_attention, ) from vllm.utils.math_utils import cdiv from vllm.utils.platform_utils import is_pin_memory_available from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, KVCacheLayoutType, get_dcp_local_seq_lens, get_kv_cache_layout, get_per_layer_parameters, infer_global_hyperparameters, split_decodes_and_prefills, ) from vllm.v1.kv_cache_interface import AttentionSpec from vllm.v1.utils import CpuGpuBuffer FLASHINFER_WORKSPACE_BUFFER_SIZE_BATCH_INVARIANT = 2048 * 1024 * 1024 FP8_DTYPE = current_platform.fp8_dtype() FP4_DTYPE = torch.uint8 logger = init_logger(__name__) trtllm_gen_workspace_buffer = None def _get_trtllm_gen_workspace_buffer(): global trtllm_gen_workspace_buffer if trtllm_gen_workspace_buffer is None: trtllm_gen_workspace_buffer = torch.zeros( envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE, dtype=torch.uint8, device="cuda" ) return trtllm_gen_workspace_buffer @triton.jit def _trtllm_prefill_attn_kvfp8_dequant( kv_cache_ptr, block_tables_prefill_ptr, block_table_stride, mock_kv_cache_ptr, k_scale_ptr, v_scale_ptr, K_CACHE_STRIDE: tl.constexpr, KV_CACHE_STRIDE: tl.constexpr, ): batch_idx = tl.program_id(0).to(tl.int64) mock_block_table_idx = tl.program_id(1).to(tl.int64) orig_page_num = tl.load( block_tables_prefill_ptr + batch_idx * block_table_stride + mock_block_table_idx ).to(tl.int64) if orig_page_num <= 0: return dequant_dtype = mock_kv_cache_ptr.dtype.element_ty # Dequantize K k_scale_val = tl.load(k_scale_ptr) offset = orig_page_num * KV_CACHE_STRIDE + tl.arange(0, K_CACHE_STRIDE) fp8_vals = tl.load(kv_cache_ptr + offset) dequantized_vals = fp8_vals.to(tl.float32) * k_scale_val mock_cache_offset = ( batch_idx * block_table_stride + mock_block_table_idx + 1 ) * KV_CACHE_STRIDE + tl.arange(0, K_CACHE_STRIDE) dequantized_vals = dequantized_vals.to(dequant_dtype) tl.store(mock_kv_cache_ptr + mock_cache_offset, dequantized_vals) # Dequantize V v_scale_val = tl.load(v_scale_ptr) offset = ( orig_page_num * KV_CACHE_STRIDE + K_CACHE_STRIDE + tl.arange(0, K_CACHE_STRIDE) ) fp8_vals = tl.load(kv_cache_ptr + offset) dequantized_vals = fp8_vals.to(tl.float32) * v_scale_val mock_cache_offset = ( (batch_idx * block_table_stride + mock_block_table_idx + 1) * KV_CACHE_STRIDE + K_CACHE_STRIDE + tl.arange(0, K_CACHE_STRIDE) ) dequantized_vals = dequantized_vals.to(dequant_dtype) tl.store(mock_kv_cache_ptr + mock_cache_offset, dequantized_vals) def trtllm_prefill_attn_kvfp8_dequant( kv_cache: torch.Tensor, block_tables_prefill: torch.Tensor, k_scale: torch.Tensor, v_scale: torch.Tensor, dequant_dtype: torch.dtype, ) -> tuple[torch.Tensor, torch.Tensor]: batch_size, num_of_page_per_token = block_tables_prefill.shape s = kv_cache.shape assert s[1] == 2 assert dequant_dtype in (torch.bfloat16, torch.float16) k_cache_stride = s[2] * s[3] * s[4] kv_cache_stride = k_cache_stride * s[1] new_s = (batch_size * num_of_page_per_token + 1, s[1], s[2], s[3], s[4]) # mock kv cache contains just the pages needed by this prefill mock_kv_cache = torch.empty(new_s, dtype=dequant_dtype, device=kv_cache.device) # we simply sequentially index the pages needed by this prefill mock_block_table = torch.arange( start=1, end=batch_size * num_of_page_per_token + 1, dtype=torch.int32, device=block_tables_prefill.device, ).reshape(batch_size, num_of_page_per_token) grid = (batch_size, num_of_page_per_token) _trtllm_prefill_attn_kvfp8_dequant[grid]( kv_cache, block_tables_prefill, num_of_page_per_token, mock_kv_cache, k_scale, v_scale, k_cache_stride, kv_cache_stride, ) return mock_kv_cache, mock_block_table class BatchDCPPrefillWrapper: def __init__( self, workspace_buffer: torch.Tensor | None = None, ): self._context = BatchPrefillWithPagedKVCacheWrapper( workspace_buffer, get_kv_cache_layout() ) self._new_tokens = BatchPrefillWithRaggedKVCacheWrapper( workspace_buffer, get_kv_cache_layout() ) def plan( self, qo_indptr_cpu: torch.Tensor, paged_kv_indptr_cpu: torch.Tensor, paged_kv_indices: torch.Tensor, paged_kv_last_page_len_cpu: torch.Tensor, page_size: int, num_qo_heads: int, dcp_world_size: int, num_kv_heads: int, head_dim: int, sm_scale: float, window_left: int, logits_soft_cap: float | None, q_data_type: torch.dtype, kv_cache_dtype: torch.dtype, prefill_fixed_split_size: int, disable_split_kv: bool, ): """Plan the prefill operation with given parameters.""" self._context.plan( qo_indptr_cpu, paged_kv_indptr_cpu, paged_kv_indices, paged_kv_last_page_len_cpu, num_qo_heads * dcp_world_size, num_kv_heads, head_dim, page_size, causal=False, # This is context run sm_scale=sm_scale, window_left=window_left, logits_soft_cap=logits_soft_cap, q_data_type=q_data_type, kv_data_type=kv_cache_dtype, fixed_split_size=prefill_fixed_split_size, disable_split_kv=disable_split_kv, ) self._new_tokens.plan( qo_indptr=qo_indptr_cpu, kv_indptr=qo_indptr_cpu, num_qo_heads=num_qo_heads, num_kv_heads=num_kv_heads, head_dim_qk=head_dim, head_dim_vo=head_dim, causal=True, # This is newtokens run sm_scale=sm_scale, window_left=window_left, logits_soft_cap=logits_soft_cap, q_data_type=q_data_type, ) def run( self, layer: torch.nn.Module, prefill_query: torch.Tensor, kv_cache_permute: torch.Tensor, key: torch.Tensor, value: torch.Tensor, out: torch.Tensor, ): prefill_query_across_dcp = get_dcp_group().all_gather( prefill_query.contiguous(), dim=1 ) output_context_tmp, lse_context_tmp = self._context.run( prefill_query_across_dcp, kv_cache_permute, k_scale=layer._k_scale_float, v_scale=layer._v_scale_float, return_lse=True, ) output_context, lse_context = cp_lse_ag_out_rs( output_context_tmp, lse_context_tmp, get_dcp_group(), return_lse=True, is_lse_base_on_e=False, ) lse_context = lse_context.transpose(0, 1).contiguous() output_query, lse_query = self._new_tokens.run( prefill_query, key, value, return_lse=True, ) lse_query = lse_query.transpose(0, 1).contiguous() merge_attn_states( out, output_context, lse_context, output_query, lse_query, ) return out class FlashInferBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ "auto", "fp8", "fp8_e4m3", "fp8_e5m2", ] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: # Note: Not sure for all platforms, but on Blackwell, # only support a page size of 16, 32, 64. return [16, 32, 64] @staticmethod def get_name() -> str: return "FLASHINFER" @staticmethod def get_impl_cls() -> type["FlashInferImpl"]: return FlashInferImpl @staticmethod def get_builder_cls() -> type["FlashInferMetadataBuilder"]: return FlashInferMetadataBuilder @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, ...]: return (num_blocks, 2, block_size, num_kv_heads, head_size) @staticmethod def get_kv_cache_stride_order( include_num_layers_dimension: bool = False, ) -> tuple[int, ...]: # `stride_order` indicates the permutation that gets us from # `get_kv_cache_shape` to the actual memory layout we want. cache_layout = get_kv_cache_layout() if cache_layout == "NHD" and include_num_layers_dimension: # (num_blocks, num_layers, 2, block_size, num_kv_heads, head_size) return (1, 0, 2, 3, 4, 5) elif cache_layout == "NHD": stride_order = (0, 1, 2, 3, 4) elif cache_layout == "HND" and include_num_layers_dimension: # (num_blocks, 2, num_kv_heads, num_layers, block_size, head_size) return (1, 2, 4, 0, 3, 5) elif cache_layout == "HND": stride_order = (0, 1, 3, 2, 4) else: raise ValueError(f"Unknown cache layout format {cache_layout}.") return stride_order @staticmethod def get_fp8_dtype_for_flashinfer(kv_cache_dtype: str) -> torch.dtype: if kv_cache_dtype in ("fp8", "fp8_e4m3"): return torch.float8_e4m3fn elif kv_cache_dtype == "fp8_e5m2": return torch.float8_e5m2 else: raise ValueError(f"Unrecognized FP8 dtype: {kv_cache_dtype}") @classmethod def get_supported_head_sizes(cls) -> list[int]: # https://github.com/flashinfer-ai/flashinfer/blob/3d55c71a62052c590c130897d3a3db49b14fcc34/include/flashinfer/utils.cuh#L157 return [64, 128, 256] @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return capability >= DeviceCapability(7, 5) and capability <= DeviceCapability( 12, 1 ) @classmethod def supports_sink(cls) -> bool: """FlashInfer supports sinks when TRTLLM attention is available (SM100).""" from vllm.utils.flashinfer import ( force_use_trtllm_attention, supports_trtllm_attention, ) # Respect explicit disable flag (e.g., # --attention-config.use_trtllm_attention=0) if force_use_trtllm_attention() is False: return False # Check if TRTLLM is supported on this platform return supports_trtllm_attention() @classmethod def get_required_kv_cache_layout(cls) -> KVCacheLayoutType | None: from vllm.platforms import current_platform capability = current_platform.get_device_capability() if capability is not None and capability.major == 10: return "HND" return None @dataclass class FIPrefill: """Metadata for the native FlashInfer prefill pathway (non-TRTLLM).""" wrapper: BatchPrefillWithPagedKVCacheWrapper | BatchDCPPrefillWrapper @dataclass class FIDecode: """Metadata for the native FlashInfer decode pathway (non-TRTLLM).""" wrapper: BatchDecodeWithPagedKVCacheWrapper @dataclass class TRTLLMPrefill: """Metadata for the TRTLLM prefill pathway.""" block_tables: torch.Tensor """ The slice of the block table tensor corresponding *only* to prefill requests. Shape: [num_prefills, max_num_blocks_per_seq] """ seq_lens: torch.Tensor """ The slice of the sequence lengths tensor corresponding *only* to prefill requests. Shape: [num_prefills] """ cum_seq_lens_q: torch.Tensor cum_seq_lens_kv: torch.Tensor max_q_len: int """ The maximum query length *among prefill requests*. """ max_seq_len: int """The maximum sequence length for KV Cache.""" @dataclass class TRTLLMDecode: """Metadata for the TRTLLM decode pathway.""" block_tables: torch.Tensor """ The slice of the block table tensor corresponding *only* to decode requests. Shape: [num_decodes, max_num_blocks_per_seq] """ seq_lens: torch.Tensor """ The slice of the sequence lengths tensor corresponding *only* to decode requests. Shape: [num_decodes] """ max_seq_len: int """The maximum sequence length for KV Cache.""" @dataclass class FlashInferMetadata: num_actual_tokens: int """Total number of tokens in the batch (excluding padding).""" slot_mapping: torch.Tensor """Tensor for writing K/V to the cache. Shape: [num_actual_tokens]""" q_data_type: torch.dtype num_decodes: int num_decode_tokens: int num_prefills: int num_prefill_tokens: int prefill: FIPrefill | TRTLLMPrefill | None """ Holds the metadata for the prefill portion of the batch. Will be `None` if `num_prefill_tokens == 0`. """ decode: FIDecode | TRTLLMDecode | None """ Holds the metadata for the decode portion of the batch. Will be `None` if `num_decode_tokens == 0`. """ # --- Special Case: Cascade Attention --- use_cascade: bool """ If True, the entire batch is a cascade attention call, and the `prefill` and `decode` fields will both be None. """ cascade_wrapper: MultiLevelCascadeAttentionWrapper | None class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]): reorder_batch_threshold: int = 1 def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.cache_config = vllm_config.cache_config self.model_config = vllm_config.model_config self.attention_config = vllm_config.attention_config self._workspace_buffer = None self._prefill_wrapper: ( BatchPrefillWithPagedKVCacheWrapper | BatchDCPPrefillWrapper | None ) = None # Wrapper for prefill/append self._decode_wrapper = None # Wrapper for decode (general shape) if vllm_is_batch_invariant(): self.decode_fixed_split_size = 2048 self.prefill_fixed_split_size = 4096 self.disable_split_kv = True else: self.decode_fixed_split_size = -1 self.prefill_fixed_split_size = -1 self.disable_split_kv = False self.compilation_config = vllm_config.compilation_config max_num_pages_per_req = cdiv( self.model_config.max_model_len, self.kv_cache_spec.block_size ) max_num_reqs = vllm_config.scheduler_config.max_num_seqs max_num_pages = max_num_reqs * max_num_pages_per_req speculative_config = vllm_config.speculative_config num_spec_tokens = ( speculative_config.num_speculative_tokens if speculative_config is not None else 0 ) self.enable_cuda_graph = ( self.compilation_config.cudagraph_mode.decode_mode() == CUDAGraphMode.FULL ) if self.enable_cuda_graph: # For full cudagraph capture, one `decode_wrapper` for each batch # size is needed for FlashInfer. self._decode_wrappers_cudagraph: dict[ int, BatchDecodeWithPagedKVCacheWrapper ] = {} self._decode_cudagraph_max_bs = min( (1 + num_spec_tokens) * max_num_reqs, self.compilation_config.max_cudagraph_capture_size, ) try: self.dcp_world_size = get_dcp_group().world_size self.dcp_rank = get_dcp_group().rank_in_group self.dcp_kv_cache_interleave_size = ( vllm_config.parallel_config.dcp_kv_cache_interleave_size ) except AssertionError: # DCP might not be initialized in testing self.dcp_world_size = 1 self.dcp_rank = 0 self.dcp_kv_cache_interleave_size = 1 self.use_dcp = self.dcp_world_size > 1 self.num_qo_heads = self.model_config.get_num_attention_heads( self.vllm_config.parallel_config ) self.num_kv_heads = self.kv_cache_spec.num_kv_heads self.head_dim = self.kv_cache_spec.head_size self.page_size = self.kv_cache_spec.block_size self.cache_dtype = self.cache_config.cache_dtype if self.cache_dtype.startswith("fp8"): self.kv_cache_dtype = FlashInferBackend.get_fp8_dtype_for_flashinfer( self.cache_dtype ) else: assert self.kv_cache_spec.dtype == self.model_config.dtype self.kv_cache_dtype = self.kv_cache_spec.dtype # Use model dtype as q dtype when TRTLLM attn is not supported, or # --attention-config.disable_flashinfer_q_quantization is set to 1. Otherwise, # try to use fp8 q if kv cache is fp8, and will fall back to model dtype # if TRTLLM attention kernel is not used when building attn metadata can_use_trtllm = can_use_trtllm_attention(self.num_qo_heads, self.num_kv_heads) if ( can_use_trtllm and not vllm_config.attention_config.disable_flashinfer_q_quantization ): self.q_data_type = self.kv_cache_dtype else: self.q_data_type = self.model_config.dtype # Prefer TRTLLM attention for decoding in all cases. # This allows us to use AttentionCGSupport.UNIFORM_BATCH mode. self.use_trtllm_decode_attention = can_use_trtllm self._init_reorder_batch_threshold(1, supports_spec_as_decode=can_use_trtllm) self._cascade_wrapper = None # Wrapper for cascade attention # Global hyperparameters shared by all attention layers # TODO: discard this for trtllm-gen backend self.global_hyperparameters = infer_global_hyperparameters( get_per_layer_parameters(vllm_config, layer_names, FlashInferImpl) ) self.sm_scale = self.global_hyperparameters.sm_scale self.window_left = self.global_hyperparameters.window_left self.logits_soft_cap = self.global_hyperparameters.logits_soft_cap self.has_sinks = self.global_hyperparameters.has_sinks if self.has_sinks and not can_use_trtllm: raise NotImplementedError( "FlashInfer backend currently does not support attention " "sinks, please use trtllm on blackwell or flash attention on " "earlier GPUs." ) # Preparing persistent buffers self.pin_memory = is_pin_memory_available() self.paged_kv_indptr = self._make_buffer(max_num_reqs + 1) self.paged_kv_indptr_cpu_buffer = torch.zeros_like( self.paged_kv_indptr.cpu, pin_memory=self.pin_memory ) # Extra buffer for mutable paged_kv_indptr.cpu in cuda graph mode self.paged_kv_indices = self._make_buffer(max_num_pages) self.paged_kv_last_page_len = self._make_buffer(max_num_reqs) if self.head_dim == 256 and current_platform.is_device_capability_family(100): # https://github.com/flashinfer-ai/flashinfer/issues/1993 reports that # head size 256 and block size 16 is not supported on blackwell. assert kv_cache_spec.block_size != 16, ( "There is a bug in FlashInfer " "block_size 16 head size 256 support. Please avoid this combination by " "passing --block-size 32 or --block-size 64." ) def _make_buffer( self, *size: int | torch.SymInt, dtype: torch.dtype = torch.int32 ) -> CpuGpuBuffer: return CpuGpuBuffer( *size, dtype=dtype, device=self.device, pin_memory=self.pin_memory, with_numpy=True, ) @override # type: ignore[misc] @classmethod def get_cudagraph_support( cls: type["FlashInferMetadataBuilder"], vllm_config: VllmConfig, kv_cache_spec: AttentionSpec, ) -> AttentionCGSupport: has_trtllm_support = can_use_trtllm_attention( num_qo_heads=vllm_config.model_config.get_num_attention_heads( vllm_config.parallel_config ), num_kv_heads=kv_cache_spec.num_kv_heads, ) if has_trtllm_support: return AttentionCGSupport.UNIFORM_BATCH else: return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE def _get_workspace_buffer(self): if self._workspace_buffer is None: buffer_size = envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE if vllm_is_batch_invariant(): buffer_size = FLASHINFER_WORKSPACE_BUFFER_SIZE_BATCH_INVARIANT self._workspace_buffer = torch.zeros( buffer_size, dtype=torch.uint8, device=self.device ) return self._workspace_buffer def set_workspace_buffer(self, workspace_buffer: torch.Tensor): self._workspace_buffer = workspace_buffer def _get_prefill_wrapper( self, ) -> BatchPrefillWithPagedKVCacheWrapper | BatchDCPPrefillWrapper: if self._prefill_wrapper is None: if self.use_dcp: self._prefill_wrapper = BatchDCPPrefillWrapper( workspace_buffer=self._get_workspace_buffer(), ) else: self._prefill_wrapper = BatchPrefillWithPagedKVCacheWrapper( self._get_workspace_buffer(), get_kv_cache_layout() ) assert self._prefill_wrapper is not None return self._prefill_wrapper def _get_decode_wrapper(self, batch_size: int, use_cudagraph: bool = False): if use_cudagraph: decode_wrapper = self._decode_wrappers_cudagraph.get(batch_size, None) else: decode_wrapper = self._decode_wrapper if decode_wrapper is None: if use_cudagraph: paged_kv_indptr = self.paged_kv_indptr.gpu[: batch_size + 1] paged_kv_indices = self.paged_kv_indices.gpu paged_kv_last_page_len = self.paged_kv_last_page_len.gpu[:batch_size] else: paged_kv_indptr = None paged_kv_indices = None paged_kv_last_page_len = None decode_wrapper = BatchDecodeWithPagedKVCacheWrapper( self._get_workspace_buffer(), get_kv_cache_layout(), use_cuda_graph=use_cudagraph, paged_kv_indptr_buffer=paged_kv_indptr, paged_kv_indices_buffer=paged_kv_indices, paged_kv_last_page_len_buffer=paged_kv_last_page_len, # Tensor cores are enabled by default because the perf would be # at least as good as cuda cores for all attention ops in latest # gpus. use_tensor_cores=True, ) # save the decode wrapper if use_cudagraph: self._decode_wrappers_cudagraph[batch_size] = decode_wrapper else: self._decode_wrapper = decode_wrapper return decode_wrapper def _get_cascade_wrapper(self): if self._cascade_wrapper is None: self._cascade_wrapper = MultiLevelCascadeAttentionWrapper( 2, self._get_workspace_buffer(), get_kv_cache_layout() ) return self._cascade_wrapper def _compute_flashinfer_kv_metadata( self, num_blocks_np: np.ndarray, seq_lens_np: np.ndarray, block_table_tensor: torch.Tensor, num_reqs: int, page_size: int, ) -> torch.Tensor: """ Compute paged_kv_indptr, paged_kv_indices, paged_kv_last_page_len for FlashInfer attention. Results are stored in self.paged_kv_indptr, self.paged_kv_indices, self.paged_kv_last_page_len buffers. Returns paged_kv_indices, a GPU tensor with shape [num_actual_pages]. """ # write self.paged_kv_indptr_cpu inplace (0-index is always 0) np.cumsum( num_blocks_np, dtype=np.int32, out=self.paged_kv_indptr.np[1 : num_reqs + 1], ) # NOTE(woosuk): Because self.paged_kv_indptr_cpu can be modified # after this line (e.g., for cuda graphs), we need to copy the data to # self.paged_kv_indptr_buffer to avoid race condition. self.paged_kv_indptr_cpu_buffer[: num_reqs + 1] = self.paged_kv_indptr.cpu[ : num_reqs + 1 ] paged_kv_indptr = self.paged_kv_indptr.gpu[: num_reqs + 1] paged_kv_indptr.copy_( self.paged_kv_indptr_cpu_buffer[: num_reqs + 1], non_blocking=True ) # write self.paged_kv_indices inplace num_actual_pages = self.paged_kv_indptr.np[num_reqs] paged_kv_indices = self.paged_kv_indices.gpu[:num_actual_pages] _copy_page_indices_kernel[(num_reqs,)]( paged_kv_indices, block_table_tensor, block_table_tensor.stride(0), paged_kv_indptr, BLOCK_SIZE=1024, ) # write self.paged_kv_last_page_len_cpu inplace paged_kv_last_page_len_np = seq_lens_np % page_size self.paged_kv_last_page_len.np[:num_reqs] = np.where( (paged_kv_last_page_len_np == 0) & (seq_lens_np != 0), page_size, paged_kv_last_page_len_np, ) return paged_kv_indices def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> FlashInferMetadata: num_reqs = common_attn_metadata.num_reqs num_actual_tokens = common_attn_metadata.num_actual_tokens num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=self.reorder_batch_threshold, require_uniform=True, ) ) page_size = self.page_size max_seq_len = common_attn_metadata.max_seq_len seq_lens = common_attn_metadata.seq_lens block_table_tensor = common_attn_metadata.block_table_tensor qo_indptr = common_attn_metadata.query_start_loc qo_indptr_cpu = common_attn_metadata.query_start_loc_cpu # Step 1: Decide which dispatch modes to use: # - Cascade attention (distinct mode) # - Prefill (FI native or TRTLLM) # - Decode (FI native or TRTLLM) use_cascade = common_prefix_len > 0 uses_spec_reorder = self.reorder_batch_threshold > 1 prefill_use_trtllm = use_trtllm_attention( self.num_qo_heads, self.num_kv_heads, num_prefill_tokens, max_seq_len, self.dcp_world_size, self.cache_dtype, self.q_data_type, is_prefill=True, force_use_trtllm=self.attention_config.use_trtllm_attention, has_sinks=self.has_sinks, has_spec=uses_spec_reorder, ) decode_use_trtllm = ( self.use_trtllm_decode_attention and self.dcp_world_size <= 1 ) all_uses_trtllm = (num_prefills == 0 or prefill_use_trtllm) and ( num_decodes == 0 or decode_use_trtllm ) is_only_trtllm_decode = num_prefills == 0 and ( num_decodes > 0 and decode_use_trtllm ) if not all_uses_trtllm: if self.has_sinks: raise NotImplementedError( "FlashInfer backend currently does not support attention " "sinks, please use trtllm on blackwell or flash attention " "on earlier GPUs." ) if not self.global_hyperparameters.has_same_window_lefts: raise ValueError( "Window left is not the same for all layers. " "One potential fix is to set disable_sliding_window=True" ) assert self.global_hyperparameters.has_same_all_params, ( "FlashInfer backend currently only supports models in which " "all layers share the same values for the following " "hyperparameters: `window_left`, `logits_soft_cap`, " "`sm_scale`." ) # The q quantization is not supported for non-trtllm attention, # fall back to model dtype. self.q_data_type = self.model_config.dtype # Step 2: Initialize the output metadata # Leave prefill/decode/cascade_wrapper empty, to be populated # case by case depending on the batch contents and backend selection. attn_metadata = FlashInferMetadata( num_actual_tokens=num_actual_tokens, slot_mapping=common_attn_metadata.slot_mapping, q_data_type=self.q_data_type, num_decodes=num_decodes, num_decode_tokens=num_decode_tokens, num_prefills=num_prefills, num_prefill_tokens=num_prefill_tokens, use_cascade=use_cascade, prefill=None, decode=None, cascade_wrapper=None, ) # Guard access to seq_lens_cpu, which may not always be needed # and can be expensive to retrieve in async mode. needs_seq_lens_cpu = self.use_dcp or use_cascade or not is_only_trtllm_decode seq_lens_cpu = common_attn_metadata.seq_lens_cpu if needs_seq_lens_cpu else None seq_lens_np = seq_lens_cpu.numpy() if seq_lens_cpu is not None else None num_blocks_np = ( (seq_lens_np + (page_size - 1)) // page_size if seq_lens_np is not None else None ) # Adjust seq_lens_cpu for DCP if self.use_dcp: assert seq_lens_cpu is not None if num_prefills > 0: qo_indptr_prefill_cpu = ( qo_indptr_cpu[num_decodes:] - qo_indptr_cpu[num_decodes] ) query_lens_prefill_cpu = ( qo_indptr_prefill_cpu[1:] - qo_indptr_prefill_cpu[:-1] ) seq_lens_cpu[num_decodes:] = ( seq_lens_cpu[num_decodes:] - query_lens_prefill_cpu ) seq_lens_cpu = get_dcp_local_seq_lens( seq_lens_cpu, self.dcp_world_size, self.dcp_rank, self.dcp_kv_cache_interleave_size, ) # Adjust num_block_np for cascade attention if use_cascade: assert num_blocks_np is not None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/__init__.py
vllm/v1/attention/backends/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mamba1_attn.py
vllm/v1/attention/backends/mamba1_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from vllm.attention.backends.abstract import AttentionBackend from vllm.v1.attention.backends.mamba_attn import ( BaseMambaAttentionMetadata, BaseMambaAttentionMetadataBuilder, ) class Mamba1AttentionBackend(AttentionBackend): @staticmethod def get_builder_cls() -> type["Mamba1AttentionMetadataBuilder"]: return Mamba1AttentionMetadataBuilder @dataclass class Mamba1AttentionMetadata(BaseMambaAttentionMetadata): pass class Mamba1AttentionMetadataBuilder( BaseMambaAttentionMetadataBuilder[Mamba1AttentionMetadata] ): metadata_cls = Mamba1AttentionMetadata supports_update_block_table: bool = False
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/rocm_aiter_fa.py
vllm/v1/attention/backends/rocm_aiter_fa.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with AiterFlashAttention.""" from dataclasses import dataclass from typing import ClassVar import torch from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionType, MultipleOf, ) from vllm.attention.layer import Attention from vllm.attention.ops.merge_attn_states import merge_attn_states from vllm.config import VllmConfig, get_layers_from_vllm_config from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.math_utils import cdiv from vllm.utils.platform_utils import get_cu_count from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, split_decodes_prefills_and_extends, ) from vllm.v1.kv_cache_interface import AttentionSpec _PARTITION_SIZE_ROCM = 256 _CP_TOKENS_PER_ITER_ROCM = 32 * 1024 if current_platform.is_rocm(): import aiter from vllm.triton_utils import tl, triton def block_size(x, head_dim): return min(65536 // x.element_size(), triton.next_power_of_2(head_dim)) def num_programs(total_tokens): return min(total_tokens, get_cu_count()) @triton.jit def cp_mha_gather_cache_kernel( key_cache_ptr, # [num_blocks, page_size, num_head, head_size] value_cache_ptr, # [num_blocks, page_size, num_head, head_size] key_ptr, # [num_tokens, num_heads, head_size] value_ptr, # [num_tokens, num_heads, head_size] block_table_ptr, # [num_batches, max_block_num] cu_seqlens_kv_ptr, # [num_batches + 1] token_to_batch_ptr, # [max_cum_tokens] seq_start_ptr, # [num_batches] k_scale_ptr, v_scale_ptr, num_heads, head_size, x, max_block_num, DEQUANT: tl.constexpr, PAGE_SIZE: tl.constexpr, CACHE_FORMAT: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): token_id = tl.program_id(0) col_offsets = tl.arange(0, BLOCK_SIZE) if DEQUANT: k_scale = tl.load(k_scale_ptr) v_scale = tl.load(v_scale_ptr) key_ptr_offset = key_ptr + token_id * head_size * num_heads value_ptr_offset = value_ptr + token_id * head_size * num_heads batch_idx = tl.load(token_to_batch_ptr + token_id) batch_start = tl.load(seq_start_ptr + batch_idx) token_start = tl.load(cu_seqlens_kv_ptr + batch_idx) batch_offset = token_id - token_start + batch_start block_offset = batch_offset // PAGE_SIZE block_id = tl.load( block_table_ptr + max_block_num * batch_idx + block_offset ).to(tl.int64) slot_id = batch_offset % PAGE_SIZE if CACHE_FORMAT == "NHD": # for kv cache layout as # K: [num_blocks, page_size, num_head, head_dim] # V: [num_blocks, page_size, num_head, head_dim] key_cache_ptr_offset = ( key_cache_ptr + block_id * num_heads * head_size * PAGE_SIZE + slot_id * num_heads * head_size ) value_cache_ptr_offset = ( value_cache_ptr + block_id * num_heads * head_size * PAGE_SIZE + slot_id * num_heads * head_size ) for i in tl.range(0, head_size * num_heads, BLOCK_SIZE): mask = (col_offsets + i) < head_size * num_heads k_reg = tl.load(key_cache_ptr_offset + col_offsets + i, mask=mask) v_reg = tl.load(value_cache_ptr_offset + col_offsets + i, mask=mask) if DEQUANT: k_dtype = k_reg.dtype v_dtype = v_reg.dtype k_reg = (k_reg.to(tl.float32) * k_scale).to(k_dtype) v_reg = (v_reg.to(tl.float32) * v_scale).to(v_dtype) tl.store(key_ptr_offset + col_offsets + i, k_reg, mask=mask) tl.store(value_ptr_offset + col_offsets + i, v_reg, mask=mask) def cp_mha_gather_cache( key_cache: torch.Tensor, value_cache: torch.Tensor, key: torch.Tensor, value: torch.Tensor, block_tables: torch.Tensor, k_scales: torch.Tensor, v_scales: torch.Tensor, cu_seqlens_kv: torch.Tensor, token_to_batch: torch.Tensor, seq_starts: torch.Tensor, dequant: bool, kv_cache_layout: str, total_tokens: int, ): assert kv_cache_layout in ["v0", "NHD", "HND"], ( "kv_cache_layout only support v0, NHD, HND" ) head_dim = key.shape[2] x = 0 # assert dequant is True, "Currently, we only support "\ # "gather cache with dequant" # For k cache layout: [num_blocks, num_heads, page_size, head_dim] assert kv_cache_layout == "NHD", ( "ROCM_AITER_FA_BACKEND Only support NHD kv cache layout for now" ) assert head_dim == key_cache.shape[3], ( "We assume your kv cache layout is [num_blocks, " "page_size, num_heads, head_dim], but got otherwise" ) page_size = key_cache.shape[1] num_heads = key_cache.shape[2] grid = lambda meta: (total_tokens,) cp_mha_gather_cache_kernel[grid]( key_cache, value_cache, key, value, block_tables, cu_seqlens_kv, token_to_batch, seq_starts, k_scales, v_scales, num_heads, head_dim, x, block_tables.size(1), DEQUANT=dequant, PAGE_SIZE=page_size, CACHE_FORMAT=kv_cache_layout, BLOCK_SIZE=head_dim, ) logger = init_logger(__name__) @dataclass class AiterFlashAttentionDecodeMetadata: max_query_len: int min_query_len: int max_seq_len: int query_start_loc: torch.Tensor @dataclass class AiterFlashAttentionPrefillMetadata: max_query_len: int min_query_len: int max_seq_len: int query_start_loc: torch.Tensor @dataclass class AiterChunkSlidingWindowMetadata: swa_seqlens: torch.Tensor swa_cu_seqlens: torch.Tensor swa_seq_starts: torch.Tensor swa_token_to_batch: torch.Tensor swa_max_seqlens: int swa_total_tokens: int swa_workspace: torch.Tensor @dataclass class AiterChunkContextMetadata: workspace: torch.Tensor cu_seq_lens_chunk: torch.Tensor chunk_starts: torch.Tensor token_to_batch: torch.Tensor seq_tot: list[int] max_seq_lens: list[int] seq_lens: torch.Tensor num_chunks: int total_token_per_batch: list[int] swa_metadata: AiterChunkSlidingWindowMetadata | None @dataclass class AiterFlashAttentionChunkPrefillMetadata: max_query_len: int min_query_len: int max_seq_len: int query_start_loc: torch.Tensor chunk_context_metadata: AiterChunkContextMetadata @dataclass class AiterFlashAttentionMetadata: # NOTE(sang): Definition of context_len, query_len, and seq_len. # |---------- N-1 iteration --------| # |---------------- N iteration ---------------------| # |- tokenA -|......................|-- newTokens ---| # |---------- context_len ----------| # |-------------------- seq_len ---------------------| # |-- query_len ---| num_actual_tokens: int # Number of tokens excluding padding. num_actual_kv_tokens: int max_query_len: int query_start_loc: torch.Tensor max_seq_len: int seq_lens: torch.Tensor slot_mapping: torch.Tensor block_table: torch.Tensor # prefill and deocde split num_decodes: int num_decode_tokens: int num_prefills: int num_prefill_tokens: int num_extends: int num_extend_tokens: int decode_metadata: AiterFlashAttentionDecodeMetadata | None prefill_metadata: AiterFlashAttentionPrefillMetadata | None extend_metadata: AiterFlashAttentionChunkPrefillMetadata | None # For cascade attention. use_cascade: bool common_prefix_len: int total_tokens: int class AiterFlashAttentionMetadataBuilder( AttentionMetadataBuilder[AiterFlashAttentionMetadata] ): _cudagraph_support = AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE reorder_batch_threshold: int = 1 def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.model_config = vllm_config.model_config self.parallel_config = vllm_config.parallel_config self.cache_config = vllm_config.cache_config self.num_heads_q = self.model_config.get_num_attention_heads( self.parallel_config ) self.num_heads_kv = self.model_config.get_num_kv_heads(self.parallel_config) self.headdim = self.model_config.get_head_size() self.block_size = kv_cache_spec.block_size # Sliding window size to be used with the AOT scheduler will be # populated on first build() call. self.aot_sliding_window: tuple[int, int] | None = None self.total_tokens: int = 0 sliding_window_configs: set[tuple[int, int] | None] = set() layers = get_layers_from_vllm_config(self.vllm_config, Attention) for layer in layers.values(): assert isinstance(layer.impl, AiterFlashAttentionImpl) sliding_window_configs.add(layer.impl.sliding_window) while len(sliding_window_configs) > 0: sliding_window_config = sliding_window_configs.pop() if sliding_window_config is not None and sliding_window_config[0] != -1: assert self.aot_sliding_window is None, ( "Aiter Flash ATTENTION can only support one valid sliding window!" ) self.aot_sliding_window = sliding_window_config self.extend_workspace = torch.empty( [2, _CP_TOKENS_PER_ITER_ROCM, self.num_heads_kv, self.headdim], dtype=self.model_config.dtype, device=device, ) def build_for_cudagraph_capture( self, common_attn_metadata: CommonAttentionMetadata ): self.total_tokens = ( self.model_config.max_model_len * self.vllm_config.scheduler_config.max_num_partial_prefills ) res = self.build(common_prefix_len=0, common_attn_metadata=common_attn_metadata) self.total_tokens = 0 return res def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> "AiterFlashAttentionMetadata": split_ret = split_decodes_prefills_and_extends( common_attn_metadata, decode_threshold=self.reorder_batch_threshold, ) ( num_decodes, num_extends, num_prefills, num_decode_tokens, num_extend_tokens, num_prefill_tokens, ) = split_ret query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu seq_lens = common_attn_metadata.seq_lens_cpu query_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1] decode_metadata = None if num_decodes > 0: decode_metadata = AiterFlashAttentionDecodeMetadata( max_query_len=query_lens_cpu[:num_decodes].max().item(), min_query_len=query_lens_cpu[:num_decodes].min().item(), max_seq_len=seq_lens[:num_decodes].max().item(), query_start_loc=common_attn_metadata.query_start_loc[: num_decodes + 1], ) prefill_metadata = None if num_prefills > 0: query_lens_for_prefill = query_lens_cpu[num_decodes + num_extends :] query_start_loc_device = common_attn_metadata.query_start_loc[ num_decodes + num_extends : ] prefill_metadata = AiterFlashAttentionPrefillMetadata( max_query_len=query_lens_for_prefill.max().item(), min_query_len=query_lens_for_prefill.min().item(), max_seq_len=seq_lens[num_decodes + num_extends :].max().item(), query_start_loc=query_start_loc_device - query_start_loc_device[0], ) extend_metadata = None if num_extends > 0: num_extends_slice = slice(num_decodes, num_decodes + num_extends) query_lens_for_extend = query_lens_cpu[num_extends_slice] seq_lens_for_extend = common_attn_metadata.seq_lens_cpu[num_extends_slice] computed_kv_lens = seq_lens_for_extend - query_lens_for_extend swa_metadata = None if self.aot_sliding_window is not None: swa_seqlen_for_extend = torch.minimum( seq_lens_for_extend, query_lens_for_extend + self.aot_sliding_window[0] + 1, ) cu_seq_lens = torch.zeros( num_extends + 1, dtype=torch.int32, device=seq_lens_for_extend.device, ) torch.cumsum( swa_seqlen_for_extend, dim=0, dtype=cu_seq_lens.dtype, out=cu_seq_lens[1:], ) token_to_seq = torch.arange( 0, num_extends, dtype=torch.int32, device=seq_lens_for_extend.device, ) token_to_seq = torch.repeat_interleave( token_to_seq, swa_seqlen_for_extend ) fetched_shape = cu_seq_lens[-1].item() # TODO(ganyi): Maybe reuse these 2 buffer from extend_workspace swa_workspace = torch.empty( (2, fetched_shape, self.num_heads_kv, self.headdim), dtype=self.vllm_config.model_config.dtype, device=self.device, ) seq_starts = seq_lens_for_extend - swa_seqlen_for_extend max_seqlen_k = swa_seqlen_for_extend.max().item() total_tokens = cu_seq_lens[-1].item() swa_metadata = AiterChunkSlidingWindowMetadata( swa_seqlens=swa_seqlen_for_extend.to( self.device, non_blocking=True ), swa_cu_seqlens=cu_seq_lens.to(self.device, non_blocking=True), swa_seq_starts=seq_starts.to(self.device, non_blocking=True), swa_token_to_batch=token_to_seq.to(self.device, non_blocking=True), swa_max_seqlens=max_seqlen_k, swa_total_tokens=total_tokens, swa_workspace=swa_workspace, ) # allocate the equal amount of workspace for # each chunk prefill request max_context_chunk = _CP_TOKENS_PER_ITER_ROCM // num_extends num_chunks = cdiv(computed_kv_lens.max().item(), max_context_chunk) chunk_starts = ( torch.arange(num_chunks, dtype=torch.int32) .unsqueeze(1) .expand(-1, num_extends) * max_context_chunk ) chunk_ends = torch.min( computed_kv_lens.unsqueeze(0), chunk_starts + max_context_chunk ) chunk_seq_lens = (chunk_ends - chunk_starts).clamp( min=0 ) # [num_chunks, num_extends] cu_seq_lens_cpu = torch.zeros( [num_chunks, num_extends + 1], dtype=torch.int32, pin_memory=True ) torch.cumsum( chunk_seq_lens, dim=1, out=cu_seq_lens_cpu[:, 1:], dtype=torch.int32 ) max_cum_tokens = cu_seq_lens_cpu[:, -1].max().item() range_idx = torch.arange(max_cum_tokens, dtype=torch.int32)[None, None, :] idx_to_batch_tensor = range_idx == cu_seq_lens_cpu[:, 1:][:, :, None] idx_to_batch_tensor = idx_to_batch_tensor.sum( dim=1 ) # [num_chunks, max_cum_tokens] token_to_batch_tensor = torch.cumsum(idx_to_batch_tensor, dim=1) chunk_context_metadata = AiterChunkContextMetadata( workspace=self.extend_workspace, cu_seq_lens_chunk=cu_seq_lens_cpu.to(self.device, non_blocking=True), chunk_starts=chunk_starts.to(self.device, non_blocking=True), seq_tot=chunk_seq_lens.sum(dim=1).tolist(), max_seq_lens=chunk_seq_lens.max(dim=1).values.tolist(), seq_lens=chunk_seq_lens, token_to_batch=token_to_batch_tensor.to(self.device, non_blocking=True), num_chunks=num_chunks, total_token_per_batch=cu_seq_lens_cpu[:, -1].tolist(), swa_metadata=swa_metadata, ) query_start_loc_device = common_attn_metadata.query_start_loc[ num_decodes : num_decodes + num_extends + 1 ] seq_lens_device = common_attn_metadata.seq_lens[num_extends_slice] cu_seq_lens = torch.zeros( num_extends + 1, dtype=torch.int32, device=seq_lens_device.device ) torch.cumsum( seq_lens_device, dim=0, dtype=cu_seq_lens.dtype, out=cu_seq_lens[1:] ) extend_metadata = AiterFlashAttentionChunkPrefillMetadata( max_query_len=query_lens_for_extend.max().item(), min_query_len=query_lens_for_extend.min().item(), max_seq_len=seq_lens[num_extends_slice].max().item(), query_start_loc=query_start_loc_device - query_start_loc_device[0], chunk_context_metadata=chunk_context_metadata, ) num_actual_kv_tokens = torch.sum(seq_lens).item() use_cascade = common_prefix_len > 0 attn_metadata = AiterFlashAttentionMetadata( num_actual_tokens=common_attn_metadata.num_actual_tokens, num_actual_kv_tokens=num_actual_kv_tokens, max_query_len=common_attn_metadata.max_query_len, query_start_loc=common_attn_metadata.query_start_loc, max_seq_len=common_attn_metadata.max_seq_len, seq_lens=common_attn_metadata.seq_lens, block_table=common_attn_metadata.block_table_tensor, slot_mapping=common_attn_metadata.slot_mapping, num_decodes=num_decodes, num_decode_tokens=num_decode_tokens, num_prefills=num_prefills, num_prefill_tokens=num_prefill_tokens, num_extends=num_extends, num_extend_tokens=num_extend_tokens, decode_metadata=decode_metadata, prefill_metadata=prefill_metadata, extend_metadata=extend_metadata, use_cascade=use_cascade, common_prefix_len=common_prefix_len, total_tokens=self.total_tokens, ) return attn_metadata def use_cascade_attention(self, *args, **kwargs) -> bool: return False class AiterFlashAttentionBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [MultipleOf(16)] @classmethod def get_supported_head_sizes(cls) -> list[int]: return [64, 128, 256] @staticmethod def get_name() -> str: return "FLASH_ATTN" @staticmethod def get_impl_cls() -> type["AiterFlashAttentionImpl"]: return AiterFlashAttentionImpl @staticmethod def get_builder_cls() -> type["AiterFlashAttentionMetadataBuilder"]: return AiterFlashAttentionMetadataBuilder @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) class AiterFlashAttentionImpl(AttentionImpl): 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, ) -> None: self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_kv_heads if alibi_slopes is not None: alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32) self.alibi_slopes = alibi_slopes if sliding_window is None: self.sliding_window = (-1, -1) else: self.sliding_window = (sliding_window - 1, 0) self.kv_cache_dtype = kv_cache_dtype if logits_soft_cap is None: # In flash-attn, setting logits_soft_cap as 0 means no soft cap. logits_soft_cap = 0.0 self.logits_soft_cap = logits_soft_cap self.kv_sharing_target_layer_name = kv_sharing_target_layer_name assert self.num_heads % self.num_kv_heads == 0 self.num_queries_per_kv = self.num_heads // self.num_kv_heads if attn_type not in [AttentionType.DECODER, AttentionType.ENCODER_DECODER]: raise NotImplementedError( "Encoder self-attention is not implemented for FlashAttentionImpl" ) def extend_for_sliding_window( self, attn_metadata: AiterFlashAttentionMetadata, query: torch.Tensor, key_cache, value_cache, output: torch.Tensor, cu_seqlens_q: torch.Tensor, max_seqlen_q: int, block_table: torch.Tensor, k_scale: float, v_scale: float, ): assert attn_metadata.extend_metadata is not None assert attn_metadata.extend_metadata.chunk_context_metadata is not None chunked_metadata = attn_metadata.extend_metadata.chunk_context_metadata swa_metadata = chunked_metadata.swa_metadata assert swa_metadata is not None swa_cu_seqlens = swa_metadata.swa_cu_seqlens swa_seq_starts = swa_metadata.swa_seq_starts swa_token_to_batch = swa_metadata.swa_token_to_batch swa_max_seqlens = swa_metadata.swa_max_seqlens swa_total_tokens = swa_metadata.swa_total_tokens key_fetched, value_fetched = ( swa_metadata.swa_workspace[0], swa_metadata.swa_workspace[1], ) cp_mha_gather_cache( key_cache=key_cache, value_cache=value_cache, key=key_fetched, value=value_fetched, block_tables=block_table, k_scales=k_scale, v_scales=v_scale, cu_seqlens_kv=swa_cu_seqlens, token_to_batch=swa_token_to_batch, seq_starts=swa_seq_starts, dequant=False, kv_cache_layout="NHD", total_tokens=swa_total_tokens, ) aiter.flash_attn_varlen_func( q=query, k=key_fetched, v=value_fetched, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=swa_cu_seqlens, max_seqlen_q=max_seqlen_q, max_seqlen_k=swa_max_seqlens, min_seqlen_q=1, dropout_p=0.0, softmax_scale=self.scale, causal=True, window_size=self.sliding_window, alibi_slopes=self.alibi_slopes, return_lse=False, out=output, ) def extend_forward( self, attn_metadata: AiterFlashAttentionMetadata, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_cache: torch.Tensor, value_cache: torch.Tensor, output: torch.Tensor, cu_seqlens_q: torch.Tensor, max_seqlen_q: int, max_seqlen_k: int, min_seqlen_q: int, block_table: torch.Tensor, slot_mapping: torch.Tensor, k_scale: float, v_scale: float, ): if self.sliding_window[0] != -1: self.extend_for_sliding_window( attn_metadata, query, key_cache, value_cache, output, cu_seqlens_q, max_seqlen_q, block_table, k_scale, v_scale, ) return out, lse = aiter.flash_attn_varlen_func( q=query, k=key, v=value, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_q, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_q, min_seqlen_q=min_seqlen_q, dropout_p=0.0, softmax_scale=self.scale, causal=True, window_size=self.sliding_window, alibi_slopes=self.alibi_slopes, return_lse=True, ) assert attn_metadata.extend_metadata is not None chunk_context_metadata = attn_metadata.extend_metadata.chunk_context_metadata num_chunks = chunk_context_metadata.num_chunks workspace = chunk_context_metadata.workspace cu_seqlens_kv = chunk_context_metadata.cu_seq_lens_chunk max_seqlens = chunk_context_metadata.max_seq_lens chunk_starts = chunk_context_metadata.chunk_starts token_to_batch = chunk_context_metadata.token_to_batch total_token_per_batch = chunk_context_metadata.total_token_per_batch key_fetched, value_fetched = workspace[0], workspace[1] chunked_output = None chunked_lse = None for chunk_idx in range(num_chunks): cp_mha_gather_cache( key_cache=key_cache, value_cache=value_cache, key=key_fetched, value=value_fetched, block_tables=block_table, k_scales=k_scale, v_scales=v_scale, cu_seqlens_kv=cu_seqlens_kv[chunk_idx], token_to_batch=token_to_batch[chunk_idx], seq_starts=chunk_starts[chunk_idx], dequant=False, kv_cache_layout="NHD", total_tokens=total_token_per_batch[chunk_idx], ) suf_out, suf_lse = aiter.flash_attn_varlen_func( q=query, k=key_fetched, v=value_fetched, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_kv[chunk_idx], max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlens[chunk_idx], min_seqlen_q=min_seqlen_q, dropout_p=0.0, softmax_scale=self.scale, causal=False, window_size=self.sliding_window, alibi_slopes=self.alibi_slopes, return_lse=True, ) if chunked_output is None: chunked_output = suf_out chunked_lse = suf_lse else: tmp_output = torch.empty_like(out) tmp_lse = torch.empty_like(lse) merge_attn_states( output=tmp_output, output_lse=tmp_lse, prefix_output=chunked_output, prefix_lse=chunked_lse, suffix_output=suf_out, suffix_lse=suf_lse, ) chunked_output = tmp_output chunked_lse = tmp_lse merge_attn_states( output=output, prefix_output=chunked_output, prefix_lse=chunked_lse, suffix_output=out, suffix_lse=lse, ) def forward( self, layer: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, attn_metadata: AiterFlashAttentionMetadata, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Forward pass with AiterFlashAttention. 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] NOTE: FP8 quantization, flash-attn expect the size of {q,k,v}_descale to be (num_sequences, num_kv_heads). We use torch's .expand() to avoid duplicating values """ assert output is not None, "Output tensor must be provided." if output_scale is not None or output_block_scale is not None: raise NotImplementedError( "fused output quantization is not yet supported for FlashAttentionImpl" ) if attn_metadata is None: # Profiling run. return output.fill_(0) # 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 key_cache, value_cache = kv_cache.unbind(0) # key and value may be None in the case of cross attention. They are # calculated once based on the output from the encoder and then cached # in KV cache. if ( self.kv_sharing_target_layer_name is None and key is not None and value is not None ): # Reshape the input keys and values and store them in the cache. # Skip this if sharing KV cache with an earlier attention layer. # NOTE(woosuk): Here, key and value are padded while slot_mapping # is not padded. However, we don't need to do # key[:num_actual_tokens] and value[:num_actual_tokens] because # the reshape_and_cache_flash op uses the slot_mapping's shape # to determine the number of actual tokens. torch.ops._C_cache_ops.reshape_and_cache_flash( key, value, key_cache, value_cache, attn_metadata.slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) if self.kv_cache_dtype.startswith("fp8"): key_cache = key_cache.view(current_platform.fp8_dtype()) value_cache = value_cache.view(current_platform.fp8_dtype()) # decode:extend:prefill query = query[:num_actual_tokens] if key is not None: key = key[:num_actual_tokens] if value is not None: value = value[:num_actual_tokens] output_actual_tokens = output[:num_actual_tokens] num_decodes = attn_metadata.num_decodes num_prefills = attn_metadata.num_prefills num_extends = attn_metadata.num_extends num_decode_tokens = attn_metadata.num_decode_tokens num_extend_tokens = attn_metadata.num_extend_tokens if not attn_metadata.use_cascade: # calculate for pure prefills if num_prefills > 0:
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/tree_attn.py
vllm/v1/attention/backends/tree_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with TreeAttention.""" import ast from dataclasses import dataclass from typing import ClassVar, Optional import torch from vllm import _custom_ops as ops from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionType, MultipleOf, ) from vllm.attention.ops.triton_unified_attention import unified_attention from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.v1.attention.backends.utils import ( AttentionMetadataBuilder, CommonAttentionMetadata, split_decodes_and_prefills, ) from vllm.v1.kv_cache_interface import AttentionSpec logger = init_logger(__name__) class TreeAttentionBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [MultipleOf(16)] @classmethod def get_supported_head_sizes(cls) -> list[int]: return [32, 64, 96, 128, 160, 192, 224, 256] @staticmethod def get_name() -> str: return "TREE_ATTN" @staticmethod def get_impl_cls() -> type["TreeAttentionImpl"]: return TreeAttentionImpl @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 get_builder_cls() -> type["TreeAttentionMetadataBuilder"]: return TreeAttentionMetadataBuilder @staticmethod def use_cascade_attention(*args, **kwargs) -> bool: return False @dataclass class TreeAttentionMetadata: num_actual_tokens: int # Number of tokens excluding padding. max_query_len: int query_start_loc: torch.Tensor max_seq_len: int seq_lens: torch.Tensor block_table: torch.Tensor slot_mapping: torch.Tensor num_prefill_tokens: int = 0 num_decode_tokens: int = 0 num_prefills: int = 0 num_decodes: int = 0 tree_attn_bias: torch.Tensor | None = None # Cached Prefill/decode metadata. _cached_prefill_metadata: Optional["TreeAttentionMetadata"] = None _cached_decode_metadata: Optional["TreeAttentionMetadata"] = None @property def prefill_metadata(self) -> Optional["TreeAttentionMetadata"]: if self.num_prefills == 0: return None if self._cached_prefill_metadata is not None: # Recover cached prefill-phase attention # metadata structure return self._cached_prefill_metadata q_start_loc = self.query_start_loc[self.num_decodes :] q_seqlens = torch.diff(q_start_loc) kv_seqlens = self.seq_lens[self.num_decodes :] # Construct & cache prefill-phase attention metadata structure self._cached_prefill_metadata = TreeAttentionMetadata( num_actual_tokens=self.num_prefill_tokens, max_query_len=int(q_seqlens.max().item()), query_start_loc=q_start_loc - q_start_loc[0], max_seq_len=int(kv_seqlens.max().item()), seq_lens=kv_seqlens, block_table=self.block_table[self.num_decodes :], slot_mapping=self.slot_mapping[self.num_decode_tokens :], ) return self._cached_prefill_metadata @property def decode_metadata(self) -> Optional["TreeAttentionMetadata"]: if self.num_decode_tokens == 0: return None if self._cached_decode_metadata is not None: # Recover cached decode-phase attention # metadata structure return self._cached_decode_metadata q_start_loc = self.query_start_loc[: self.num_decodes + 1] q_seqlens = torch.diff(q_start_loc) kv_seqlens = self.seq_lens[: self.num_decodes] # Construct & cache decode-phase attention metadata structure self._cached_decode_metadata = TreeAttentionMetadata( num_actual_tokens=self.num_decode_tokens, max_query_len=int(q_seqlens.max().item()), query_start_loc=q_start_loc, max_seq_len=int(kv_seqlens.max().item()), seq_lens=kv_seqlens, block_table=self.block_table[: self.num_decodes], slot_mapping=self.slot_mapping[: self.num_decode_tokens], tree_attn_bias=self.tree_attn_bias, ) return self._cached_decode_metadata class TreeAttentionMetadataBuilder(AttentionMetadataBuilder[TreeAttentionMetadata]): def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.block_size = kv_cache_spec.block_size spec_config = vllm_config.speculative_config spec_token_tree = (spec := spec_config) and spec.speculative_token_tree tree_choices: list[tuple[int, ...]] = ( ast.literal_eval(spec_token_tree) if spec_token_tree is not None else [(0,)] ) # Construct the tree attention bias. depth_counts = _get_depth_counts(tree_choices) self.tree_attn_bias = _prepare_tree_attn_bias( tree_choices, depth_counts, dtype=torch.float32, device=device, ) self.reorder_batch_threshold = self.tree_attn_bias.shape[0] def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> TreeAttentionMetadata: decode_threshold = self.tree_attn_bias.shape[0] num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=decode_threshold ) ) num_actual_tokens = common_attn_metadata.num_actual_tokens q_start_loc = common_attn_metadata.query_start_loc max_query_len = common_attn_metadata.max_query_len kv_seqlens = common_attn_metadata.seq_lens max_seq_len = common_attn_metadata.max_seq_len block_table = common_attn_metadata.block_table_tensor slot_mapping = common_attn_metadata.slot_mapping return TreeAttentionMetadata( num_actual_tokens=num_actual_tokens, num_prefill_tokens=num_prefill_tokens, num_decode_tokens=num_decode_tokens, num_prefills=num_prefills, num_decodes=num_decodes, max_query_len=max_query_len, query_start_loc=q_start_loc, max_seq_len=max_seq_len, seq_lens=kv_seqlens, block_table=block_table, slot_mapping=slot_mapping, tree_attn_bias=self.tree_attn_bias, ) def build_for_drafting( self, common_attn_metadata: CommonAttentionMetadata, draft_index: int, ) -> TreeAttentionMetadata: # Cache the original tree attention bias. orig_tree_attn_bias = self.tree_attn_bias if draft_index == 0: # Use prefill for drafting at the root level. self.tree_attn_bias = torch.empty(0) else: # Slice the tree attention bias for drafting. Exclude # the root level. start, end = 1, 1 + common_attn_metadata.max_query_len self.tree_attn_bias = self.tree_attn_bias[start:end, start:end].contiguous() # Build attention bias. attn_metadata = self.build(0, common_attn_metadata, fast_build=True) # Reset the tree attention bias to the original value. self.tree_attn_bias = orig_tree_attn_bias return attn_metadata def _get_depth_counts(sorted_tree_choices: list[tuple[int, ...]]) -> list[int]: # Count the number of choices at each depth of the tree. depth_counts = [] prev_depth = 0 for path in sorted_tree_choices: depth = len(path) if depth != prev_depth: depth_counts.append(0) depth_counts[depth - 1] += 1 prev_depth = depth return depth_counts def _prepare_tree_attn_bias( sorted_tree_choices: list[tuple[int, ...]], depth_counts: list[int], dtype: torch.dtype | None, device: torch.device | None, ) -> torch.Tensor: # +1 comes from the additional root node. tree_len = len(sorted_tree_choices) + 1 tree_attn_mask = torch.full( (tree_len, tree_len), -torch.inf, device=device, dtype=dtype ) # Set diagonal to all zeros. Each token should # attend to itself. mask_val = 0 for i in range(tree_len): tree_attn_mask[i, i] = mask_val # Set root to all zeros. All tokens attend to it. tree_attn_mask[:, 0] = mask_val # Set all ancestors to zeros. start = 0 for i in range(len(depth_counts)): for j in range(depth_counts[i]): cur_tree_choice = sorted_tree_choices[start + j] # Retrieve ancestor position. if len(cur_tree_choice) == 1: continue ancestor_idx = [] for c in range(len(cur_tree_choice) - 1): ancestor_idx.append( sorted_tree_choices.index(cur_tree_choice[: c + 1]) + 1 ) tree_attn_mask[j + start + 1, ancestor_idx] = mask_val start += depth_counts[i] return tree_attn_mask class TreeAttentionImpl(AttentionImpl): 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: str | None = None, ) -> None: self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_kv_heads self.num_queries_per_kv = self.num_heads // self.num_kv_heads self.kv_cache_dtype = kv_cache_dtype self.kv_sharing_target_layer_name = kv_sharing_target_layer_name if alibi_slopes is not None: alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32) self.alibi_slopes = alibi_slopes if logits_soft_cap is None: # Setting logits_soft_cap to 0 means no soft cap. logits_soft_cap = 0 self.logits_soft_cap = logits_soft_cap if sliding_window is None: self.sliding_window = (-1, -1) else: self.sliding_window = (sliding_window - 1, 0) if attn_type != AttentionType.DECODER: raise NotImplementedError( "Encoder self-attention and " "encoder/decoder cross-attention " "are not implemented for " "TreeAttentionImpl." ) def forward( self, layer: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, kv_cache: torch.Tensor, attn_metadata: TreeAttentionMetadata, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Forward pass with TreeAttention. 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_scale is not None or output_block_scale is not None: raise NotImplementedError( "fused output quantization is not yet supported for TreeAttentionImpl" ) if attn_metadata is None: # Profiling run. return output.fill_(0) # Cache the input KVs. key_cache, value_cache = kv_cache.unbind(0) if self.kv_sharing_target_layer_name is None: # Reshape the input keys and values and store them in the cache. # Skip this if sharing KV cache with an earlier attention layer. # NOTE(woosuk): Here, key and value are padded while slot_mapping is # not padded. However, we don't need to do key[:num_actual_tokens] # and value[:num_actual_tokens] because the reshape_and_cache_flash # op uses the slot_mapping's shape to determine the number of # actual tokens. ops.reshape_and_cache_flash( key, value, key_cache, value_cache, attn_metadata.slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) num_actual_tokens = attn_metadata.num_actual_tokens num_decode_tokens = attn_metadata.num_decode_tokens descale_shape = (attn_metadata.query_start_loc.shape[0] - 1, key.shape[1]) if prefill_meta := attn_metadata.prefill_metadata: unified_attention( q=query[num_decode_tokens:num_actual_tokens], k=key_cache, v=value_cache, out=output[num_decode_tokens:num_actual_tokens], cu_seqlens_q=prefill_meta.query_start_loc, max_seqlen_q=prefill_meta.max_query_len, seqused_k=prefill_meta.seq_lens, max_seqlen_k=prefill_meta.max_seq_len, softmax_scale=self.scale, causal=True, alibi_slopes=self.alibi_slopes, window_size=self.sliding_window, block_table=prefill_meta.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), ) if decode_meta := attn_metadata.decode_metadata: unified_attention( q=query[:num_decode_tokens], k=key_cache, v=value_cache, out=output[:num_decode_tokens], cu_seqlens_q=decode_meta.query_start_loc, max_seqlen_q=decode_meta.max_query_len, seqused_k=decode_meta.seq_lens, max_seqlen_k=decode_meta.max_seq_len, softmax_scale=self.scale, causal=True, alibi_slopes=self.alibi_slopes, qq_bias=decode_meta.tree_attn_bias, window_size=self.sliding_window, block_table=decode_meta.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), ) return output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/flash_attn.py
vllm/v1/attention/backends/flash_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Attention layer with FlashAttention.""" import copy from dataclasses import dataclass from typing import ClassVar import numpy as np import torch from vllm.attention.backends.abstract import ( AttentionBackend, AttentionImpl, AttentionType, MultipleOf, is_quantized_kv_cache, ) from vllm.attention.layer import Attention from vllm.attention.ops.common import cp_lse_ag_out_rs from vllm.attention.ops.merge_attn_states import merge_attn_states from vllm.attention.utils.fa_utils import ( flash_attn_supports_fp8, get_flash_attn_version, is_flash_attn_varlen_func_available, ) if is_flash_attn_varlen_func_available(): from vllm.attention.utils.fa_utils import ( flash_attn_supports_sinks, flash_attn_varlen_func, get_scheduler_metadata, reshape_and_cache_flash, ) from vllm.config import VllmConfig, get_current_vllm_config, get_layers_from_vllm_config from vllm.config.cache import CacheDType from vllm.distributed.parallel_state import get_dcp_group from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.platforms.interface import DeviceCapability from vllm.utils.math_utils import cdiv from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, get_dcp_local_seq_lens, get_kv_cache_layout, ) from vllm.v1.kv_cache_interface import AttentionSpec logger = init_logger(__name__) class FlashAttentionBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: vllm_config = get_current_vllm_config() model_config = vllm_config.model_config cache_config = vllm_config.cache_config if ( model_config and model_config.is_hybrid and ( cache_config.mamba_ssm_cache_dtype == "float32" or cache_config.mamba_cache_dtype == "float32" ) ): # NOTE(tdoublep): while in principle, FA supports # MultipleOf(16), these are the block sizes that do not # suffer from the NaN propagation problem described here: # https://github.com/Dao-AILab/flash-attention/issues/1974 return [16, 32, 64] return [MultipleOf(16)] @staticmethod def get_name() -> str: return "FLASH_ATTN" @classmethod def supports_attn_type(cls, attn_type: str) -> bool: """FlashAttention supports all attention types.""" return attn_type in ( AttentionType.DECODER, AttentionType.ENCODER, AttentionType.ENCODER_ONLY, AttentionType.ENCODER_DECODER, ) @staticmethod def get_impl_cls() -> type["FlashAttentionImpl"]: return FlashAttentionImpl @staticmethod def get_builder_cls() -> type["FlashAttentionMetadataBuilder"]: return FlashAttentionMetadataBuilder @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 get_kv_cache_stride_order( include_num_layers_dimension: bool = False, ) -> tuple[int, ...]: # `stride_order` indicates the permutation that gets # us from `get_kv_cache_shape` to the actual memory layout we want. cache_layout = get_kv_cache_layout() if cache_layout == "NHD" and include_num_layers_dimension: # (num_blocks, num_layers, 2, block_size, num_kv_heads, head_size) return (2, 0, 1, 3, 4, 5) elif cache_layout == "NHD": stride_order = (0, 1, 2, 3, 4) elif cache_layout == "HND" and include_num_layers_dimension: # (num_blocks, num_kv_heads, num_layers, 2, block_size, head_size) return (2, 4, 0, 1, 3, 5) elif cache_layout == "HND": stride_order = (0, 1, 3, 2, 4) else: raise ValueError(f"Unknown cache layout format {cache_layout}.") return stride_order @staticmethod def get_fp8_dtype_for_flashattn(kv_cache_dtype: str) -> torch.dtype: if kv_cache_dtype in ("fp8", "fp8_e4m3"): return torch.float8_e4m3fn else: raise ValueError(f"Unrecognized FP8 dtype: {kv_cache_dtype}") @classmethod def supports_head_size(cls, head_size: int) -> bool: return head_size % 8 == 0 and head_size <= 256 @classmethod def supports_kv_cache_dtype(cls, kv_cache_dtype: CacheDType | None) -> bool: if kv_cache_dtype is None: return True if kv_cache_dtype.startswith("fp8"): return flash_attn_supports_fp8() return kv_cache_dtype in ["auto"] @classmethod def supports_sink(cls) -> bool: if not is_flash_attn_varlen_func_available(): return False return flash_attn_supports_sinks() @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return capability >= DeviceCapability(8, 0) @classmethod def supports_combination( cls, head_size: int, dtype: torch.dtype, kv_cache_dtype: CacheDType | None, block_size: int, use_mla: bool, has_sink: bool, use_sparse: bool, device_capability: DeviceCapability, ) -> str | None: if has_sink and device_capability < DeviceCapability(9, 0): return "sink not supported on compute capability < 9.0" return None @dataclass class FlashAttentionMetadata: # NOTE(sang): Definition of context_len, query_len, and seq_len. # |---------- N-1 iteration --------| # |---------------- N iteration ---------------------| # |- tokenA -|......................|-- newTokens ---| # |---------- context_len ----------| # |-------------------- seq_len ---------------------| # |-- query_len ---| num_actual_tokens: int # Number of tokens excluding padding. max_query_len: int query_start_loc: torch.Tensor max_seq_len: int seq_lens: torch.Tensor block_table: torch.Tensor slot_mapping: torch.Tensor # For cascade attention. use_cascade: bool common_prefix_len: int cu_prefix_query_lens: torch.Tensor | None prefix_kv_lens: torch.Tensor | None suffix_kv_lens: torch.Tensor | None # For GQA DCP max_dcp_context_kv_len: int | None = None dcp_context_kv_lens: torch.Tensor | None = None # Optional aot scheduling scheduler_metadata: torch.Tensor | None = None prefix_scheduler_metadata: torch.Tensor | None = None max_num_splits: int = 0 causal: bool = True def _get_sliding_window_configs( vllm_config: VllmConfig, ) -> set[tuple[int, int] | None]: """Get the set of all sliding window configs used in the model.""" sliding_window_configs: set[tuple[int, int] | None] = set() layers = get_layers_from_vllm_config(vllm_config, Attention) for layer in layers.values(): assert isinstance(layer.impl, FlashAttentionImpl) sliding_window_configs.add(layer.impl.sliding_window) return sliding_window_configs class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetadata]): # FA3: # Supports full cudagraphs for all cases. # # FA2: # For FA2, a graph is captured with max_query_len=1, (which is what we # capture by default for num_tokens <= max_num_seqs when there is no # spec-decode) then these graphs will not work for mixed prefill-decode # (unlike FA3). This is due to special max_query_len=1 packed-GQA handling # in FA2. # In summary if we are running with spec decodes the graphs would # work for mixed prefill-decode and uniform-decode. But for non-spec decodes # the graphs would not work for mixed prefill-decode; sorta the inverse # of UNIFORM_SINGLE_TOKEN_DECODE. # There's probably a better way to describe this using `AttentionCGSupport` # but for now just set it to `UNIFORM_BATCH` to get use to drop down # to FULL_AND_PIECEWISE. # TODO(luka, lucas): audit FA2 as part of: # https://github.com/vllm-project/vllm/issues/22945 _cudagraph_support = ( AttentionCGSupport.ALWAYS if get_flash_attn_version() == 3 else AttentionCGSupport.UNIFORM_BATCH ) supports_update_block_table: bool = True def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) self.model_config = vllm_config.model_config self.parallel_config = vllm_config.parallel_config self.cache_config = vllm_config.cache_config self.compilation_config = vllm_config.compilation_config self.attention_config = vllm_config.attention_config self.num_heads_q = self.model_config.get_num_attention_heads( self.parallel_config ) self.num_heads_kv = self.model_config.get_num_kv_heads(self.parallel_config) self.kv_cache_dtype = kv_cache_spec.dtype self.headdim = self.model_config.get_head_size() self.block_size = kv_cache_spec.block_size self.max_num_splits = 0 # No upper bound on the number of splits. self.aot_schedule = get_flash_attn_version() == 3 try: from vllm.distributed.parallel_state import get_dcp_group self.dcp_world_size = get_dcp_group().world_size self.dcp_rank = get_dcp_group().rank_in_group except AssertionError: # DCP might not be initialized in testing self.dcp_world_size = 1 self.dcp_rank = 0 self.cp_kv_cache_interleave_size = ( self.parallel_config.cp_kv_cache_interleave_size ) self.use_full_cuda_graph = ( self.compilation_config.cudagraph_mode.has_full_cudagraphs() ) self.max_cudagraph_size = self.compilation_config.max_cudagraph_capture_size if self.use_full_cuda_graph and self.aot_schedule: self.scheduler_metadata = torch.zeros( vllm_config.scheduler_config.max_num_seqs + 1, dtype=torch.int32, device=self.device, ) # When using cuda graph, we need to set the upper bound of the # number of splits so that large enough intermediate buffers are # pre-allocated during capture. self.max_num_splits = ( self.attention_config.flash_attn_max_num_splits_for_cuda_graph ) # Sliding window size to be used with the AOT scheduler will be # populated on first build() call. self.aot_sliding_window: tuple[int, int] | None = None def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> FlashAttentionMetadata: """ fast_build disables AOT scheduling, used when there will be few iterations i.e. spec-decode """ num_reqs = common_attn_metadata.num_reqs num_actual_tokens = common_attn_metadata.num_actual_tokens max_query_len = common_attn_metadata.max_query_len max_seq_len = common_attn_metadata.max_seq_len query_start_loc = common_attn_metadata.query_start_loc seq_lens = common_attn_metadata.seq_lens block_table_tensor = common_attn_metadata.block_table_tensor slot_mapping = common_attn_metadata.slot_mapping causal = common_attn_metadata.causal # the overhead of the aot schedule is not worth it for spec-decode aot_schedule = self.aot_schedule and not fast_build if self.aot_sliding_window is None: self.aot_sliding_window = (-1, -1) # For the AOT scheduler we need the sliding window value to be # constant for all layers to. We have to populate this on the first # build() call so the layers are constructed (cannot populate) # in __init__. if aot_schedule: sliding_window_configs = _get_sliding_window_configs(self.vllm_config) if len(sliding_window_configs) == 1: sliding_window_config = sliding_window_configs.pop() if sliding_window_config is not None: self.aot_sliding_window = sliding_window_config elif len(sliding_window_configs) > 1: self.aot_schedule = False aot_schedule = False max_num_splits = 0 # 0 means use FA3's heuristics, not CG compatible if self.use_full_cuda_graph and num_actual_tokens <= self.max_cudagraph_size: # NOTE(woosuk): Setting num_splits > 1 may increase the memory # usage, because the intermediate buffers of size [num_splits, # num_heads, num_tokens, head_size] are allocated. Therefore, # we only set num_splits when using cuda graphs. max_num_splits = self.max_num_splits if vllm_is_batch_invariant(): max_num_splits = 1 def schedule( batch_size, cu_query_lens, max_query_len, seqlens, max_seq_len, causal ): cache_dtype = self.cache_config.cache_dtype if cache_dtype.startswith("fp8"): qkv_dtype = FlashAttentionBackend.get_fp8_dtype_for_flashattn( cache_dtype ) else: qkv_dtype = self.kv_cache_dtype if aot_schedule: return get_scheduler_metadata( batch_size=batch_size, max_seqlen_q=max_query_len, max_seqlen_k=max_seq_len, num_heads_q=self.num_heads_q * self.dcp_world_size, num_heads_kv=self.num_heads_kv, headdim=self.headdim, cache_seqlens=seqlens, qkv_dtype=qkv_dtype, cu_seqlens_q=cu_query_lens, page_size=self.block_size, causal=causal, window_size=self.aot_sliding_window, num_splits=max_num_splits, ) return None use_cascade = common_prefix_len > 0 max_dcp_context_kv_len = 0 dcp_context_kv_lens = None cu_prefix_query_lens = None prefix_kv_lens = None suffix_kv_lens = None prefix_scheduler_metadata = None if self.dcp_world_size > 1: query_kv_lens = query_start_loc[1:] - query_start_loc[:-1] dcp_context_kv_lens = seq_lens - query_kv_lens dcp_context_kv_lens = get_dcp_local_seq_lens( dcp_context_kv_lens, self.dcp_world_size, self.dcp_rank, self.cp_kv_cache_interleave_size, ) # After DCP distribution, the maximum number of tokens for any rank is # ceil(L / (N * I)) * I, where L is max_seq_len, N is dcp_world_size, # and I is cp_kv_cache_interleave_size. # This eliminates GPU->CPU sync while minimizing workspace over-allocation. num_partitions = self.dcp_world_size * self.cp_kv_cache_interleave_size max_dcp_context_kv_len = ( (max_seq_len + num_partitions - 1) // num_partitions ) * self.cp_kv_cache_interleave_size scheduler_metadata = schedule( batch_size=num_reqs, cu_query_lens=query_start_loc, max_query_len=max_query_len, seqlens=dcp_context_kv_lens, max_seq_len=max_dcp_context_kv_len, causal=False, ) elif use_cascade: cu_prefix_query_lens = torch.tensor( [0, num_actual_tokens], dtype=torch.int32, device=self.device ) prefix_kv_lens = torch.tensor( [common_prefix_len], dtype=torch.int32, device=self.device ) # Use GPU tensor directly - no CPU sync needed suffix_kv_lens = seq_lens[:num_reqs] - common_prefix_len prefix_scheduler_metadata = schedule( batch_size=1, cu_query_lens=cu_prefix_query_lens, max_query_len=num_actual_tokens, seqlens=prefix_kv_lens, max_seq_len=common_prefix_len, causal=False, ) scheduler_metadata = schedule( batch_size=num_reqs, cu_query_lens=query_start_loc, max_query_len=max_query_len, seqlens=suffix_kv_lens, max_seq_len=max_seq_len - common_prefix_len, causal=True, ) else: scheduler_metadata = schedule( batch_size=num_reqs, cu_query_lens=query_start_loc, max_query_len=max_query_len, seqlens=seq_lens, max_seq_len=max_seq_len, causal=causal, ) # For FA3 + full cudagraph if self.use_full_cuda_graph and scheduler_metadata is not None: n = scheduler_metadata.shape[0] self.scheduler_metadata[:n] = scheduler_metadata # NOTE(woosuk): We should zero out the rest of the scheduler # metadata to guarantee the correctness. Otherwise, some thread # blocks may use the invalid scheduler metadata and overwrite the # output buffer. self.scheduler_metadata[n:] = 0 scheduler_metadata = self.scheduler_metadata[:n] attn_metadata = FlashAttentionMetadata( num_actual_tokens=num_actual_tokens, max_query_len=max_query_len, query_start_loc=query_start_loc, max_seq_len=max_seq_len, seq_lens=seq_lens, block_table=block_table_tensor, slot_mapping=slot_mapping, max_dcp_context_kv_len=max_dcp_context_kv_len, dcp_context_kv_lens=dcp_context_kv_lens, use_cascade=use_cascade, common_prefix_len=common_prefix_len, scheduler_metadata=scheduler_metadata, cu_prefix_query_lens=cu_prefix_query_lens, prefix_kv_lens=prefix_kv_lens, suffix_kv_lens=suffix_kv_lens, prefix_scheduler_metadata=prefix_scheduler_metadata, max_num_splits=max_num_splits, causal=causal, ) return attn_metadata def update_block_table( self, metadata: FlashAttentionMetadata, blk_table: torch.Tensor, slot_mapping: torch.Tensor, ) -> FlashAttentionMetadata: new_metadata = copy.copy(metadata) new_metadata.block_table = blk_table new_metadata.slot_mapping = slot_mapping return new_metadata def use_cascade_attention(self, *args, **kwargs) -> bool: return use_cascade_attention(*args, **kwargs) class FlashAttentionImpl(AttentionImpl): can_return_lse_for_decode: bool = True 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: str | None = None, sinks: torch.Tensor | None = None, ) -> None: self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_kv_heads if alibi_slopes is not None: alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32) self.alibi_slopes = alibi_slopes if sliding_window is None: self.sliding_window = (-1, -1) elif attn_type == AttentionType.ENCODER_ONLY: self.sliding_window = (sliding_window - 1, sliding_window - 1) else: self.sliding_window = (sliding_window - 1, 0) self.kv_cache_dtype = kv_cache_dtype if logits_soft_cap is None: # In flash-attn, setting logits_soft_cap as 0 means no soft cap. logits_soft_cap = 0 self.logits_soft_cap = logits_soft_cap self.kv_sharing_target_layer_name = kv_sharing_target_layer_name self.num_queries_per_kv = self.num_heads // self.num_kv_heads self.attn_type = attn_type self.vllm_flash_attn_version = get_flash_attn_version() # Cache the batch invariant result for use in forward passes self.batch_invariant_enabled = vllm_is_batch_invariant() if is_quantized_kv_cache(self.kv_cache_dtype) and not flash_attn_supports_fp8(): raise NotImplementedError( "FlashAttention does not support fp8 kv-cache on this device." ) self.sinks = sinks if self.sinks is not None: assert flash_attn_supports_sinks(), ( "Sinks are only supported in FlashAttention 3" ) assert self.sinks.shape[0] == num_heads, ( "Sinks must have the same number of heads as the number of " "heads in the layer" ) self.supports_quant_query_input = True 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] NOTE: FP8 quantization, flash-attn expect the size of {q,k,v}_descale to be (num_sequences, num_kv_heads). We use torch's .expand() to avoid duplicating values """ assert output is not None, "Output tensor must be provided." if output_scale is not None or output_block_scale is not None: raise NotImplementedError( "fused output quantization is not yet supported for FlashAttentionImpl" ) if attn_metadata is None: # Profiling run. return output.fill_(0) attn_type = self.attn_type # 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 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, ) # For decoder and cross-attention, use KV cache as before key_cache, value_cache = kv_cache.unbind(0) # key and value may be None in the case of cross attention. They are # calculated once based on the output from the encoder and then cached # in KV cache. if ( self.kv_sharing_target_layer_name is None and key is not None and value is not None ): # Reshape the input keys and values and store them in the cache. # Skip this if sharing KV cache with an earlier attention layer. # NOTE(woosuk): Here, key and value are padded while slot_mapping is # not padded. However, we don't need to do key[:num_actual_tokens] # and value[:num_actual_tokens] because the reshape_and_cache_flash # op uses the slot_mapping's shape to determine the number of # actual tokens. reshape_and_cache_flash( key, value, key_cache, value_cache, attn_metadata.slot_mapping, self.kv_cache_dtype, layer._k_scale, layer._v_scale, ) if self.kv_cache_dtype.startswith("fp8"): # queries are quantized in the attention layer dtype = FlashAttentionBackend.get_fp8_dtype_for_flashattn( self.kv_cache_dtype ) key_cache = key_cache.view(dtype) value_cache = value_cache.view(dtype) if not attn_metadata.use_cascade: 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 scheduler_metadata = attn_metadata.scheduler_metadata descale_shape = (cu_seqlens_q.shape[0] - 1, self.num_kv_heads) if self.dcp_world_size > 1: self._forward_with_dcp( query[:num_actual_tokens], key[:num_actual_tokens], value[:num_actual_tokens], key_cache, value_cache, output[:num_actual_tokens], attn_metadata, q_descale=layer._q_scale.expand(descale_shape), k_descale=layer._k_scale.expand(descale_shape), v_descale=layer._v_scale.expand(descale_shape), ) return output else: flash_attn_varlen_func( 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=attn_metadata.causal, alibi_slopes=self.alibi_slopes, window_size=self.sliding_window, block_table=block_table, softcap=self.logits_soft_cap, scheduler_metadata=scheduler_metadata, fa_version=self.vllm_flash_attn_version, q_descale=layer._q_scale.expand(descale_shape), k_descale=layer._k_scale.expand(descale_shape), v_descale=layer._v_scale.expand(descale_shape), num_splits=attn_metadata.max_num_splits, s_aux=self.sinks, ) return output # Cascade attention (rare case). cascade_attention( output[:num_actual_tokens], query[:num_actual_tokens], key_cache, value_cache, cu_query_lens=attn_metadata.query_start_loc, max_query_len=attn_metadata.max_query_len, cu_prefix_query_lens=attn_metadata.cu_prefix_query_lens, prefix_kv_lens=attn_metadata.prefix_kv_lens, suffix_kv_lens=attn_metadata.suffix_kv_lens, max_kv_len=attn_metadata.max_seq_len, softmax_scale=self.scale, alibi_slopes=self.alibi_slopes, sliding_window=self.sliding_window, logits_soft_cap=self.logits_soft_cap, block_table=attn_metadata.block_table, common_prefix_len=attn_metadata.common_prefix_len, max_num_splits=attn_metadata.max_num_splits, fa_version=self.vllm_flash_attn_version, prefix_scheduler_metadata=attn_metadata.prefix_scheduler_metadata, suffix_scheduler_metadata=attn_metadata.scheduler_metadata, q_descale=layer._q_scale, k_descale=layer._k_scale, v_descale=layer._v_scale, s_aux=self.sinks, ) return output def _forward_with_dcp( self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_cache: torch.Tensor, value_cache: torch.Tensor, output: torch.Tensor, attn_metadata: FlashAttentionMetadata, q_descale: torch.Tensor | None = None, k_descale: torch.Tensor | None = None, v_descale: torch.Tensor | None = None, ) -> torch.Tensor: cu_seqlens_q = attn_metadata.query_start_loc max_seqlen_q = attn_metadata.max_query_len block_table = attn_metadata.block_table query = query.contiguous() query_across_dcp = get_dcp_group().all_gather(query, dim=1) context_attn_out, context_lse = flash_attn_varlen_func( q=query_across_dcp, k=key_cache, v=value_cache, out=None, cu_seqlens_q=cu_seqlens_q, max_seqlen_q=max_seqlen_q, seqused_k=attn_metadata.dcp_context_kv_lens, max_seqlen_k=attn_metadata.max_dcp_context_kv_len, softmax_scale=self.scale, causal=False, alibi_slopes=self.alibi_slopes, window_size=self.sliding_window, block_table=block_table, softcap=self.logits_soft_cap, return_softmax_lse=True, scheduler_metadata=attn_metadata.scheduler_metadata, fa_version=self.vllm_flash_attn_version, q_descale=q_descale, k_descale=k_descale, v_descale=v_descale, ) # FA returns LSE in shape [ H, B ] but cp_lse_ag_out_rs wants [ B, H ] context_attn_out_cor, context_lse_cor = cp_lse_ag_out_rs( context_attn_out, context_lse.transpose(0, 1), get_dcp_group(), return_lse=True, ) context_lse_cor = context_lse_cor.transpose(0, 1).contiguous() query_attn_out, query_lse = flash_attn_varlen_func( q=query, k=key, v=value, out=None, cu_seqlens_q=cu_seqlens_q, max_seqlen_q=max_seqlen_q, cu_seqlens_k=cu_seqlens_q, max_seqlen_k=max_seqlen_q, softmax_scale=self.scale, causal=attn_metadata.causal, alibi_slopes=self.alibi_slopes, window_size=self.sliding_window, softcap=self.logits_soft_cap, return_softmax_lse=True, fa_version=self.vllm_flash_attn_version, q_descale=q_descale, k_descale=k_descale, v_descale=v_descale, ) assert context_attn_out_cor.shape == query_attn_out.shape assert context_lse_cor.shape == query_lse.shape merge_attn_states( output, context_attn_out_cor,
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mamba_attn.py
vllm/v1/attention/backends/mamba_attn.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import abc import copy from dataclasses import dataclass from typing import ClassVar, TypeVar import torch from vllm.config import VllmConfig from vllm.utils.math_utils import cdiv from vllm.v1.attention.backends.utils import ( PAD_SLOT_ID, AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, compute_causal_conv1d_metadata, split_decodes_and_prefills, ) from vllm.v1.kv_cache_interface import AttentionSpec, MambaSpec M = TypeVar("M", bound="BaseMambaAttentionMetadata") @dataclass class BaseMambaAttentionMetadata: num_prefills: int num_prefill_tokens: int num_decodes: int num_decode_tokens: int num_reqs: int # The following tensors only contain prefill requests and will be None if # the batch has no prefill request. has_initial_states_p: torch.Tensor | None query_start_loc_p: torch.Tensor | None num_computed_tokens_p: torch.Tensor | None state_indices_tensor: torch.Tensor # The following tensors are only used for prefix caching and are None if disabled block_idx_last_scheduled_token: torch.Tensor | None block_idx_first_scheduled_token_p: torch.Tensor | None block_idx_last_computed_token: torch.Tensor | None # The following attributes are for triton implementation of causal_conv1d nums_dict: dict | None = None batch_ptr: torch.Tensor | None = None token_chunk_offset_ptr: torch.Tensor | None = None class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC): metadata_cls: type[M] reorder_batch_threshold: int = 1 _cudagraph_support: ClassVar[AttentionCGSupport] = ( AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE ) supports_update_block_table: bool = True def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__(kv_cache_spec, layer_names, vllm_config, device) assert isinstance(kv_cache_spec, MambaSpec) self.compilation_config = vllm_config.compilation_config self.decode_cudagraph_max_bs = min( self.vllm_config.scheduler_config.max_num_seqs, self.compilation_config.max_cudagraph_capture_size, ) if self.vllm_config.cache_config.enable_prefix_caching: self.state_indices_tensor = torch.empty( ( self.decode_cudagraph_max_bs, cdiv( self.vllm_config.model_config.max_model_len, self.kv_cache_spec.block_size, ), ), dtype=torch.int32, device=device, ) self.block_idx_last_scheduled_token = torch.empty( (self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device, ) self.block_idx_last_computed_token = torch.empty( (self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device, ) else: self.state_indices_tensor = torch.empty( (self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device, ) def build_for_cudagraph_capture( self, common_attn_metadata: CommonAttentionMetadata ) -> M: """ This method builds the metadata for full cudagraph capture. Currently, only decode is supported for full cudagraphs with Mamba. """ m = common_attn_metadata assert m.num_reqs == m.num_actual_tokens, ( "Mamba only supports decode-only full CUDAGraph capture. " "Make sure all cudagraph capture sizes <= max_num_seq." ) m.max_query_len = 1 # decode-only return self.build(0, m) def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> M: """ Default build implementation for Mamba-like attention backends. Subclasses (e.g., Mamba2) can override to add additional metadata. """ return self._compute_common_metadata(common_attn_metadata) def _compute_prefix_caching_block_indices( self, common_attn_metadata: CommonAttentionMetadata, mamba_block_size: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: num_computed_tokens = common_attn_metadata.num_computed_tokens_cpu.to( self.device ) # Block index of the last computed token block_idx_last_computed_token = cdiv(num_computed_tokens, mamba_block_size) - 1 # which is <= block index for the first scheduled token block_idx_first_scheduled_token = ( cdiv(num_computed_tokens + 1, mamba_block_size) - 1 ) # which is <= block index of the last scheduled token block_idx_last_scheduled_token = ( cdiv(common_attn_metadata.seq_lens, mamba_block_size) - 1 ) # -1 in case it's non-computed and causes later issues with indexing block_idx_last_computed_token = block_idx_last_computed_token.clamp(min=0) # -1 in the case we have a padded request (0 seq-len) block_idx_last_scheduled_token = block_idx_last_scheduled_token.clamp(min=0) return ( block_idx_last_computed_token, block_idx_first_scheduled_token, block_idx_last_scheduled_token, ) def _compute_common_metadata( self, common_attn_metadata: CommonAttentionMetadata, ) -> M: """ Compute metadata common to both Mamba1 and Mamba2. """ num_reqs = common_attn_metadata.num_reqs num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=self.reorder_batch_threshold ) ) # Need flags to indicate if there are initial states has_initial_states_p = None query_start_loc_p = None num_computed_tokens = None num_computed_tokens_p = None # for prefix caching block_idx_first_scheduled_token = None block_idx_first_scheduled_token_p = None block_idx_last_computed_token = None block_idx_last_scheduled_token = None # for causal_conv1d nums_dict, batch_ptr, token_chunk_offset_ptr = None, None, None if self.vllm_config.cache_config.enable_prefix_caching: # Return a tensor of shape (#requests, #max blocks) state_indices_tensor = common_attn_metadata.block_table_tensor # Additional cache-related varaiables: mamba_block_size = self.kv_cache_spec.block_size num_computed_tokens = common_attn_metadata.num_computed_tokens_cpu.to( self.device ) ( block_idx_last_computed_token, block_idx_first_scheduled_token, block_idx_last_scheduled_token, ) = self._compute_prefix_caching_block_indices( common_attn_metadata, mamba_block_size ) else: # Always return just a single block per each request: state_indices_tensor = common_attn_metadata.block_table_tensor[:, 0] if num_prefills > 0: query_start_loc_p = ( common_attn_metadata.query_start_loc[-num_prefills - 1 :] - num_decode_tokens ) has_initial_states_cpu = ( common_attn_metadata.num_computed_tokens_cpu[ num_reqs - num_prefills : num_reqs ] > 0 ) has_initial_states_p = has_initial_states_cpu.to( common_attn_metadata.query_start_loc.device ) nums_dict, batch_ptr, token_chunk_offset_ptr = ( compute_causal_conv1d_metadata(query_start_loc_p) ) if self.vllm_config.cache_config.enable_prefix_caching: assert num_computed_tokens is not None num_computed_tokens_p = num_computed_tokens[ num_reqs - num_prefills : num_reqs ] assert block_idx_first_scheduled_token is not None block_idx_first_scheduled_token_p = block_idx_first_scheduled_token[ num_reqs - num_prefills : num_reqs ] elif ( num_decodes <= self.decode_cudagraph_max_bs and self.compilation_config.cudagraph_mode.has_full_cudagraphs() ): self.state_indices_tensor[:num_decodes].copy_( state_indices_tensor, non_blocking=True ) state_indices_tensor = self.state_indices_tensor[:num_decode_tokens] state_indices_tensor[num_decodes:] = PAD_SLOT_ID if self.vllm_config.cache_config.enable_prefix_caching: self.block_idx_last_scheduled_token[:num_decodes].copy_( block_idx_last_scheduled_token, non_blocking=True ) block_idx_last_scheduled_token = self.block_idx_last_scheduled_token[ :num_decode_tokens ] self.block_idx_last_computed_token[:num_decodes].copy_( block_idx_last_computed_token, non_blocking=True ) block_idx_last_computed_token = self.block_idx_last_computed_token[ :num_decode_tokens ] return self.metadata_cls( num_prefills=num_prefills, num_prefill_tokens=num_prefill_tokens, num_decodes=num_decodes, num_decode_tokens=num_decode_tokens, query_start_loc_p=query_start_loc_p, has_initial_states_p=has_initial_states_p, state_indices_tensor=state_indices_tensor, block_idx_last_scheduled_token=block_idx_last_scheduled_token, block_idx_first_scheduled_token_p=block_idx_first_scheduled_token_p, block_idx_last_computed_token=block_idx_last_computed_token, num_computed_tokens_p=num_computed_tokens_p, num_reqs=num_reqs, nums_dict=nums_dict, batch_ptr=batch_ptr, token_chunk_offset_ptr=token_chunk_offset_ptr, ) def update_block_table( self, metadata: M, blk_table: torch.Tensor, slot_mapping: torch.Tensor, ) -> M: new_metadata = copy.copy(metadata) prefix_caching = self.vllm_config.cache_config.enable_prefix_caching state_indices_t = blk_table if prefix_caching else blk_table[:, 0] num_reqs = blk_table.shape[0] # For CUDA graphs, copy to persistent buffer if ( metadata.num_prefills == 0 and num_reqs <= self.decode_cudagraph_max_bs and self.compilation_config.cudagraph_mode.has_full_cudagraphs() ): persistent_state_indices_t = self.state_indices_tensor[:num_reqs] persistent_state_indices_t.copy_(state_indices_t, non_blocking=True) state_indices_t = persistent_state_indices_t new_metadata.state_indices_tensor = state_indices_t return new_metadata
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/indexer.py
vllm/v1/attention/backends/mla/indexer.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import ClassVar import torch from vllm.attention.backends.abstract import ( AttentionBackend, MultipleOf, ) from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.deep_gemm import get_paged_mqa_logits_metadata, is_deep_gemm_supported from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, split_decodes_and_prefills, split_prefill_chunks, ) logger = init_logger(__name__) class DeepseekV32IndexerBackend(AttentionBackend): @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [1 if current_platform.is_rocm() else 64] @classmethod def get_supported_head_sizes(cls) -> list[int]: return [32, 64, 128] @staticmethod def get_builder_cls() -> type["DeepseekV32IndexerMetadataBuilder"]: return DeepseekV32IndexerMetadataBuilder @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, ...]: assert num_kv_heads == 1 return (num_blocks, block_size, head_size) @staticmethod def get_kv_cache_stride_order( include_num_layers_dimension: bool = False, ) -> tuple[int, ...]: if include_num_layers_dimension: return (0, 1, 2, 3) return (0, 1, 2) @dataclass class DeepseekV32IndexerPrefillChunkMetadata: block_table: torch.Tensor cu_seqlen_ks: torch.Tensor cu_seqlen_ke: torch.Tensor cu_seq_lens: torch.Tensor total_seq_lens: int token_start: int token_end: int num_reqs: int @dataclass class DeepseekV32IndexerPrefillMetadata: chunks: list[DeepseekV32IndexerPrefillChunkMetadata] @dataclass class DeepSeekV32IndexerDecodeMetadata: block_table: torch.Tensor seq_lens: torch.Tensor decode_lens: torch.Tensor requires_padding: bool schedule_metadata: torch.Tensor @dataclass class DeepseekV32IndexerMetadata: # FIXME (zyongye) # hacky way to access the data now, need to be in chunked meta seq_lens: torch.Tensor num_reqs: int max_query_len: int max_seq_len: int num_actual_tokens: int # Number of tokens excluding padding. query_start_loc: torch.Tensor slot_mapping: torch.Tensor # The dimension of the attention heads head_dim: int # New for MLA (compared to FlashAttention) # For handling prefill decode split num_decodes: int num_decode_tokens: int num_prefills: int num_prefill_tokens: int decode: DeepSeekV32IndexerDecodeMetadata | None = None prefill: DeepseekV32IndexerPrefillMetadata | None = None # TODO (zyongye) optimize this, this is now vibe coded def kv_spans_from_batches( start_seq_loc: torch.Tensor, seq_len_per_batch: torch.Tensor, device: torch.device ) -> tuple[torch.Tensor, torch.Tensor]: """ Args: start_seq_loc: 1D long tensor [B+1], cumulative counts of selected tokens per batch. Example: [0, 2, 4, 7] -> batch sizes (selected) [2, 2, 3], N=7 tokens total. seq_len_per_batch: 1D long tensor [B], full sequence length (KV length) of each batch. Example: [5, 9, 4]. Returns: start_tensor: 1D long tensor [N], start offset in the concatenated KV cache for each token's batch. end_location: 1D long tensor [N], **exclusive** end = start + token's local position. (So the attended KV slice is kv[start:end].) Assumes each batch contributes its full `seq_len_per_batch[i]` keys to the KV cache, andthe selected tokens within a batch are the **last** `counts[i]` positions of that sequence. """ q = start_seq_loc.to(dtype=torch.long) L = seq_len_per_batch.to(dtype=torch.long) assert q.dim() == 1 and L.dim() == 1 assert q.numel() == L.numel() + 1, "start_seq_loc must have length B+1" # Selected tokens per batch and totals counts = q[1:] - q[:-1] # [B] N = int(q[-1].item()) # total selected tokens B = L.numel() if N == 0: return ( torch.empty(0, dtype=torch.long, device=device), torch.empty(0, dtype=torch.long, device=device), ) # KV start offsets per batch in the concatenated KV cache kv_starts_per_batch = torch.cumsum(L, dim=0) - L # [B] # For each selected token, which batch does it belong to? batch_id = torch.repeat_interleave(torch.arange(B), counts) # [N] # Map batch KV start to each token start_tensor = kv_starts_per_batch[batch_id] # [N] # End-align local positions inside each batch: # local_pos = L[b] - counts[b] + (1..counts[b]) for each batch b L_expand = torch.repeat_interleave(L, counts) # [N] m_expand = torch.repeat_interleave(counts, counts) # [N] # position within the selected block: 1..counts[b] pos_within = ( torch.arange(N, dtype=torch.long) - torch.repeat_interleave(q[:-1], counts) + 1 ) local_pos = L_expand - m_expand + pos_within # [N], 1-based end_location = start_tensor + local_pos # exclusive end return start_tensor.int().to(device), end_location.int().to(device) def get_max_prefill_buffer_size(vllm_config: VllmConfig): max_model_len = vllm_config.model_config.max_model_len # NOTE(Chen): 40 is a magic number for controlling the prefill buffer size. # Each entry is 128 fp8 bytes and 4 scale bytes for a total of 132 bytes. # The flashmla_sparse backend uses a workspace size of 5 * max_model_len. # The memory usage of the workspace there is 576 * 2 bytes; so we size this as # (576 * 2 // 132) * 5 = 40 to maximize this workspace size while still fitting # within the flashmla_sparse workspace. # For DeepSeek-V3.2, the max_model_len is 163840. # 40 * 163840 * 132 = 865075200 bytes = 825 MB return max_model_len * 40 class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder): _cudagraph_support: ClassVar[AttentionCGSupport] = ( AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE ) reorder_batch_threshold: int = 1 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) scheduler_config = self.vllm_config.scheduler_config # NOTE(Chen):an estimated max size of flattened_kv. Need to double check. self.max_prefill_buffer_size = get_max_prefill_buffer_size(self.vllm_config) self.num_speculative_tokens = ( self.vllm_config.speculative_config.num_speculative_tokens if self.vllm_config.speculative_config else 0 ) # Now deepgemm fp8_paged_mqa_logits does not support next_n > 2 self.reorder_batch_threshold += min(self.num_speculative_tokens, 1) props = torch.cuda.get_device_properties(self.device) sm_count = props.multi_processor_count self.num_sms = sm_count self.decode_lens_buffer = torch.empty( (scheduler_config.max_num_seqs,), dtype=torch.int32, device=self.device ) # See: DeepGMM/csrc/apis/attention.hpp self.scheduler_metadata_buffer = torch.empty( (self.num_sms + 1, 2), dtype=torch.int32, device=self.device ) def build_one_prefill_chunk( self, reqs_start, reqs_end, query_start_loc_cpu, seq_lens_cpu, block_table ): prefill_query_start_loc = ( query_start_loc_cpu[reqs_start : reqs_end + 1] - query_start_loc_cpu[reqs_start] ) cu_seqlen_ks, cu_seqlen_ke = kv_spans_from_batches( prefill_query_start_loc, seq_lens_cpu[reqs_start:reqs_end], self.device ) token_start = query_start_loc_cpu[reqs_start].item() token_end = query_start_loc_cpu[reqs_end].item() total_seq_lens = seq_lens_cpu[reqs_start:reqs_end].sum() assert total_seq_lens <= self.max_prefill_buffer_size cu_seq_lens = ( torch.cat( [ torch.zeros(1, dtype=torch.int32), seq_lens_cpu[reqs_start:reqs_end].cumsum(dim=0), ] ) .to(torch.int32) .to(self.device) ) return DeepseekV32IndexerPrefillChunkMetadata( cu_seqlen_ks=cu_seqlen_ks, cu_seqlen_ke=cu_seqlen_ke, cu_seq_lens=cu_seq_lens, total_seq_lens=total_seq_lens, block_table=block_table[reqs_start:reqs_end], token_start=token_start, token_end=token_end, num_reqs=reqs_end - reqs_start, ) def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> DeepseekV32IndexerMetadata: num_reqs = common_attn_metadata.num_reqs num_tokens = common_attn_metadata.num_actual_tokens query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=self.reorder_batch_threshold ) ) assert num_decodes + num_prefills == num_reqs assert num_decode_tokens + num_prefill_tokens == num_tokens prefill_metadata = None if num_prefills > 0: chunk_seq_ids = split_prefill_chunks( common_attn_metadata.seq_lens_cpu[num_decodes:], self.max_prefill_buffer_size, request_offset=num_decodes, ) chunks = [ self.build_one_prefill_chunk( reqs_start, reqs_end, query_start_loc_cpu, common_attn_metadata.seq_lens_cpu, common_attn_metadata.block_table_tensor, ) for reqs_start, reqs_end in chunk_seq_ids ] prefill_metadata = DeepseekV32IndexerPrefillMetadata( chunks=chunks, ) decode_metadata = None if num_decodes > 0: torch.diff( common_attn_metadata.query_start_loc[: num_decodes + 1], out=self.decode_lens_buffer[:num_decodes], ) decode_lens = self.decode_lens_buffer[:num_decodes] decode_lens_cpu = torch.diff( common_attn_metadata.query_start_loc_cpu[: num_decodes + 1] ) # Use CPU to avoid GPU sync; breaking async scheduling requires_padding = (decode_lens_cpu.max() > decode_lens_cpu.min()).item() seq_lens = common_attn_metadata.seq_lens[:num_decodes] if is_deep_gemm_supported(): self.scheduler_metadata_buffer[:] = get_paged_mqa_logits_metadata( seq_lens, self.kv_cache_spec.block_size, self.num_sms ) decode_metadata = DeepSeekV32IndexerDecodeMetadata( block_table=common_attn_metadata.block_table_tensor[:num_decodes, ...], seq_lens=common_attn_metadata.seq_lens[:num_decodes], decode_lens=decode_lens, requires_padding=requires_padding, schedule_metadata=self.scheduler_metadata_buffer, ) attn_metadata = DeepseekV32IndexerMetadata( seq_lens=common_attn_metadata.seq_lens, num_reqs=common_attn_metadata.num_reqs, max_query_len=common_attn_metadata.max_query_len, max_seq_len=common_attn_metadata.max_seq_len, num_actual_tokens=common_attn_metadata.num_actual_tokens, query_start_loc=common_attn_metadata.query_start_loc, slot_mapping=common_attn_metadata.slot_mapping, head_dim=128, num_decodes=num_decodes, num_decode_tokens=num_decode_tokens, num_prefills=num_prefills, num_prefill_tokens=num_prefill_tokens, prefill=prefill_metadata, decode=decode_metadata, ) # if get_tensor_model_parallel_rank() == 0: # logger.info(f"attn_metadata: {attn_metadata}") return attn_metadata
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/flashmla_sparse.py
vllm/v1/attention/backends/mla/flashmla_sparse.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import TYPE_CHECKING, ClassVar, Optional import numpy as np import torch from vllm import _custom_ops as ops from vllm.attention.backends.abstract import ( AttentionBackend, AttentionLayer, MultipleOf, ) from vllm.attention.backends.utils import get_mla_dims from vllm.attention.ops.flashmla import ( flash_mla_sparse_prefill, flash_mla_with_kvcache, get_mla_metadata, ) from vllm.config import VllmConfig, get_current_vllm_config from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.platforms.interface import DeviceCapability from vllm.triton_utils import tl, triton from vllm.utils.math_utils import cdiv from vllm.v1.attention.backends.mla.common import MLACommonBaseImpl from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, reshape_attn_output_for_spec_decode, reshape_query_for_spec_decode, split_decodes_and_prefills, split_prefill_chunks, ) from vllm.v1.kv_cache_interface import AttentionSpec from vllm.v1.worker.workspace import current_workspace_manager if TYPE_CHECKING: from vllm.model_executor.models.deepseek_v2 import Indexer logger = init_logger(__name__) # For FP8 sparse attention we have two impelementations: # 1. Mixed batch mode: use the FP8 decode kernel for both prefill and decode this is # done by treating all tokens as single batch. # 2. Separate prefill and decode mode: use the BF16 prefill kernel for prefill # (upconverting the FP8 cache to BF16 then calling the prefill kernel) and using # the FP8 decode kernel for decode. # Currently we use #1 when the number of heads per rank is low (i.e. TP) since the BF16 # prefill kernel requires padding the numer of heads to 128 while the decode does not # so when the per ranke head count is below MIN_HEADS_FOR_BF16_PREFILL we use the mixed # batch mode (#2). MIN_HEADS_FOR_BF16_PREFILL = 32 """ NOTE: FlashMLA Sparse uses an fp8 cache with the following format In the "FP8 with scale" format, each token's KV cache is 656 Bytes, structured as: - **First 512 bytes:** The "quantized NoPE" part, containing 512 `float8_e4m3` values. - **Next 16 bytes:** Scale factors, containing 4 `float32` values. The first `float32` is the scale for the first 128 `float8_e4m3` values, the second for the next 128, and so on. - **Last 128 bytes:** The "RoPE" part, containing 64 `bfloat16` values. This part is not quantized for accuracy. """ class FlashMLASparseBackend(AttentionBackend): accept_output_buffer: bool = True supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "fp8_ds_mla"] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [64] @staticmethod def get_name() -> str: return "FLASHMLA_SPARSE" @staticmethod def get_builder_cls() -> type["FlashMLASparseMetadataBuilder"]: return FlashMLASparseMetadataBuilder @staticmethod def get_impl_cls() -> type["FlashMLASparseImpl"]: return FlashMLASparseImpl @classmethod def get_supported_head_sizes(cls) -> list[int]: return [576] @classmethod def is_mla(cls) -> bool: return True @classmethod def is_sparse(cls) -> bool: return True @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return capability.major in [9, 10] @staticmethod def get_kv_cache_shape( num_blocks: int, block_size: int, num_kv_heads: int, # assumed to be 1 for MLA head_size: int, cache_dtype_str: str = "auto", ) -> tuple[int, ...]: if cache_dtype_str == "fp8_ds_mla": # custom storage fromat is 656 bytes # see FlashMLA readme.md for details return (num_blocks, block_size, 656) else: return (num_blocks, block_size, head_size) @dataclass class FlashMLASparseMetadata: num_reqs: int max_query_len: int max_seq_len: int num_actual_tokens: int # Number of tokens excluding padding. query_start_loc: torch.Tensor slot_mapping: torch.Tensor block_table: torch.Tensor req_id_per_token: torch.Tensor block_size: int = 64 topk_tokens: int = 2048 @dataclass class FP8KernelMetadata: scheduler_metadata: torch.Tensor | None num_splits: torch.Tensor dummy_block_table: torch.Tensor cache_lens: torch.Tensor @dataclass class FP8SeperatePrefillDecode: @dataclass class Decode: kernel_metadata: "FlashMLASparseMetadata.FP8KernelMetadata" decode_query_len: int # needed for reshape in spec decode @dataclass class Prefill: # Sequence lengths (context + query) for prefill requests # Shape: [num_prefill_reqs] seq_lens: torch.Tensor # Request ID for each token: -1 for decode tokens, request index # (0, 1, 2, ...) for prefill tokens. # Shape: [num_actual_tokens] request_ids: torch.Tensor # Workspace start offsets for all prefill requests # Shape: [num_prefill_reqs], adjusted in-place per chunk to be # 0-indexed within each chunk. Used to map prefill tokens to workspace # offsets in convert_logical_index_to_physical_index workspace_starts: torch.Tensor @dataclass class Chunk: """Metadata for a chunk of prefill requests. Prefill requests may be chunked to fit within the fixed workspace size. """ seq_lens: torch.Tensor tokens_slice: slice block_table: torch.Tensor req_start_idx: int workspace_starts: torch.Tensor chunk_tot_seqlen: int chunks: list[Chunk] num_prefills: int = 0 num_decodes: int = 0 num_prefill_tokens: int = 0 num_decode_tokens: int = 0 decode: Decode | None = None prefill: Prefill | None = None fp8_extra_metadata: FP8SeperatePrefillDecode | FP8KernelMetadata | None = None fp8_use_mixed_batch: bool = False # Kernel with prefill workspace support @triton.jit def _convert_req_index_to_global_index_kernel( req_id_ptr, # int32 [num_tokens] block_table_ptr, # int32 [num_requests, max_num_blocks_per_req] token_indices_ptr, # int32 [num_tokens, NUM_TOPK_TOKENS] out_ptr, # int32 [num_tokens, NUM_TOPK_TOKENS] prefill_request_id_ptr, # int32 [num_tokens], -1 for decode, >=0 for prefill workspace_starts_ptr, # int32 [num_prefill_reqs+1] or nullptr # shapes (compile-time where possible) max_num_blocks_per_req: tl.constexpr, BLOCK_SIZE: tl.constexpr, BLOCK_N: tl.constexpr, # tile width along columns HAS_PREFILL: tl.constexpr, # strides (in elements) bt_stride0, bt_stride1, ti_stride0, ti_stride1, out_stride0, out_stride1, ): # program_id(0) -> token_id (row) # program_id(1) -> tile index along columns token_id = tl.program_id(0) tile_id = tl.program_id(1) # Each program covers BLOCK_N consecutive columns indice_id = tile_id * BLOCK_N + tl.arange(0, BLOCK_N) # Load request id for this token (no mask: grid is exact) req = tl.load(req_id_ptr + token_id) # Load token indices for this tile ti_ptr = token_indices_ptr + token_id * ti_stride0 + indice_id * ti_stride1 tok = tl.load(ti_ptr) # int32 # Only token == -1 should propagate as -1 is_invalid_tok = tok < 0 is_prefill = False if HAS_PREFILL: prefill_req_id = tl.load(prefill_request_id_ptr + token_id) is_prefill = prefill_req_id >= 0 # Compute block id and in-block offset block_id = tok // BLOCK_SIZE inblock_off = tok % BLOCK_SIZE # Guard block_table access valid_block = (block_id < max_num_blocks_per_req) & (block_id >= 0) bt_ptr = block_table_ptr + req * bt_stride0 + block_id * bt_stride1 is_invalid_tok |= ~valid_block base = tl.load(bt_ptr, mask=valid_block & ~is_prefill, other=0) out_val = base * BLOCK_SIZE + inblock_off # Override with prefill output if prefill is enabled if HAS_PREFILL: workspace_start = tl.load( workspace_starts_ptr + prefill_req_id, mask=is_prefill, other=0 ) prefill_out = workspace_start + tok out_val = tl.where(is_prefill, prefill_out, out_val) out_val = tl.where(is_invalid_tok, -1, out_val) # Store results out_ptr_ij = out_ptr + token_id * out_stride0 + indice_id * out_stride1 tl.store(out_ptr_ij, out_val) def triton_convert_req_index_to_global_index( req_id: torch.Tensor, # int32 [num_tokens] block_table: torch.Tensor, # int32 [num_requests, max_num_blocks_per_req] token_indices: torch.Tensor, # int32 [num_tokens, NUM_TOPK_TOKENS] BLOCK_SIZE: int = 64, NUM_TOPK_TOKENS: int = 2048, BLOCK_N: int = 128, # tile width along columns HAS_PREFILL_WORKSPACE: bool = False, prefill_workspace_request_ids: torch.Tensor | None = None, prefill_workspace_starts: torch.Tensor | None = None, ): """ out[token_id, indice_id] = block_table[req_id[token_id], token_indices[token_id, indice_id] // BLOCK_SIZE] * BLOCK_SIZE + token_indices[token_id, indice_id] % BLOCK_SIZE Only when token_indices[token_id, indice_id] == -1 do we output -1. For safety, we also output -1 if the derived block_id would be out-of-bounds. When HAS_PREFILL_WORKSPACE is True, prefill tokens are mapped to workspace offsets instead of global cache slots. prefill_workspace_request_ids and prefill_workspace_starts must be provided. prefill_workspace_request_ids: int32 [num_tokens], -1 for decode else prefill request index (maps to prefill_workspace_starts) prefill_workspace_starts: int32 [num_prefills], 0-indexed workspace starts for each prefill request """ assert req_id.dtype == torch.int32 assert block_table.dtype == torch.int32 assert token_indices.dtype == torch.int32 assert token_indices.shape[1] == NUM_TOPK_TOKENS assert NUM_TOPK_TOKENS % BLOCK_N == 0, ( f"NUM_TOPK_TOKENS ({NUM_TOPK_TOKENS}) must be divisible by BLOCK_N ({BLOCK_N})" ) if HAS_PREFILL_WORKSPACE: assert prefill_workspace_request_ids is not None assert prefill_workspace_starts is not None assert prefill_workspace_request_ids.dtype == torch.int32 assert prefill_workspace_starts.dtype == torch.int32 num_tokens = req_id.shape[0] max_num_blocks_per_req = block_table.shape[1] tiles_per_row = NUM_TOPK_TOKENS // BLOCK_N # Ensure contiguous tensors on the same device req_id_c = req_id.contiguous() block_table_c = block_table.contiguous() token_indices_c = token_indices.contiguous() out = torch.empty_like(token_indices_c) # Strides in elements bt_stride0, bt_stride1 = block_table_c.stride() ti_stride0, ti_stride1 = token_indices_c.stride() out_stride0, out_stride1 = out.stride() # Prepare prefill pointers if HAS_PREFILL_WORKSPACE: assert prefill_workspace_request_ids is not None # for mypy assert prefill_workspace_starts is not None # for mypy assert prefill_workspace_request_ids.is_contiguous() assert prefill_workspace_starts.is_contiguous() # Exact 2D grid: tokens × column tiles grid = (num_tokens, tiles_per_row) _convert_req_index_to_global_index_kernel[grid]( req_id_c, block_table_c, token_indices_c, out, prefill_workspace_request_ids, prefill_workspace_starts, # shapes / constexprs max_num_blocks_per_req, BLOCK_SIZE, BLOCK_N, HAS_PREFILL_WORKSPACE, # strides bt_stride0, bt_stride1, ti_stride0, ti_stride1, out_stride0, out_stride1, ) return out def get_prefill_workspace_size(max_model_len: int): # NOTE(Lucas): 5 is a magic number for controlling the prefill buffer size. # May be tuned later. # Memory usage: 5 * max_model_len * 576 * 2 bytes # Example: DeepSeek-V3.2 with max_model_len=163840 -> # 5 * 163840 * 576 * 2 = ~900 MB # This fits nicely below the typical MoE workspace size of >2GB so this is "free" return max_model_len * 5 class FlashMLASparseMetadataBuilder(AttentionMetadataBuilder[FlashMLASparseMetadata]): _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ) -> None: self.vllm_config = vllm_config self.layer_names = layer_names cache_config = vllm_config.cache_config self.kv_cache_spec = kv_cache_spec self.model_config = vllm_config.model_config parallel_config = vllm_config.parallel_config self.device = device # Treat requests with query length <= 1 as decodes to match the # DeepGEMM indexer constraint (fp8_paged_mqa_logits only supports next_n <= 2) self._init_reorder_batch_threshold(1, supports_spec_as_decode=True) props = torch.cuda.get_device_properties(device) sm_count = props.multi_processor_count self.num_heads = self.model_config.get_num_attention_heads(parallel_config) self.mla_dims = get_mla_dims(self.model_config) self.topk_tokens = vllm_config.model_config.hf_config.index_topk self.use_fp8_kv_cache = cache_config.cache_dtype == "fp8_ds_mla" max_num_seqs = vllm_config.scheduler_config.max_num_seqs # Shape: [max_num_seqs], all elements = topk_tokens (constant for full-CG) self.topk_tokens_tensor = torch.full( (max_num_seqs,), self.topk_tokens, device=device, dtype=torch.int32 ) # Shape: [max_num_seqs], all elements = max_model_len self.max_model_len_tensor = torch.full( (max_num_seqs,), self.model_config.max_model_len, device=device, dtype=torch.int32, ) # this is ignored by `flash_mla_with_kvcache` if indices not None self.dummy_block_table = torch.empty( (max_num_seqs, 1), dtype=torch.int32, device=self.device ) # Equation taken from FlashMLA/csrc/pybind.cpp h_q, h_k = self.num_heads, 1 s_q = 1 # inversely proportional to s_q, so s_q = 1 is the largest max_num_sm_parts = int( max((sm_count // 2) / h_k // (cdiv(h_q // h_k, 2 * 64) * s_q), 1) ) if current_platform.is_device_capability_family(100): max_num_sm_parts *= 2 self.tile_scheduler_metadata_buffer = torch.empty( # TileSchedulerMetaDataSize = 8 # see: FlashMLA/csrc/params.h (max_num_sm_parts, 8), dtype=torch.int32, device=device, ) # Sized for per-request batching (num_decodes + 1) self.num_splits_buffer = torch.empty( (max_num_seqs + 1,), dtype=torch.int32, device=device, ) self.req_id_per_token_buffer = torch.empty( (vllm_config.scheduler_config.max_num_batched_tokens,), dtype=torch.int32, device=device, ) def _build_fp8_mixed_decode_prefill( self, common_attn_metadata: CommonAttentionMetadata, ) -> "FlashMLASparseMetadata.FP8KernelMetadata": """Build FP8 metadata treating all tokens as one mixed batch. This matches main branch's approach and avoids the BF16 prefill kernel which has head padding overhead when num_heads is small (high TP case). """ num_tokens = common_attn_metadata.num_actual_tokens # Build metadata for all tokens as a single batch tile_scheduler_metadata, num_splits = get_mla_metadata( cache_seqlens=self.topk_tokens_tensor[:1], # Single batch num_q_tokens_per_head_k=num_tokens * self.num_heads, topk=self.topk_tokens, num_heads_q=self.num_heads, num_heads_k=1, is_fp8_kvcache=True, ) num_sm_parts = tile_scheduler_metadata.size(0) tile_scheduler_metadata_buffer = self.tile_scheduler_metadata_buffer[ :num_sm_parts ] tile_scheduler_metadata_buffer.copy_(tile_scheduler_metadata) num_splits_view = self.num_splits_buffer[:2] num_splits_view.copy_(num_splits) fp8_metadata = FlashMLASparseMetadata.FP8KernelMetadata( scheduler_metadata=tile_scheduler_metadata_buffer, num_splits=num_splits_view, cache_lens=self.max_model_len_tensor[:1], dummy_block_table=self.dummy_block_table[:1], ) return fp8_metadata def _build_fp8_separate_prefill_decode( self, common_attn_metadata: CommonAttentionMetadata, ) -> "FlashMLASparseMetadata.FP8SeperatePrefillDecode": num_tokens = common_attn_metadata.num_actual_tokens (num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens) = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=self.reorder_batch_threshold or 1, require_uniform=True, ) ) FP8Meta = FlashMLASparseMetadata.FP8SeperatePrefillDecode fp8_metadata = FP8Meta( num_decodes=num_decodes, num_prefills=num_prefills, num_decode_tokens=num_decode_tokens, num_prefill_tokens=num_prefill_tokens, ) # Extract prefill sequence lengths (context + query, not just query) # Decode requests come first in the batch, prefill requests follow prefill_seq_lens = None prefill_request_id = None prefill_workspace_starts = None prefill_chunks = None # For pure decode batches, prefill_request_id will be None # For mixed batches, it will have -1 for decode and request_id for prefill if num_prefills > 0: seq_lens_cpu = common_attn_metadata.seq_lens_cpu seq_lens = common_attn_metadata.seq_lens query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu prefill_seq_lens_cpu = seq_lens_cpu[num_decodes:] prefill_seq_lens = seq_lens[num_decodes:] # Build prefill_request_id: -1 for decode, request index for # prefill. This enables a single # convert_logical_index_to_physical_index call for all tokens prefill_request_id = torch.full( (num_tokens,), -1, dtype=torch.int32, device=self.device ) # Map prefill tokens to their request IDs (0, 1, 2, ...) for req_idx in range(num_prefills): # Get query token range for this prefill request global_req_idx = num_decodes + req_idx req_query_start = query_start_loc_cpu[global_req_idx] req_query_end = query_start_loc_cpu[global_req_idx + 1] prefill_request_id[req_query_start:req_query_end] = req_idx # will be adjusted by chunk loop prefill_workspace_starts_cpu = torch.zeros( num_prefills, dtype=torch.int32, pin_memory=True ) prefill_workspace_starts_cpu[1:] = torch.cumsum( prefill_seq_lens_cpu[:-1], dim=0 ) # populated by non-blocking copy after prefill_workspace_starts_cpu is # updated by each chunk prefill_workspace_starts = torch.empty( num_prefills, dtype=torch.int32, device=self.device ) # Chunk prefill requests to fit within workspace size max_prefill_buffer_size = get_prefill_workspace_size( self.vllm_config.model_config.max_model_len ) chunk_bounds = split_prefill_chunks( prefill_seq_lens_cpu, max_prefill_buffer_size ) prefill_chunks = [] for chunk_start, chunk_end in chunk_bounds: # Adjust workspace_starts in-place per chunk to be # 0-indexed within each chunk # Example: seq_lens=[10,15,20,5], chunks=[[0,2],[2,4]] # Initial: workspace_starts=[0,10,25,45] # After: workspace_starts=[0,10,0,20] # (chunk 0 starts at 0, chunk 1 starts at 0) offset = prefill_workspace_starts_cpu[chunk_start].item() prefill_workspace_starts_cpu[chunk_start:chunk_end] -= offset chunk_seq_lens = prefill_seq_lens[chunk_start:chunk_end] chunk_tot_seqlen = prefill_seq_lens_cpu[chunk_start:chunk_end].sum() token_start = query_start_loc_cpu[num_decodes + chunk_start].item() token_end = query_start_loc_cpu[num_decodes + chunk_end].item() tokens_slice = slice(token_start, token_end) # Create chunk view of gpu tensor chunk_workspace_starts = prefill_workspace_starts[chunk_start:chunk_end] chunk_block_table = common_attn_metadata.block_table_tensor[ num_decodes + chunk_start : num_decodes + chunk_end ] prefill_chunks.append( FP8Meta.Prefill.Chunk( seq_lens=chunk_seq_lens, tokens_slice=tokens_slice, block_table=chunk_block_table, req_start_idx=chunk_start, workspace_starts=chunk_workspace_starts, chunk_tot_seqlen=chunk_tot_seqlen, ) ) prefill_workspace_starts.copy_( prefill_workspace_starts_cpu, non_blocking=True ) fp8_metadata.prefill = FP8Meta.Prefill( seq_lens=prefill_seq_lens, request_ids=prefill_request_id, workspace_starts=prefill_workspace_starts, chunks=prefill_chunks, ) if num_decodes > 0: # Compute decode_query_len for spec decode (uniform due to require_uniform) query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu decode_query_len = (query_start_loc_cpu[1] - query_start_loc_cpu[0]).item() tile_scheduler_metadata, num_splits = get_mla_metadata( cache_seqlens=self.topk_tokens_tensor[:num_decodes], num_q_tokens_per_head_k=decode_query_len * self.num_heads, topk=self.topk_tokens, num_heads_q=self.num_heads, num_heads_k=1, is_fp8_kvcache=True, ) num_sm_parts = tile_scheduler_metadata.size(0) # Copy to persistent buffer for full-CG support tile_scheduler_metadata_buffer = self.tile_scheduler_metadata_buffer[ :num_sm_parts ] tile_scheduler_metadata_buffer.copy_(tile_scheduler_metadata) # num_splits has size [num_decodes + 1] num_splits_view = self.num_splits_buffer[: num_decodes + 1] num_splits_view.copy_(num_splits) kernel_meta = FlashMLASparseMetadata.FP8KernelMetadata( scheduler_metadata=tile_scheduler_metadata_buffer, num_splits=num_splits_view, dummy_block_table=self.dummy_block_table[:num_decodes], cache_lens=self.max_model_len_tensor[:num_decodes], ) fp8_metadata.decode = FP8Meta.Decode( kernel_metadata=kernel_meta, decode_query_len=decode_query_len, ) return fp8_metadata def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> FlashMLASparseMetadata: cm = common_attn_metadata num_tokens = cm.num_actual_tokens starts = np.asarray(cm.query_start_loc_cpu, dtype=np.int32) seg_lengths = np.diff(starts) req_id_per_token = np.repeat( np.arange(seg_lengths.shape[0], dtype=np.int32), seg_lengths ) # Zero-fill for cudagraphs self.req_id_per_token_buffer.fill_(0) self.req_id_per_token_buffer[: req_id_per_token.shape[0]].copy_( torch.from_numpy(req_id_per_token), non_blocking=True ) req_id_per_token = self.req_id_per_token_buffer[:num_tokens] fp8_extra_metadata: ( FlashMLASparseMetadata.FP8SeperatePrefillDecode | FlashMLASparseMetadata.FP8KernelMetadata | None ) = None fp8_use_mixed_batch = self.num_heads < MIN_HEADS_FOR_BF16_PREFILL if self.use_fp8_kv_cache: if fp8_use_mixed_batch: fp8_extra_metadata = self._build_fp8_mixed_decode_prefill(cm) else: fp8_extra_metadata = self._build_fp8_separate_prefill_decode(cm) metadata = FlashMLASparseMetadata( num_reqs=cm.num_reqs, max_query_len=cm.max_query_len, max_seq_len=cm.max_seq_len, num_actual_tokens=cm.num_actual_tokens, query_start_loc=cm.query_start_loc, slot_mapping=cm.slot_mapping, block_table=cm.block_table_tensor, req_id_per_token=req_id_per_token, block_size=self.kv_cache_spec.block_size, topk_tokens=self.topk_tokens, fp8_extra_metadata=fp8_extra_metadata, fp8_use_mixed_batch=fp8_use_mixed_batch, ) return metadata class FlashMLASparseImpl(MLACommonBaseImpl[FlashMLASparseMetadata]): 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments topk_indice_buffer: torch.Tensor | None = None, indexer: Optional["Indexer"] = None, **mla_args, ) -> 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, **mla_args, ) self.softmax_scale = scale assert indexer is not None self.topk_indices_buffer = indexer.topk_indices_buffer self.padding = 128 if current_platform.is_device_capability_family(100) else 64 if kv_cache_dtype == "fp8_ds_mla": # Reserve workspace during initialization vllm_config = get_current_vllm_config() assert vllm_config is not None and vllm_config.model_config is not None prefill_workspace_size = get_prefill_workspace_size( vllm_config.model_config.max_model_len ) self.prefill_workspace_shape = (prefill_workspace_size, head_size) (self.prefill_bf16_workspace,) = ( current_workspace_manager().get_simultaneous( (self.prefill_workspace_shape, torch.bfloat16) ) ) def _forward_bf16_kv( self, q: torch.Tensor, kv_c_and_k_pe_cache: torch.Tensor, topk_indices: torch.Tensor, attn_metadata: FlashMLASparseMetadata, ) -> torch.Tensor: # Convert per-request indices to global slots (decode) or workspace # offsets (prefill). topk_indices = triton_convert_req_index_to_global_index( attn_metadata.req_id_per_token, attn_metadata.block_table, topk_indices, BLOCK_SIZE=attn_metadata.block_size, NUM_TOPK_TOKENS=topk_indices.shape[1], ) return self._bf16_flash_mla_kernel(q, kv_c_and_k_pe_cache, topk_indices) def _forward_fp8_kv_separate_prefill_decode( self, q: torch.Tensor, kv_c_and_k_pe_cache: torch.Tensor, topk_indices: torch.Tensor, attn_metadata: FlashMLASparseMetadata, ) -> torch.Tensor: fp8_metadata = attn_metadata.fp8_extra_metadata assert isinstance(fp8_metadata, FlashMLASparseMetadata.FP8SeperatePrefillDecode) num_decodes = fp8_metadata.num_decodes prefill_request_ids = None prefill_workspace_starts = None has_prefill_workspace = False if fp8_metadata.prefill is not None: prefill_request_ids = fp8_metadata.prefill.request_ids prefill_workspace_starts = fp8_metadata.prefill.workspace_starts has_prefill_workspace = True # Convert per-request indices to global slots (decode) or workspace # offsets (prefill). # For FP8 cache: prefill uses workspace mapping (upconverted to BF16) # For BF16 cache: always use global cache slots (no workspace) # prefill_workspace_starts has been adjusted in-place per chunk so # prefill indices automatically come out chunk-local topk_indices = triton_convert_req_index_to_global_index( attn_metadata.req_id_per_token, attn_metadata.block_table, topk_indices, BLOCK_SIZE=attn_metadata.block_size, NUM_TOPK_TOKENS=topk_indices.shape[1], HAS_PREFILL_WORKSPACE=has_prefill_workspace, prefill_workspace_request_ids=prefill_request_ids, prefill_workspace_starts=prefill_workspace_starts, ) fp8_metadata = attn_metadata.fp8_extra_metadata assert isinstance(fp8_metadata, FlashMLASparseMetadata.FP8SeperatePrefillDecode) def _fp8_decode(q: torch.Tensor, topk_indices: torch.Tensor) -> torch.Tensor: # Reshape q: (num_decode_tokens, num_heads, head_dim) # -> (num_decodes, seq_len, num_heads, head_dim) q = reshape_query_for_spec_decode(q, num_decodes) seq_len = q.shape[1] # Reshape topk_indices: (num_decode_tokens, topk) # -> (num_decodes, seq_len, topk) topk_indices = topk_indices.view(num_decodes, seq_len, -1) assert fp8_metadata.decode is not None attn_out, _ = self._fp8_flash_mla_kernel( q=q, kv_c_and_k_pe_cache=kv_c_and_k_pe_cache, topk_indices=topk_indices, kernel_metadata=fp8_metadata.decode.kernel_metadata, ) # Reshape output: (num_decodes, seq_len, num_heads, head_dim_v) # -> (num_decode_tokens, num_heads, head_dim_v) return reshape_attn_output_for_spec_decode(attn_out) num_decode_tokens = fp8_metadata.num_decode_tokens num_prefill_tokens = fp8_metadata.num_prefill_tokens # Pure decode: direct call without allocation if num_decode_tokens > 0 and num_prefill_tokens == 0: assert fp8_metadata.decode is not None attn_out = _fp8_decode(q, topk_indices) else: # Mixed or pure prefill: allocate output tensor attn_out = q.new_empty( (attn_metadata.num_actual_tokens, self.num_heads, self.kv_lora_rank), dtype=q.dtype, device=q.device, ) if num_decode_tokens > 0: attn_out[:num_decode_tokens] = _fp8_decode( q[:num_decode_tokens], topk_indices[:num_decode_tokens] ) assert fp8_metadata.prefill is not None for chunk in fp8_metadata.prefill.chunks: chunk_workspace = self.prefill_bf16_workspace[: chunk.chunk_tot_seqlen] ops.cp_gather_and_upconvert_fp8_kv_cache(
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/aiter_triton_mla.py
vllm/v1/attention/backends/mla/aiter_triton_mla.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.v1.attention.backends.mla.common import MLACommonBackend from vllm.v1.attention.backends.mla.rocm_aiter_mla import ( AiterMLAImpl, AiterMLAMetadataBuilder, ) class AiterTritonMLABackend(MLACommonBackend): @staticmethod def get_name() -> str: return "AITER_TRITON_MLA" @staticmethod def get_impl_cls() -> type["AiterTritonMLAImpl"]: return AiterTritonMLAImpl @staticmethod def get_builder_cls() -> type["AiterMLAMetadataBuilder"]: return AiterMLAMetadataBuilder class AiterTritonMLAImpl(AiterMLAImpl): 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments **mla_args, ) -> 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, **mla_args, ) from aiter.ops.triton.mha import flash_attn_varlen_func self.flash_attn_varlen_func = flash_attn_varlen_func def _flash_attn_varlen_diff_headdims( self, q, k, v, return_softmax_lse=False, softmax_scale=None, **kwargs ): result = self.flash_attn_varlen_func( q, k, v, softmax_scale=softmax_scale, return_lse=return_softmax_lse, **kwargs, ) # Transpose the LSE if Triton MHA is used: # (q.shape[0], num_q_heads) to (num_q_heads, q.shape[0]) if type(result) is tuple and return_softmax_lse: output, lse = result lse = lse.T.contiguous() return (output, lse) return result
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/flashmla.py
vllm/v1/attention/backends/mla/flashmla.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import ClassVar import torch from vllm.attention.backends.abstract import AttentionLayer, AttentionType, MultipleOf from vllm.attention.ops.flashmla import ( flash_mla_with_kvcache, get_mla_metadata, is_flashmla_dense_supported, ) from vllm.config import VllmConfig from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.platforms.interface import DeviceCapability from vllm.v1.attention.backends.mla.common import ( MLACommonBackend, MLACommonDecodeMetadata, MLACommonImpl, MLACommonMetadata, MLACommonMetadataBuilder, QueryLenSupport, ) from vllm.v1.attention.backends.utils import ( AttentionCGSupport, reshape_attn_output_for_spec_decode, reshape_query_for_spec_decode, ) from vllm.v1.kv_cache_interface import AttentionSpec logger = init_logger(__name__) class FlashMLABackend(MLACommonBackend): supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ "auto", "fp8", "fp8_e4m3", ] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [64] @staticmethod def get_name() -> str: return "FLASHMLA" @staticmethod def get_builder_cls() -> type["FlashMLAMetadataBuilder"]: return FlashMLAMetadataBuilder @staticmethod def get_impl_cls() -> type["FlashMLAImpl"]: return FlashMLAImpl @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return capability.major in [9, 10] @classmethod def supports_combination( cls, head_size: int, dtype: torch.dtype, kv_cache_dtype: CacheDType | None, block_size: int, use_mla: bool, has_sink: bool, use_sparse: bool, device_capability: DeviceCapability, ) -> str | None: if use_sparse: from vllm.attention.ops.flashmla import is_flashmla_sparse_supported return is_flashmla_sparse_supported()[1] else: from vllm.attention.ops.flashmla import is_flashmla_dense_supported return is_flashmla_dense_supported()[1] @dataclass class FlashMLADecodeMetadata(MLACommonDecodeMetadata): tile_scheduler_metadata: torch.Tensor num_splits: torch.Tensor @dataclass class FlashMLAMetadata(MLACommonMetadata[FlashMLADecodeMetadata]): pass class FlashMLAMetadataBuilder(MLACommonMetadataBuilder[FlashMLAMetadata]): _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.UNIFORM reorder_batch_threshold: int = 128 # process small prefills with decode pathway # ^ TODO(matt): tune this def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__( kv_cache_spec, layer_names, vllm_config, device, FlashMLAMetadata ) self.num_q_heads = vllm_config.model_config.get_num_attention_heads( vllm_config.parallel_config ) self.cg_buf_tile_scheduler_metadata = None self.cg_buf_num_splits = None self.is_fp8_kvcache = vllm_config.cache_config.cache_dtype.startswith("fp8") device_properties = torch.cuda.get_device_properties(self.device) num_sms = device_properties.multi_processor_count if self.compilation_config.cudagraph_mode.has_full_cudagraphs(): self.cg_buf_tile_scheduler_metadata = torch.zeros( # Upper bound on size (<= #SMs, TileSchedulerMetaDataSize) # TileSchedulerMetaDataSize = 8 (num_sms, 8), device=self.device, dtype=torch.int32, ) self.cg_buf_num_splits = torch.empty( (vllm_config.scheduler_config.max_num_seqs + 1), device=self.device, dtype=torch.int32, ) def _build_decode( self, block_table_tensor: torch.Tensor, seq_lens_device: torch.Tensor, max_seq_len: int, query_start_loc_cpu: torch.Tensor, query_start_loc_device: torch.Tensor, num_decode_tokens: int, dcp_tot_seq_lens_device: torch.Tensor | None, ) -> FlashMLADecodeMetadata: query_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1] # we use the max but all should be the same due to uniform length requirement max_query_len = query_lens_cpu.max().item() num_q_tokens_per_head_k = max_query_len * self.num_q_heads // 1 tile_scheduler_metadata, num_splits = get_mla_metadata( seq_lens_device, num_q_tokens_per_head_k, 1, # MQA for the decode path is_fp8_kvcache=self.is_fp8_kvcache, ) # TODO: we can disambiguate between decode and mixed-prefill decode here # so we can only use the persistent buffer if a cudagraph is actually # being used. if self.compilation_config.cudagraph_mode.has_full_cudagraphs(): assert self.cg_buf_tile_scheduler_metadata is not None assert self.cg_buf_num_splits is not None sm_parts = tile_scheduler_metadata.size(0) # Metadata per-SM, upper bound on size (<= #SMs, TileMetadataSize) assert sm_parts <= self.cg_buf_tile_scheduler_metadata.size(0) tile_scheduler_metadata_view = self.cg_buf_tile_scheduler_metadata[ :sm_parts ] tile_scheduler_metadata_view.copy_(tile_scheduler_metadata) tile_scheduler_metadata = tile_scheduler_metadata_view # Num splits is per-batch, varying size (batch_size,) n = num_splits.size(0) # make sure static buffer is large enough assert n <= self.cg_buf_num_splits.size(0) num_splits_view = self.cg_buf_num_splits[:n] num_splits_view.copy_(num_splits) # Num splits needs to monotonically increasing # (with: https://github.com/vllm-project/FlashMLA/pull/3, otherwise # it needs to monotonically increasing by 1) self.cg_buf_num_splits[n:].fill_(num_splits[-1]) num_splits = num_splits_view return FlashMLADecodeMetadata( block_table=block_table_tensor, seq_lens=seq_lens_device, tile_scheduler_metadata=tile_scheduler_metadata, num_splits=num_splits, dcp_tot_seq_lens=dcp_tot_seq_lens_device, ) class FlashMLAImpl(MLACommonImpl[FlashMLAMetadata]): can_return_lse_for_decode: bool = True 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments **mla_args, ) -> 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, **mla_args, ) is_supported, reason = is_flashmla_dense_supported() assert is_supported, reason unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap] if any(unsupported_features): raise NotImplementedError( "FlashMLAImpl does not support one of the following: " "alibi_slopes, sliding_window, logits_soft_cap" ) if attn_type != AttentionType.DECODER: raise NotImplementedError( "Encoder self-attention and " "encoder/decoder cross-attention " "are not implemented for " "FlashMLAImpl" ) def _forward_decode( self, q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], kv_c_and_k_pe_cache: torch.Tensor, attn_metadata: FlashMLAMetadata, layer: AttentionLayer, ) -> tuple[torch.Tensor, torch.Tensor | None]: # TODO: (zyongye) decode function for mla here assert kv_c_and_k_pe_cache.numel() > 0 assert attn_metadata.decode is not None if type(q) is tuple: q = torch.cat(q, dim=-1) # mypy assertion: q is now always a tensor assert isinstance(q, torch.Tensor) num_decodes = attn_metadata.num_decodes q = reshape_query_for_spec_decode(q, num_decodes) tile_scheduler_metadata = attn_metadata.decode.tile_scheduler_metadata num_splits = attn_metadata.decode.num_splits if vllm_is_batch_invariant(): device = q.device dtype = torch.int32 B = q.shape[0] # block_table shape: [batch_size, max_num_blocks_per_seq] # The number of blocks per sequence is in the second dimension topk = attn_metadata.decode.block_table.shape[-1] B_TOPK = 64 assert topk % B_TOPK == 0, f"topk ({topk}) must be divisible by {B_TOPK}" end_block_idx = topk // B_TOPK # Single partition => num_sm_parts = 1 # TileSchedulerMetaDataSize = 8, layout: # [begin_idx, begin_block_idx, end_idx, end_block_idx, # begin_n_split_idx, _, _, _] tile_scheduler_metadata = torch.zeros((1, 8), dtype=dtype, device=device) tile_scheduler_metadata[0, 0] = 0 # begin_idx tile_scheduler_metadata[0, 1] = 0 # sched_begin_block_idx tile_scheduler_metadata[0, 2] = B - 1 # end_idx tile_scheduler_metadata[0, 3] = end_block_idx tile_scheduler_metadata[0, 4] = 0 # begin_n_split_idx # fields [5..7] stay 0 # Non-split path ignores num_splits, but the API requires it: # zeros of length B+1 num_splits = torch.zeros((B + 1,), dtype=dtype, device=device) o, lse = flash_mla_with_kvcache( q=q, k_cache=kv_c_and_k_pe_cache.unsqueeze(-2), # Add head dim of 1 block_table=attn_metadata.decode.block_table, cache_seqlens=attn_metadata.decode.seq_lens, head_dim_v=self.kv_lora_rank, tile_scheduler_metadata=tile_scheduler_metadata, num_splits=num_splits, softmax_scale=self.scale, causal=True, descale_q=layer._q_scale.reshape(1), descale_k=layer._k_scale.reshape(1), ) o = reshape_attn_output_for_spec_decode(o) return o, lse
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/common.py
vllm/v1/attention/backends/mla/common.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ # MLA Common Components This file implements common components for MLA implementations. First we define: Sq as Q sequence length Skv as KV sequence length MLA has two possible ways of computing, a data-movement friendly approach and a compute friendly approach, we generally want to use the compute friendly approach for "prefill" (i.e. the ratio Sq / Skv is "small", is near 1) and the data-movement friendly approach for "decode" (i.e. the ratio Sq / Skv is "large"). NOTE what we deem small and large is currently determined by if its labelled prefill or decode by the scheduler, but this is something we should probably tune. Main reference: DeepseekV2 paper, and FlashInfer Implementation (https://arxiv.org/abs/2405.04434 and https://github.com/flashinfer-ai/flashinfer/pull/551). Deepseek's MLA attention works the following way: * Use a single latent vector to represent the per-token entry of the KV cache. * For decode (i.e. the memory friendly approach) the attention "simulates" a multi-head attention, while the compute is similar to multi-query attention. Below is example of both paths assuming batchsize = 1 ## More Extent Definitions: C Context length, `Skv - Sq` H hidden size N number of attention heads Lq latent dimension for Q 1536 in DSV3 Lkv latent dimension for K/V 512 in DSV3 P nope dimension, no rope. 128 in DSV3 R rope dimension, goes through rope. 64 in DSV3 V V head dim. 128 in DSV3 ## Vector/Matrix Definitions h_t hidden states (input to attention) shape [Sq, H] q_c latent/compressed Q shape [Sq, Lq] q_nope uncompressed Q (no-rope) shape [Sq, N, P] q_pe uncompressed Q (rope) shape [Sq, N, R] kv_c latent/compressed KV shape [Skv, Lkv] k_pe decoupled k position embeddings shape [Skv, R] new_kv_c new kv_c from current iter shape [Sq, Lkv] new_k_pe new k_pe from current iter shape [Sq, R] cache_kv_c cached k_c from previous iters shape [C, Lkv] cache_k_pe cached k_pe from previous iters shape [C, R] W_DQ project h_t to q_c shape [H, Lq] W_UQ project q_c to q_nope shape [Lq, N * P] W_QR project q_c to q_pe shape [Lq, N * R] W_DKV project h_t to kv_c shape [H, Lkv] W_UK project kv_c to k_nope shape [Lkv, N, P] W_KR project h_t to k_pe shape [H, R] W_UV project kv_c to v shape [Lkv, N, V] W_O project v to h_t shape [N * V, H] ## Compute Friendly Approach (i.e. "_forward_prefill"): q_c = h_t @ W_DQ q_nope = (q_c @ W_UQ).view(Sq, N, P) q_pe = RoPE(q_c @ W_QR).view(Sq, N, R) new_kv_c = h_t @ W_DKV new_k_pe = RoPE(h_t @ W_KR) kv_c = torch.cat([new_kv_c, cache_kv_c], dim=0) k_pe = torch.cat([new_k_pe, cache_k_pe], dim=0) k_nope = (kv_c @ W_UK.view(Lkv, N * P)).view(Skv, N, P) v = (kv_c @ W_UV.view(Lkv, N * V)).view(Skv, N, V) // MHA with QK headdim = P + R // V headdim = V // spda_o shape [Sq, N, V] spda_o = scaled_dot_product_attention( torch.cat([q_nope, q_pe], dim=-1), torch.cat([k_nope, k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1), v ) return spda_o @ W_O NOTE: in the actual code, `kv_b_proj` is [W_UK; W_UV] concatenated per head `q_b_proj` is [W_UQ; W_QR] concatenated per head `out_proj` is W_O ## Data-Movement Friendly Approach (i.e. "_forward_decode"): Runtime q_c = h_t @ W_DQ q_nope = (q_c @ W_UQ).view(-1, N, P) ql_nope = einsum("snh,lnh->snl", q, W_UK) q_pe = RoPE(q_c @ W_QR).view(Sq, N, R) new_kv_c = h_t @ W_DKV new_k_pe = RoPE(h_t @ W_KR) kv_c = torch.cat([new_kv_c, cache_kv_c], dim=0) k_pe = torch.cat([new_k_pe, cache_k_pe], dim=0) // MQA with QK headdim = Lkv + R // V headdim = Lkv // spda_o shape [Sq, N, Lkv] // NOTE: this is less compute-friendly since Lkv > P // but is more data-movement friendly since its MQA vs MHA spda_o = scaled_dot_product_attention( torch.cat([ql_nope, q_pe], dim=-1), torch.cat([kv_c, k_pe], dim=-1), kv_c ) o = einsum("snl,lnv->snv", spda_o.reshape(-1, N, Lkv), W_UV) return o.view(-1, N * V) @ self.num_heads @ W_O ## Chunked Prefill For chunked prefill we want to use the compute friendly algorithm. We are assuming sufficiently large Sq / Skv ratio, in the future may want to switch to the data-movement friendly approach if the chunk (i.e. `Sq`) is small. However, the compute-friendly approach can potentially run out of memory if Skv is large due to: `k_nope = (kv_c @ W_UK).view(Skv, N, P)` To mitigate this, we chunk the computation of attention with respect to the current context (i.e. `cache_kv_c` and `cache_k_pe`) so that we can used a fixed workspace size. The chunked prefill approach is as follows: MCC Max chunk of context to process per iter, computed dynamically, used to bound the memory usage q_c = h_t @ W_DQ q_nope = (q_c @ W_UQ).view(Sq, N, P) q_pe = RoPE(q_c @ W_QR).view(Sq, N, R) new_kv_c = h_t @ W_DKV new_k_pe = RoPE(h_t @ W_KR) new_k_nope = (new_kv_c @ W_UK.view(Lkv, N * P)).view(Sq, N, P) new_v = (new_kv_c @ W_UV.view(Lkv, N * V)).view(Sq, N, V) // MHA between queries and new KV // with QK headdim = P + R // V headdim = V // curr_o shape [Sq, N, V] // curr_lse shape [N, Sq], this is just order FA returns curr_o, curr_lse = scaled_dot_product_attention( torch.cat([q_nope, q_pe], dim=-1), torch.cat([new_k_nope, new_k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1), new_v, casual=True, return_softmax_lse=True ) // Compute attention with the already existing context for chunk_idx in range(cdiv(C, MCC)): chunk_start = chunk_idx * MCC chunk_end = min(chunk_start + MCC, C) Sc = chunk_end - chunk_start cache_kv_c_chunk = cache_kv_c[chunk_start:chunk_end] cache_k_pe_chunk = cache_k_pe[chunk_start:chunk_end] cache_k_nope_chunk = (cache_kv_c_chunk @ W_UK).view(-1, N, P) cache_v_chunk = (cache_kv_c_chunk @ W_UV).view(-1, N, V) chunk_o, chunk_lse = scaled_dot_product_attention( torch.cat([q_nope, q_pe], dim=-1), torch.cat([cache_k_nope_chunk, cache_k_pe_chunk.unsqueeze(1).expand(-1, N, -1)], dim=-1), cache_v_chunk, casual=False, return_softmax_lse=True ) curr_o, curr_lse = merge_attn_states( suffix_output=curr_o, suffix_lse=curr_lse, prefix_output=chunk_o, prefix_lse=chunk_lse, ) return curr_o @ W_O """ import functools from abc import abstractmethod from dataclasses import dataclass, field from enum import Enum from typing import ClassVar, Generic, TypeVar import torch from tqdm import tqdm from vllm import _custom_ops as ops from vllm import envs from vllm._aiter_ops import rocm_aiter_ops from vllm.attention.backends.abstract import ( AttentionBackend, AttentionLayer, MLAAttentionImpl, ) from vllm.attention.backends.utils import get_mla_dims from vllm.attention.ops.common import cp_lse_ag_out_rs from vllm.attention.ops.merge_attn_states import merge_attn_states from vllm.attention.utils.fa_utils import get_flash_attn_version from vllm.config import VllmConfig, get_current_vllm_config from vllm.distributed.parallel_state import get_dcp_group, is_global_first_rank from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.model_executor.layers.linear import ( ColumnParallelLinear, LinearBase, UnquantizedLinearMethod, ) from vllm.platforms import current_platform from vllm.utils.flashinfer import has_nvidia_artifactory from vllm.utils.math_utils import cdiv, round_down from vllm.v1.attention.backends.utils import ( AttentionMetadataBuilder, CommonAttentionMetadata, get_dcp_local_seq_lens, get_per_layer_parameters, infer_global_hyperparameters, split_decodes_and_prefills, ) from vllm.v1.kv_cache_interface import AttentionSpec class QueryLenSupport(Enum): """Defines the level of query length support for an attention backend's decode pipeline. - SINGLE_ONLY: Decode pipeline only supports single-token queries (query_len=1) - UNIFORM: Decode pipeline supports uniform multi-token queries (all requests must have same query_len > 1) - VARLEN: Decode pipeline supports variable-length queries (mixed query lengths in same batch) """ SINGLE_ONLY = "single_only" UNIFORM = "uniform" VARLEN = "varlen" try: from vllm.vllm_flash_attn import flash_attn_varlen_func is_vllm_fa = True except ImportError: # For rocm use upstream flash attention if current_platform.is_rocm(): from flash_attn import flash_attn_varlen_func is_vllm_fa = False try: from flashinfer import BatchPrefillWithRaggedKVCacheWrapper from flashinfer.prefill import cudnn_batch_prefill_with_kv_cache # noqa: F401 flashinfer_available = True except ImportError: BatchPrefillWithRaggedKVCacheWrapper = object flashinfer_available = False def dynamic_per_batched_tensor_quant( x: torch.Tensor, dtype: torch.dtype = torch.float8_e4m3fn ): DTYPE_MAX = torch.finfo(dtype).max min_val, max_val = x.aminmax() amax = torch.maximum(min_val.abs(), max_val.abs()).clamp(min=1e-10) scale = DTYPE_MAX / amax x_scl_sat = (x * scale).clamp(min=-DTYPE_MAX, max=DTYPE_MAX) return x_scl_sat.to(dtype).contiguous(), scale.float().reciprocal() logger = init_logger(__name__) CUDNN_WORKSPACE_SIZE = 12800 class MLACommonBackend(AttentionBackend): accept_output_buffer: bool = True @staticmethod def get_name() -> str: return "TRITON_MLA" @staticmethod def get_builder_cls() -> type["MLACommonMetadataBuilder"]: return MLACommonMetadataBuilder @staticmethod def get_kv_cache_shape( num_blocks: int, block_size: int, num_kv_heads: int, # assumed to be 1 for MLA head_size: int, cache_dtype_str: str = "auto", ) -> tuple[int, ...]: return (num_blocks, block_size, head_size) @staticmethod def get_kv_cache_stride_order( include_num_layers_dimension: bool = False, ) -> tuple[int, ...]: # `stride_order` indicates the permutation that gets # us from `get_kv_cache_shape` to the actual memory layout we want. # (num_blocks, num_layers, block_size, head_size) return (1, 0, 2, 3) if include_num_layers_dimension else (0, 1, 2) @classmethod def get_supported_head_sizes(cls) -> list[int]: return [576] @classmethod def is_mla(cls) -> bool: return True @dataclass class MLACommonPrefillMetadata: """Prefill Specific Metadata""" @dataclass class ChunkedContextMetadata: # New for MLA (compared to FlashAttention) # For handling chunked prefill cu_seq_lens: torch.Tensor starts: torch.Tensor seq_tot: list[int] max_seq_lens: list[int] seq_lens: torch.Tensor workspace: torch.Tensor token_to_seq: torch.Tensor chunk_total_token: list[int] # for mla DCP padded_local_chunk_seq_lens: list[list[int]] | None = None local_context_lens_allranks: list[list[int]] | None = None padded_local_cu_seq_lens: torch.Tensor | None = None cu_seq_lens_lst: list[list[int]] | None = None chunk_size: int | None = None block_table: torch.Tensor query_start_loc: torch.Tensor max_query_len: int chunked_context: ChunkedContextMetadata | None = None query_seq_lens: torch.Tensor | None = None workspace_buffer: torch.Tensor | None = None q_data_type: torch.dtype | None = None @dataclass class FlashInferPrefillMetadata(MLACommonPrefillMetadata): prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = field( default_factory=list ) @dataclass class CudnnPrefillMetadata(MLACommonPrefillMetadata): class ChunkedContextMetadata(MLACommonPrefillMetadata.ChunkedContextMetadata): seq_lens: torch.Tensor cudnn_workspace: torch.Tensor | None = None @dataclass class MLACommonDecodeMetadata: block_table: torch.Tensor seq_lens: torch.Tensor dcp_tot_seq_lens: torch.Tensor | None D = TypeVar("D", bound=MLACommonDecodeMetadata) @dataclass class MLACommonMetadata(Generic[D]): """Metadata for MLACommon. NOTE: Please read the comment at the top of the file before trying to understand this class """ # NOTE(sang): Definition of context_len, query_len, and seq_len. # |---------- N-1 iteration --------| # |---------------- N iteration ---------------------| # |- tokenA -|......................|-- newTokens ---| # |---------- context_len ----------| # |-------------------- seq_len ---------------------| # |-- query_len ---| num_reqs: int max_query_len: int max_seq_len: int num_actual_tokens: int # Number of tokens excluding padding. query_start_loc: torch.Tensor slot_mapping: torch.Tensor # New for MLA (compared to FlashAttention) # For handling prefill decode split num_decodes: int num_decode_tokens: int num_prefills: int # The dimension of the attention heads head_dim: int | None = None decode: D | None = None prefill: ( MLACommonPrefillMetadata | FlashInferPrefillMetadata | CudnnPrefillMetadata | None ) = None def __post_init__(self): if self.head_dim is not None and not MLACommonBackend.supports_head_size( self.head_dim ): raise ValueError(f"Head dimension {self.head_dim} is not supported by MLA.") M = TypeVar("M", bound=MLACommonMetadata) A = TypeVar("A") def use_flashinfer_prefill() -> bool: # For blackwell default to flashinfer prefill if it's available since # it is faster than FA2. from vllm.config import get_current_vllm_config vllm_config = get_current_vllm_config() return ( not vllm_config.attention_config.disable_flashinfer_prefill and flashinfer_available and not vllm_config.attention_config.use_cudnn_prefill and not vllm_config.attention_config.use_trtllm_ragged_deepseek_prefill and current_platform.is_device_capability_family(100) ) def use_cudnn_prefill() -> bool: from vllm.config import get_current_vllm_config vllm_config = get_current_vllm_config() return ( flashinfer_available and vllm_config.attention_config.use_cudnn_prefill and current_platform.is_device_capability_family(100) and has_nvidia_artifactory() ) def use_trtllm_ragged_deepseek_prefill() -> bool: """Check if TRT-LLM ragged DeepSeek prefill should be used.""" from vllm.config import get_current_vllm_config vllm_config = get_current_vllm_config() return ( flashinfer_available and vllm_config.attention_config.use_trtllm_ragged_deepseek_prefill and current_platform.is_device_capability_family(100) ) class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]): """ NOTE: Please read the comment at the top of the file before trying to understand this class """ # Defines the level of query length support for this backend. # - SINGLE_ONLY: Only single-token queries (no spec decode support) # - UNIFORM: Supports uniform multi-token queries (spec decode with uniform lengths) # - VARLEN: Supports variable-length queries (spec decode with mixed lengths) # If set to UNIFORM or VARLEN, this will increase `reorder_batch_threshold` when # speculative decoding is enabled. query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.SINGLE_ONLY # The threshold for reordering the batch into decode and prefill requests. # If > 1, the batch will be reordered such that requests with # query length <= threshold are classified as decode requests. # Use `query_len_support` (above) to set this automatically # when speculative decoding is enabled. reorder_batch_threshold: int = 1 @staticmethod def determine_chunked_prefill_workspace_size(vllm_config: VllmConfig) -> int: scheduler_config = vllm_config.scheduler_config cache_config = vllm_config.cache_config model_config = vllm_config.model_config chunked_prefill_workspace_size = min( # Try for 8 full length request or at least 4 pages per-request max( 8 * model_config.max_model_len, 4 * scheduler_config.max_num_seqs * cache_config.block_size, ), # For long-context models try not to over-allocate limiting # kv-cache space, limiting it to 64k tokens, # which would result in the workspace being: # 2*(576)*(64*1024) = 144mb # (assuming 576 MLA head dim, and fp16) # which would result in up-projected context being # 2*(192*128)*(64*1024) = 3gb # (assuming 192 QK head dim, 128 heads, and fp16) 64 * 1024, ) # Enforce that we enough for at least 1 page per request chunked_prefill_workspace_size = max( chunked_prefill_workspace_size, scheduler_config.max_num_seqs * cache_config.block_size, ) return chunked_prefill_workspace_size def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, metadata_cls: type[M] | None = None, supports_dcp_with_varlen: bool = False, ): self.metadata_cls = ( metadata_cls if metadata_cls is not None else MLACommonMetadata ) self.kv_cache_spec = kv_cache_spec scheduler_config = vllm_config.scheduler_config self.model_config = vllm_config.model_config parallel_config = vllm_config.parallel_config self.compilation_config = vllm_config.compilation_config self.vllm_config = vllm_config self.device = device self.num_heads = self.model_config.get_num_attention_heads(parallel_config) self.mla_dims = get_mla_dims(self.model_config) self.aot_schedule = current_platform.is_cuda() try: self.dcp_world_size = get_dcp_group().world_size self.dcp_rank = get_dcp_group().rank_in_group except AssertionError: # DCP might not be initialized in testing self.dcp_world_size = 1 self.dcp_rank = 0 self.dcp_local_block_size = parallel_config.cp_kv_cache_interleave_size self.dcp_virtual_block_size = self.dcp_local_block_size * self.dcp_world_size self.cp_kv_cache_interleave_size = parallel_config.cp_kv_cache_interleave_size # Don't try to access the runner on AMD if self.aot_schedule: self.page_size = self.kv_cache_spec.block_size self.chunked_prefill_workspace_size = ( self.determine_chunked_prefill_workspace_size(vllm_config) ) if self.dcp_world_size > 1: # Note(hc): The local kvcache is incomplete when DCP is triggered, # an additional kvcache allgather across the DCP group is therefore # required, so the workspace has to be enlarged by 1/DCP relative # to the original TP allocation. assert self.chunked_prefill_workspace_size % self.dcp_world_size == 0 self.chunked_prefill_workspace = torch.empty( ( self.chunked_prefill_workspace_size + self.chunked_prefill_workspace_size // self.dcp_world_size, self.model_config.get_head_size(), ), dtype=self.model_config.dtype, device=device, ) else: self.chunked_prefill_workspace = torch.empty( ( self.chunked_prefill_workspace_size, self.model_config.get_head_size(), ), dtype=self.model_config.dtype, device=device, ) self._use_cudnn_prefill = use_cudnn_prefill() self._use_fi_prefill = use_flashinfer_prefill() self._use_trtllm_ragged_prefill = use_trtllm_ragged_deepseek_prefill() self.prefill_metadata_cls = ( FlashInferPrefillMetadata if self._use_fi_prefill else CudnnPrefillMetadata if self._use_cudnn_prefill else MLACommonPrefillMetadata ) if self._use_fi_prefill: self._workspace_buffer = torch.empty( envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE, dtype=torch.uint8, device=device, ) self._fi_prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None self._fi_prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = [] self._global_hyperparameters = infer_global_hyperparameters( get_per_layer_parameters(vllm_config, layer_names, MLACommonImpl) ) if self._use_trtllm_ragged_prefill: self._workspace_buffer = torch.empty( envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE, dtype=torch.uint8, device=device, ) if self._use_cudnn_prefill: self.cudnn_workspace = torch.empty( CUDNN_WORKSPACE_SIZE * scheduler_config.max_num_seqs, dtype=torch.int8, device=device, ) supports_spec_decode = self.query_len_support != QueryLenSupport.SINGLE_ONLY self._init_reorder_batch_threshold( self.reorder_batch_threshold, supports_spec_decode, supports_dcp_with_varlen ) # Validate consistency between query_len_support and reorder_batch_threshold if self.query_len_support == QueryLenSupport.SINGLE_ONLY: assert self.reorder_batch_threshold == 1, ( f"reorder_batch_threshold must be 1 when query_len_support is " f"SINGLE_ONLY, got {self.reorder_batch_threshold}" ) def _build_fi_prefill_wrappers(self, prefill: FlashInferPrefillMetadata): qo_indptr = prefill.query_start_loc has_context = False if prefill.chunked_context is not None: chunked_context = prefill.chunked_context has_context = True if self._fi_prefill_main is None: self._fi_prefill_main = BatchPrefillWithRaggedKVCacheWrapper( self._workspace_buffer, "NHD", backend="cutlass" ) if has_context: num_chunks = chunked_context.cu_seq_lens.shape[0] # Allocate more prefill chunk wrappers if needed if len(self._fi_prefill_chunks) < num_chunks: for _ in range(len(self._fi_prefill_chunks), num_chunks): self._fi_prefill_chunks.append( BatchPrefillWithRaggedKVCacheWrapper( self._workspace_buffer, "NHD", backend="cutlass" ) ) assert num_chunks <= len(self._fi_prefill_chunks) # In MLA, the non-latent num_qo_heads == num_kv_heads num_qo_heads = self.num_heads num_kv_heads = num_qo_heads # Sanity: Verify that num_kv_heads == 1 since it is latent space assert self.kv_cache_spec.num_kv_heads == 1 # Get non-latent head_dim_qk and head_dim_vo head_dim_qk = self.mla_dims.qk_nope_head_dim + self.mla_dims.qk_rope_head_dim head_dim_vo = self.mla_dims.v_head_dim # For main run, qo_indptr == kv_indptr kv_indptr = qo_indptr.clone() # Prepare main prefill self._fi_prefill_main.plan( qo_indptr=qo_indptr, kv_indptr=kv_indptr, num_qo_heads=num_qo_heads, num_kv_heads=num_kv_heads, head_dim_qk=head_dim_qk, head_dim_vo=head_dim_vo, causal=True, # This is main run sm_scale=self._global_hyperparameters.sm_scale, window_left=self._global_hyperparameters.window_left, logits_soft_cap=self._global_hyperparameters.logits_soft_cap, q_data_type=self.model_config.dtype, ) # Prepare context prefills if has_context: for i in range(num_chunks): kv_indptr_chunk = chunked_context.cu_seq_lens[i] self._fi_prefill_chunks[i].plan( qo_indptr=qo_indptr, kv_indptr=kv_indptr_chunk, num_qo_heads=num_qo_heads, num_kv_heads=num_kv_heads, head_dim_qk=head_dim_qk, head_dim_vo=head_dim_vo, causal=False, # This is context run sm_scale=self._global_hyperparameters.sm_scale, window_left=self._global_hyperparameters.window_left, logits_soft_cap=self._global_hyperparameters.logits_soft_cap, q_data_type=self.model_config.dtype, ) prefill.prefill_main = self._fi_prefill_main prefill.prefill_chunks = self._fi_prefill_chunks def _build_decode( self, block_table_tensor: torch.Tensor, seq_lens_device: torch.Tensor, max_seq_len: int, query_start_loc_cpu: torch.Tensor, query_start_loc_device: torch.Tensor, num_decode_tokens: int, dcp_tot_seq_lens_device: torch.Tensor | None, ) -> MLACommonDecodeMetadata: return MLACommonDecodeMetadata( block_table=block_table_tensor, seq_lens=seq_lens_device, dcp_tot_seq_lens=dcp_tot_seq_lens_device, ) def build_for_cudagraph_capture( self, common_attn_metadata: CommonAttentionMetadata ) -> M: """ This method builds the metadata for full cudagraph capture. Currently, only decode is supported for full cudagraphs with MLA. """ m = common_attn_metadata assert m.num_reqs <= (m.num_actual_tokens * self.reorder_batch_threshold), ( "MLA only supports decode-only full CUDAGraph capture. " "Make sure all cudagraph capture sizes <= max_num_seq." ) assert m.max_query_len <= self.reorder_batch_threshold # decode only return self.build(0, m) def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> M: num_reqs = common_attn_metadata.num_reqs num_tokens = common_attn_metadata.num_actual_tokens max_query_len = common_attn_metadata.max_query_len max_seq_len = common_attn_metadata.max_seq_len # Note(simon): be careful about the CPU <> GPU memory movement in this # function. We should avoid GPU -> CPU sync as much as possible because # it blocks on all previous kernels. device = self.device block_table_tensor = common_attn_metadata.block_table_tensor slot_mapping = common_attn_metadata.slot_mapping query_start_loc = common_attn_metadata.query_start_loc query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu seq_lens = common_attn_metadata.seq_lens dcp_local_seq_lens = common_attn_metadata.dcp_local_seq_lens num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( split_decodes_and_prefills( common_attn_metadata, decode_threshold=self.reorder_batch_threshold, require_uniform=(self.query_len_support != QueryLenSupport.VARLEN), ) ) assert num_decodes + num_prefills == num_reqs assert num_decode_tokens + num_prefill_tokens == num_tokens prefill_metadata = None if num_prefills > 0: num_computed_tokens_cpu = common_attn_metadata.num_computed_tokens_cpu reqs_start = num_decodes # prefill_start context_lens_cpu = num_computed_tokens_cpu[reqs_start:num_reqs] max_context_len_cpu = context_lens_cpu.max().item() num_prefills_with_context_cpu = (context_lens_cpu > 0).sum().item() prefill_query_start_loc = ( query_start_loc[reqs_start:] - query_start_loc[reqs_start] ) chunked_context_metadata = None if max_context_len_cpu > 0: # NOTE: it is recommend you read the `Chunked Prefill` section # in the comment at the top of the file before trying to # understand the following code # currently we allocate an equal amount of workspace for each # prefill in the batch, we could probably use a more advanced # algorithm here and allocate more workspace to prefills with # longer context lengths max_context_chunk = ( self.chunked_prefill_workspace_size // num_prefills_with_context_cpu ) if self.aot_schedule: # align max_context_chunk to page_size by rounding down, # currently the `gather_and_maybe_dequant_cache` kernel # cannot handle `context_chunk_starts` that are not aligned # to page_size max_context_chunk = round_down(max_context_chunk, self.page_size) assert max_context_chunk > 0 num_chunks = cdiv(max_context_len_cpu, max_context_chunk) # if `max_context_chunk = 256`, `num_chunks = 3`, and # `num_prefills_with_context = 4`, create a tensor that looks # like # [[0, 0, 0, 0], [256, 256, 256, 256], [512, 512, 512, 512]] # Note(simon): this is done in CPU because of downstream's # of `to_list`. chunk_starts = ( torch.arange(num_chunks, dtype=torch.int32) .unsqueeze(1) .expand(-1, num_prefills) * max_context_chunk ) chunk_ends = torch.min( context_lens_cpu.unsqueeze(0), chunk_starts + max_context_chunk ) chunk_seq_lens = (chunk_ends - chunk_starts).clamp(min=0) cu_seq_lens_cpu = torch.zeros( num_chunks, num_prefills + 1, dtype=torch.int32, pin_memory=True ) torch.cumsum( chunk_seq_lens, dim=1, out=cu_seq_lens_cpu[:, 1:], dtype=torch.int32 ) chunk_total_token = cu_seq_lens_cpu[:, -1] max_token_num_over_chunk = chunk_total_token.max().item() token_to_seq_tensor_cpu = torch.zeros( [num_chunks, max_token_num_over_chunk], dtype=torch.int32 ) range_idx = torch.arange(num_prefills, dtype=torch.int32) for i in range(num_chunks): chunk_token_to_seq_tensor = torch.repeat_interleave( range_idx, chunk_seq_lens[i] ) chunk_len = chunk_token_to_seq_tensor.shape[0] token_to_seq_tensor_cpu[i, :chunk_len] = chunk_token_to_seq_tensor if self.dcp_world_size > 1: local_context_lens_allranks = get_dcp_local_seq_lens( context_lens_cpu, self.dcp_world_size, None, self.dcp_local_block_size, ) # Note(qcs): The max local context lengths # padded to `dcp_local_block_size`. padded_local_context_lens_cpu = ( cdiv(
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/rocm_aiter_mla_sparse.py
vllm/v1/attention/backends/mla/rocm_aiter_mla_sparse.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import TYPE_CHECKING, ClassVar, Optional import numpy as np import torch from vllm import _custom_ops as ops from vllm._aiter_ops import rocm_aiter_ops from vllm.attention.backends.abstract import ( AttentionBackend, AttentionLayer, AttentionMetadata, ) from vllm.attention.backends.utils import get_mla_dims from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.v1.attention.backends.mla.common import ( MLACommonBaseImpl, ) from vllm.v1.attention.backends.mla.flashmla_sparse import ( triton_convert_req_index_to_global_index, ) from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, ) from vllm.v1.kv_cache_interface import AttentionSpec if TYPE_CHECKING: from vllm.model_executor.models.deepseek_v2 import Indexer logger = init_logger(__name__) class ROCMAiterMLASparseBackend(AttentionBackend): accept_output_buffer: bool = True @staticmethod def get_name() -> str: return "ROCM_AITER_MLA_SPARSE" @staticmethod def get_metadata_cls() -> type[AttentionMetadata]: return ROCMAiterMLASparseMetadata @staticmethod def get_builder_cls() -> type["ROCMAiterMLASparseMetadataBuilder"]: return ROCMAiterMLASparseMetadataBuilder @staticmethod def get_impl_cls() -> type["ROCMAiterMLASparseImpl"]: return ROCMAiterMLASparseImpl @staticmethod def get_kv_cache_shape( num_blocks: int, block_size: int, num_kv_heads: int, # assumed to be 1 for MLA head_size: int, cache_dtype_str: str = "auto", ) -> tuple[int, ...]: return (num_blocks, block_size, head_size) @classmethod def get_supported_dtypes(cls) -> list[torch.dtype]: return [torch.bfloat16] @classmethod def get_supported_head_sizes(cls) -> list[int]: return [576] @dataclass class ROCMAiterMLASparseMetadata: num_reqs: int max_query_len: int max_seq_len: int num_actual_tokens: int # Number of tokens excluding padding. query_start_loc: torch.Tensor slot_mapping: torch.Tensor block_table: torch.Tensor req_id_per_token: torch.Tensor block_size: int = 1 topk_tokens: int = 2048 @dataclass class ROCMAiterMLASparseMetadataBuilder( AttentionMetadataBuilder[ROCMAiterMLASparseMetadata] ): cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.NEVER def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): self.kv_cache_spec = kv_cache_spec self.model_config = vllm_config.model_config parallel_config = vllm_config.parallel_config self.device = device self.num_heads = self.model_config.get_num_attention_heads(parallel_config) self.mla_dims = get_mla_dims(self.model_config) self.topk_tokens = vllm_config.model_config.hf_config.index_topk self.topk_tokens_tensor = torch.tensor( [self.topk_tokens], device=device, dtype=torch.int32 ) self.max_model_len_tensor = torch.tensor( [self.model_config.max_model_len], device=device, dtype=torch.int32 ) # this is ignored by `flash_mla_with_kvcache` if indices not None self.dummy_block_table = torch.empty( (1, 1), dtype=torch.int32, device=self.device ) self.req_id_per_token_buffer = torch.empty( (vllm_config.scheduler_config.max_num_batched_tokens,), dtype=torch.int32, device=device, ) def build( self, common_prefix_len: int, common_attn_metadata: CommonAttentionMetadata, fast_build: bool = False, ) -> ROCMAiterMLASparseMetadata: num_tokens = common_attn_metadata.num_actual_tokens starts = np.asarray(common_attn_metadata.query_start_loc_cpu, dtype=np.int32) seg_lengths = np.diff(starts) req_id_per_token = np.repeat( np.arange(seg_lengths.shape[0], dtype=np.int32), seg_lengths ) # Zero-fill for cudagraphs self.req_id_per_token_buffer.fill_(0) self.req_id_per_token_buffer[: req_id_per_token.shape[0]].copy_( torch.from_numpy(req_id_per_token), non_blocking=True ) req_id_per_token = self.req_id_per_token_buffer[:num_tokens] metadata = ROCMAiterMLASparseMetadata( num_reqs=common_attn_metadata.num_reqs, max_query_len=common_attn_metadata.max_query_len, max_seq_len=common_attn_metadata.max_seq_len, num_actual_tokens=common_attn_metadata.num_actual_tokens, query_start_loc=common_attn_metadata.query_start_loc, slot_mapping=common_attn_metadata.slot_mapping, block_table=common_attn_metadata.block_table_tensor, req_id_per_token=req_id_per_token, block_size=self.kv_cache_spec.block_size, topk_tokens=self.topk_tokens, ) return metadata # Take from # https://github.com/deepseek-ai/FlashMLA/blob/main/tests/test_flash_mla_prefill.py#L72 def reference_mla_sparse_prefill( q: torch.Tensor, kv: torch.Tensor, indices: torch.Tensor, sm_scale: float, d_v: int ) -> tuple[torch.Tensor, torch.Tensor]: import math def log2sumexp2(a: torch.Tensor, dim: int) -> torch.Tensor: return torch.logsumexp(a * math.log(2), dim=dim) * math.log2(math.e) skv = kv.shape[0] sq = q.shape[0] topk = indices.shape[-1] dqk = q.shape[-1] indices = indices[:, 0, :] # [s_q, topk] invalid_indices_mask = (indices < 0) | (indices >= skv) indices[invalid_indices_mask] = 0 qs = q # [s_q, h_q, d_qk] kvs = kv[:, 0, :][indices].view(sq, topk, dqk) # [s_q, topk, d_qk] attn_score = (qs @ kvs.transpose(1, 2)).float() # [s_q, h_q, topk] attn_score.masked_fill_(invalid_indices_mask.unsqueeze(1), float("-inf")) attn_score *= sm_scale * math.log2(math.e) lse = log2sumexp2(attn_score, dim=-1) # [s_q, h_q] attn_score = torch.exp2(attn_score - lse.unsqueeze(-1)) # [s_q, h_q, topk] result = attn_score.to(q.dtype) @ kvs[:, :, :d_v] return (result, lse) class ROCMAiterMLASparseImpl(MLACommonBaseImpl[ROCMAiterMLASparseMetadata]): 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments topk_indice_buffer: torch.Tensor | None = None, indexer: Optional["Indexer"] = None, **mla_args, ) -> 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, **mla_args, ) self.softmax_scale = scale assert indexer is not None self.topk_indices_buffer = indexer.topk_indices_buffer self.is_fp8bmm_enabled = rocm_aiter_ops.is_fp8bmm_enabled() def _forward_bf16_kv( self, q: torch.Tensor, kv_c_and_k_pe_cache: torch.Tensor, topk_indices: torch.Tensor, attn_metadata: ROCMAiterMLASparseMetadata, ) -> torch.Tensor: num_tokens = q.shape[0] kv_c_and_k_pe_cache = kv_c_and_k_pe_cache.view( -1, 1, kv_c_and_k_pe_cache.shape[-1] ) topk_indices = topk_indices.view(num_tokens, 1, -1) output = reference_mla_sparse_prefill( q, kv_c_and_k_pe_cache, topk_indices, self.softmax_scale, 512 )[0] return output[:, : self.num_heads, :] def forward( self, layer: AttentionLayer, q: torch.Tensor, k_c_normed: torch.Tensor, # key in unified attn k_pe: torch.Tensor, # value in unified attn kv_cache: torch.Tensor, attn_metadata: ROCMAiterMLASparseMetadata, output: torch.Tensor | None = None, output_scale: torch.Tensor | None = None, output_block_scale: torch.Tensor | None = None, ) -> torch.Tensor: # NOTE(lucas): for the sparse FlashMLA kernels the kernels want to use # MQA 576/512 approach for both prefill and decode assert output is not None, "Output tensor must be provided." if output_scale is not None or output_block_scale is not None: raise NotImplementedError( "fused output quantization is not yet supported for ROCMAiterMLASparse" ) if attn_metadata is None: # The zero fill is required when used with DP + EP # to ensure all ranks within a DP group compute the # same expert outputs. return output.fill_(0) num_actual_toks = attn_metadata.num_actual_tokens # Inputs and outputs may be padded for CUDA graphs q = q[:num_actual_toks, ...] k_c_normed = k_c_normed[:num_actual_toks, ...] k_pe = k_pe[:num_actual_toks, ...] q_nope, q_pe = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1) # Convert from (B, N, P) to (N, B, P) q_nope = q_nope.transpose(0, 1) if self.is_fp8bmm_enabled: # Multiply+Transpose (N, B, P)x(N, P, L)->(N, B, L)->(B, N, L) ql_nope = rocm_aiter_ops.triton_fp8_bmm( q_nope, self.W_K, self.W_K_scale, group_size=128, transpose_bm=True ) else: # Multiply (N, B, P) x (N, P, L) -> (N, B, L) ql_nope = torch.bmm(q_nope, self.W_UK_T) # Convert from (N, B, L) to (B, N, L) ql_nope = ql_nope.transpose(0, 1) topk_indices = self.topk_indices_buffer[:num_actual_toks] topk_indices_global = triton_convert_req_index_to_global_index( attn_metadata.req_id_per_token, attn_metadata.block_table, topk_indices, BLOCK_SIZE=attn_metadata.block_size, NUM_TOPK_TOKENS=attn_metadata.topk_tokens, ) q = torch.cat([ql_nope, q_pe], dim=-1) # write the latent and rope to kv cache if kv_cache.numel() > 0: ops.concat_and_cache_mla( k_c_normed, k_pe.squeeze(1), kv_cache, attn_metadata.slot_mapping.flatten(), kv_cache_dtype=self.kv_cache_dtype, scale=layer._k_scale, ) attn_out = self._forward_bf16_kv( q, kv_cache, topk_indices_global, attn_metadata ) self._v_up_proj(attn_out, out=output[:num_actual_toks]) return output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/rocm_aiter_mla.py
vllm/v1/attention/backends/mla/rocm_aiter_mla.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import ClassVar import torch from vllm._aiter_ops import rocm_aiter_ops from vllm.attention.backends.abstract import AttentionLayer, MultipleOf from vllm.config import VllmConfig from vllm.v1.attention.backends.mla.common import ( MLACommonBackend, MLACommonDecodeMetadata, MLACommonImpl, MLACommonMetadata, MLACommonMetadataBuilder, QueryLenSupport, ) from vllm.v1.attention.backends.utils import AttentionCGSupport from vllm.v1.kv_cache_interface import AttentionSpec class AiterMLABackend(MLACommonBackend): @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [1] @staticmethod def get_name() -> str: return "ROCM_AITER_MLA" @staticmethod def get_impl_cls() -> type["AiterMLAImpl"]: return AiterMLAImpl @staticmethod def get_builder_cls() -> type["AiterMLAMetadataBuilder"]: return AiterMLAMetadataBuilder @dataclass class AiterMLADecodeMetadata(MLACommonDecodeMetadata): # The indptr of the paged kv cache, shape: [batch_size + 1] paged_kv_indptr: torch.Tensor | None = None # The page indices of the paged kv cache paged_kv_indices: torch.Tensor | None = None # The number of entries in the last page of each request in # the paged kv cache, shape: [batch_size] paged_kv_last_page_len: torch.Tensor | None = None # The query indptr, shape : [num_decode + 1] qo_indptr: torch.Tensor | None = None # The dtype of MLA out tensor attn_out_dtype: torch.dtype = torch.bfloat16 # The max query output length: int max_qo_len: int | None = None class AiterMLAMetadata(MLACommonMetadata[AiterMLADecodeMetadata]): pass class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]): # TODO(luka, lucas): audit this as part of: # https://github.com/vllm-project/vllm/issues/22945 _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.UNIFORM def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): super().__init__( kv_cache_spec, layer_names, vllm_config, device, AiterMLAMetadata ) self.compilation_config = vllm_config.compilation_config self.decode_attn_out_dtype = vllm_config.model_config.dtype # kernel block size is always 1. max_num_pages_per_req = vllm_config.model_config.max_model_len max_num_reqs = vllm_config.scheduler_config.max_num_seqs max_num_pages = max_num_reqs * max_num_pages_per_req # Preparing persistent buffers # TODO: we can disambiguate between decode and mixed-prefill decode here # so we can only use the persistent buffer if a cudagraph is actually # being used. # paged_kv_last_page_len is always 1s (kernel block size is always 1), # so we create it once and reuse slices in both eager and cudagraph modes. self.paged_kv_last_page_len = torch.ones( max_num_reqs, dtype=torch.int32, device=device ) if self.compilation_config.cudagraph_mode.has_full_cudagraphs(): self.paged_kv_indptr = torch.zeros( max_num_reqs + 1, dtype=torch.int32, device=device ) self.paged_kv_indices = torch.zeros( max_num_pages, dtype=torch.int32, device=device ) self.qo_indptr = torch.zeros( max_num_reqs + 1, dtype=torch.int32, device=device ) def _build_decode( self, block_table_tensor: torch.Tensor, seq_lens_device: torch.Tensor, max_seq_len: int, query_start_loc_cpu: torch.Tensor, query_start_loc_device: torch.Tensor, num_decode_tokens: int, dcp_tot_seq_lens_device: torch.Tensor | None, ) -> AiterMLADecodeMetadata: # kernel block size is always 1, although the kv block size is not 1. device = self.device num_reqs = seq_lens_device.size(0) mask = torch.arange( block_table_tensor.size(1), dtype=block_table_tensor.dtype, device=device ).unsqueeze(0) < seq_lens_device.unsqueeze(1) paged_kv_indices = block_table_tensor[mask] # kernel block size is always 1, so each page has exactly 1 token. # last_page_len is always 1 - just slice the pre-initialized buffer. paged_kv_last_page_len = self.paged_kv_last_page_len[:num_reqs] paged_kv_indptr = torch.cat( [ torch.zeros(1, dtype=seq_lens_device.dtype, device=device), seq_lens_device.cumsum(dim=0, dtype=torch.int32), ] ) qo_len = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1] max_qo_len = qo_len.max().item() if self.compilation_config.cudagraph_mode.has_full_cudagraphs(): num_actual_pages = paged_kv_indices.size(0) self.paged_kv_indices[:num_actual_pages].copy_( paged_kv_indices, non_blocking=True ) self.paged_kv_indices[num_actual_pages:].fill_(-1) paged_kv_indices = self.paged_kv_indices[:num_actual_pages] self.paged_kv_indptr[: 1 + num_reqs].copy_( paged_kv_indptr, non_blocking=True ) self.paged_kv_indptr[1 + num_reqs :].fill_(paged_kv_indptr[-1]) paged_kv_indptr = self.paged_kv_indptr[: 1 + num_reqs] # paged_kv_last_page_len already uses the pre-initialized buffer slice # (set above), so no copy needed - buffer is always 1s. self.qo_indptr[: 1 + num_reqs].copy_( query_start_loc_device, non_blocking=True ) self.qo_indptr[1 + num_reqs :] = query_start_loc_device[-1] qo_indptr = self.qo_indptr[: 1 + num_reqs] else: qo_indptr = torch.arange( 0, num_reqs + 1, step=1, dtype=torch.int32, device=device ) attn_metadata = AiterMLADecodeMetadata( block_table=block_table_tensor, seq_lens=seq_lens_device, paged_kv_indptr=paged_kv_indptr, paged_kv_indices=paged_kv_indices, paged_kv_last_page_len=paged_kv_last_page_len, qo_indptr=qo_indptr, dcp_tot_seq_lens=dcp_tot_seq_lens_device, max_qo_len=max_qo_len, attn_out_dtype=self.decode_attn_out_dtype, ) return attn_metadata class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]): 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments **mla_args, ) -> 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, **mla_args, ) assert num_heads == 16 or num_heads == 128, ( f"Aiter MLA only supports 16 or 128 number of heads.\n" f"Provided {num_heads} number of heads.\n" "Try adjusting tensor_parallel_size value." ) unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap] if any(unsupported_features): raise NotImplementedError( "Aiter MLA does not support one of the following: " "alibi_slopes, sliding_window, logits_soft_cap" ) from aiter import flash_attn_varlen_func self.flash_attn_varlen_func = flash_attn_varlen_func def _flash_attn_varlen_diff_headdims( self, q, k, v, return_softmax_lse=False, softmax_scale=None, **kwargs ): output = self.flash_attn_varlen_func( q=q, k=k, v=v, softmax_scale=softmax_scale, return_lse=return_softmax_lse, **kwargs, ) return output def _forward_decode( self, q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], kv_c_and_k_pe_cache: torch.Tensor, attn_metadata: AiterMLAMetadata, layer: AttentionLayer, ) -> tuple[torch.Tensor, torch.Tensor | None]: assert kv_c_and_k_pe_cache.numel() > 0 assert attn_metadata.decode is not None if type(q) is tuple: q = torch.cat(q, dim=-1) assert isinstance(q, torch.Tensor) B = q.shape[0] o = torch.zeros( B, self.num_heads, self.kv_lora_rank, dtype=attn_metadata.decode.attn_out_dtype, device=q.device, ) kv_buffer = kv_c_and_k_pe_cache.unsqueeze(2) rocm_aiter_ops.mla_decode_fwd( q, kv_buffer, o, self.scale, attn_metadata.decode.qo_indptr, attn_metadata.decode.max_qo_len, attn_metadata.decode.paged_kv_indptr, attn_metadata.decode.paged_kv_indices, attn_metadata.decode.paged_kv_last_page_len, q_scale=layer._q_scale, kv_scale=layer._k_scale, ) return o, None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/flashattn_mla.py
vllm/v1/attention/backends/mla/flashattn_mla.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import ClassVar import torch from vllm.attention.backends.abstract import ( AttentionLayer, AttentionType, MultipleOf, is_quantized_kv_cache, ) from vllm.attention.utils.fa_utils import ( flash_attn_supports_mla, get_flash_attn_version, ) from vllm.config import VllmConfig from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.platforms.interface import DeviceCapability from vllm.v1.attention.backends.mla.common import ( MLACommonBackend, MLACommonDecodeMetadata, MLACommonImpl, MLACommonMetadata, MLACommonMetadataBuilder, QueryLenSupport, ) from vllm.v1.attention.backends.utils import AttentionCGSupport from vllm.v1.kv_cache_interface import AttentionSpec from vllm.vllm_flash_attn import flash_attn_varlen_func, get_scheduler_metadata logger = init_logger(__name__) class FlashAttnMLABackend(MLACommonBackend): supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto"] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [MultipleOf(16)] @staticmethod def get_name() -> str: return "FLASH_ATTN_MLA" @staticmethod def get_builder_cls() -> type["FlashAttnMLAMetadataBuilder"]: return FlashAttnMLAMetadataBuilder @staticmethod def get_impl_cls() -> type["FlashAttnMLAImpl"]: return FlashAttnMLAImpl @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return capability.major == 9 @classmethod def supports_combination( cls, head_size: int, dtype: torch.dtype, kv_cache_dtype: CacheDType | None, block_size: int, use_mla: bool, has_sink: bool, use_sparse: bool, device_capability: DeviceCapability, ) -> str | None: if not flash_attn_supports_mla(): return "FlashAttention MLA not supported on this device" return None @dataclass class FlashAttnMLADecodeMetadata(MLACommonDecodeMetadata): query_start_loc: torch.Tensor max_query_len: int max_seq_len: int scheduler_metadata: torch.Tensor | None = None max_num_splits: int = 0 @dataclass class FlashAttnMLAMetadata(MLACommonMetadata[FlashAttnMLADecodeMetadata]): pass class FlashAttnMLAMetadataBuilder(MLACommonMetadataBuilder[FlashAttnMLAMetadata]): _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.VARLEN reorder_batch_threshold: int = 512 # process small prefills with decode pathway def __init__( self, kv_cache_spec: AttentionSpec, layer_names: list[str], vllm_config: VllmConfig, device: torch.device, ): interleave_size = vllm_config.parallel_config.cp_kv_cache_interleave_size super().__init__( kv_cache_spec, layer_names, vllm_config, device, FlashAttnMLAMetadata, supports_dcp_with_varlen=(interleave_size == 1), ) self.max_num_splits = 0 # No upper bound on the number of splits. self.fa_aot_schedule = get_flash_attn_version() == 3 self.use_full_cuda_graph = ( self.compilation_config.cudagraph_mode.has_full_cudagraphs() ) self.max_cudagraph_size = self.compilation_config.max_cudagraph_capture_size if self.use_full_cuda_graph and self.fa_aot_schedule: self.scheduler_metadata = torch.zeros( vllm_config.scheduler_config.max_num_seqs + 1, dtype=torch.int32, device=self.device, ) # When using cuda graph, we need to set the upper bound of the # number of splits so that large enough intermediate buffers are # pre-allocated during capture. self.max_num_splits = ( vllm_config.attention_config.flash_attn_max_num_splits_for_cuda_graph ) if vllm_is_batch_invariant(): self.max_num_splits = 1 def _schedule_decode( self, num_reqs, cu_query_lens, max_query_len, seqlens, max_seq_len, causal, max_num_splits, ): if self.fa_aot_schedule: return get_scheduler_metadata( batch_size=num_reqs, max_seqlen_q=max_query_len, max_seqlen_k=max_seq_len, num_heads_q=self.num_heads * self.dcp_world_size, num_heads_kv=1, headdim=self.mla_dims.qk_rope_head_dim, cache_seqlens=seqlens, qkv_dtype=self.kv_cache_spec.dtype, headdim_v=self.mla_dims.kv_lora_rank, page_size=self.page_size, cu_seqlens_q=cu_query_lens, causal=causal, num_splits=max_num_splits, ) return None def _build_decode( self, block_table_tensor: torch.Tensor, seq_lens_device: torch.Tensor, max_seq_len: int, query_start_loc_cpu: torch.Tensor, query_start_loc_device: torch.Tensor, num_decode_tokens: int, dcp_tot_seq_lens_device: torch.Tensor | None, ) -> FlashAttnMLADecodeMetadata: query_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1] max_query_len = query_lens_cpu.max().item() # For Flash Attention MLA + full cudagraph max_num_splits = 0 if self.use_full_cuda_graph and num_decode_tokens <= self.max_cudagraph_size: # NOTE(woosuk): Setting num_splits > 1 may increase the memory # usage, because the intermediate buffers of size [num_splits, # num_heads, num_tokens, head_size] are allocated. Therefore, # we only set num_splits when using cuda graphs. max_num_splits = self.max_num_splits if vllm_is_batch_invariant(): max_num_splits = 1 scheduler_metadata = self._schedule_decode( num_reqs=seq_lens_device.shape[0], cu_query_lens=query_start_loc_device, max_query_len=max_query_len, seqlens=seq_lens_device, max_seq_len=max_seq_len, causal=True, max_num_splits=max_num_splits, ) if self.use_full_cuda_graph and scheduler_metadata is not None: n = scheduler_metadata.shape[0] # Ensure the persistent buffer is large enough assert n <= self.scheduler_metadata.shape[0], ( f"Scheduler metadata size {n} exceeds buffer size " + f"{self.scheduler_metadata.shape[0]}" ) self.scheduler_metadata[:n] = scheduler_metadata # NOTE(woosuk): We should zero out the rest of the scheduler # metadata to guarantee the correctness. Otherwise, some thread # blocks may use the invalid scheduler metadata and overwrite the # output buffer. self.scheduler_metadata[n:] = 0 scheduler_metadata = self.scheduler_metadata[:n] metadata = FlashAttnMLADecodeMetadata( block_table=block_table_tensor, seq_lens=seq_lens_device, query_start_loc=query_start_loc_device, max_query_len=max_query_len, max_seq_len=max_seq_len, scheduler_metadata=scheduler_metadata, max_num_splits=max_num_splits, dcp_tot_seq_lens=dcp_tot_seq_lens_device, ) return metadata class FlashAttnMLAImpl(MLACommonImpl[FlashAttnMLAMetadata]): can_return_lse_for_decode: bool = True 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments **mla_args, ) -> 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, **mla_args, ) assert flash_attn_supports_mla(), "FlashAttnMLA is not supported on this device" unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap] if any(unsupported_features): raise NotImplementedError( "FlashAttnMLAImpl does not support one of the following: " "alibi_slopes, sliding_window, logits_soft_cap" ) if attn_type != AttentionType.DECODER: raise NotImplementedError( "Encoder self-attention and " "encoder/decoder cross-attention " "are not implemented for " "FlashAttnMLAImpl" ) if is_quantized_kv_cache(self.kv_cache_dtype): raise NotImplementedError( "FlashAttnMLA V1 with FP8 KV cache not yet supported" ) def _forward_decode( self, q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], kv_c_and_k_pe_cache: torch.Tensor, attn_metadata: FlashAttnMLAMetadata, layer: AttentionLayer, ) -> tuple[torch.Tensor, torch.Tensor | None]: assert kv_c_and_k_pe_cache.numel() > 0 assert attn_metadata.decode is not None if type(q) is tuple: q_nope, q_pe = q else: q_nope, q_pe = torch.split( q, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) if self.kv_cache_dtype.startswith("fp8"): raise NotImplementedError("FP8 FlashAttention MLA not yet supported") kv_c_cache = kv_c_and_k_pe_cache[..., : self.kv_lora_rank] k_pe_cache = kv_c_and_k_pe_cache[..., self.kv_lora_rank :] # NOTE(matt): During CUDA graph capture, max_query_len can be 0, but the # kernel uses this to calculate grid dimensions. Ensure it's at least 1 # to prevent invalid grid configuration during graph capture. max_seqlen_q = max(attn_metadata.decode.max_query_len, 1) attn_out = flash_attn_varlen_func( q=q_pe, k=k_pe_cache.unsqueeze(-2), # Add head dim of 1 v=kv_c_cache.unsqueeze(-2), # Add head dim of 1 q_v=q_nope, max_seqlen_q=max_seqlen_q, cu_seqlens_q=attn_metadata.decode.query_start_loc, max_seqlen_k=attn_metadata.decode.max_seq_len, seqused_k=attn_metadata.decode.seq_lens, block_table=attn_metadata.decode.block_table, softmax_scale=self.scale, causal=True, return_softmax_lse=self.need_to_return_lse_for_decode, fa_version=3, # only version 3 is supported scheduler_metadata=attn_metadata.decode.scheduler_metadata, num_splits=attn_metadata.decode.max_num_splits, cp_world_size=self.dcp_world_size, cp_rank=self.dcp_rank, cp_tot_seqused_k=attn_metadata.decode.dcp_tot_seq_lens, ) if self.need_to_return_lse_for_decode: o, lse = attn_out # FA returns LSE in shape [ H, B ] but DCP wants [ B, H ] return o, lse.transpose(0, 1) # [ H, B ] -> [ B, H ] else: o = attn_out return o, None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/flashinfer_mla.py
vllm/v1/attention/backends/mla/flashinfer_mla.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import ClassVar import torch from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla from vllm.attention.backends.abstract import ( AttentionLayer, AttentionType, MultipleOf, ) from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.platforms.interface import DeviceCapability from vllm.v1.attention.backends.mla.common import ( MLACommonBackend, MLACommonImpl, MLACommonMetadata, MLACommonMetadataBuilder, QueryLenSupport, ) from vllm.v1.attention.backends.utils import AttentionCGSupport, KVCacheLayoutType logger = init_logger(__name__) FLASHINFER_MLA_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024 class FlashInferMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]): _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.UNIFORM class FlashInferMLABackend(MLACommonBackend): supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ "auto", "fp8", "fp8_e4m3", ] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [32, 64] @staticmethod def get_name() -> str: return "FLASHINFER_MLA" @staticmethod def get_impl_cls() -> type["FlashInferMLAImpl"]: return FlashInferMLAImpl @staticmethod def get_builder_cls() -> type["FlashInferMLAMetadataBuilder"]: return FlashInferMLAMetadataBuilder @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return capability.major == 10 @classmethod def get_required_kv_cache_layout(cls) -> "KVCacheLayoutType | None": return "HND" g_fi_workspace = torch.zeros( FLASHINFER_MLA_WORKSPACE_BUFFER_SIZE, dtype=torch.uint8, device="cuda", ) class FlashInferMLAImpl(MLACommonImpl[MLACommonMetadata]): 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments **mla_args, ) -> 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, **mla_args, ) unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap] if any(unsupported_features): raise NotImplementedError( "FlashInferMLAImpl does not support one of the following: " "alibi_slopes, sliding_window, logits_soft_cap" ) if attn_type != AttentionType.DECODER: raise NotImplementedError( "Encoder self-attention and " "encoder/decoder cross-attention " "are not implemented for " "FlashInferMLAImpl" ) self._workspace_buffer = g_fi_workspace self.bmm1_scale: float | None = None self.bmm2_scale: float | None = None def _forward_decode( self, q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], kv_c_and_k_pe_cache: torch.Tensor, attn_metadata: MLACommonMetadata, layer: AttentionLayer, ) -> tuple[torch.Tensor, torch.Tensor | None]: assert kv_c_and_k_pe_cache.numel() > 0 assert attn_metadata.decode is not None if isinstance(q, tuple): q_nope, q_pe = q q = torch.cat([q_nope, q_pe], dim=-1) # trtllm API requires extra dimension q_len_per_request for MTP if attn_metadata.num_decode_tokens % attn_metadata.num_decodes != 0: logger.warning_once( """FlashInferMLAImpl got a query of uneven length. This usually indicates an issue in batch reordering or incorrect setup in dummy_run.""" ) q = q.unsqueeze(1) else: q = q.view(attn_metadata.num_decodes, -1, q.shape[-2], q.shape[-1]) if self.bmm1_scale is None: self.bmm1_scale = layer._q_scale_float * layer._k_scale_float * self.scale if self.bmm2_scale is None: self.bmm2_scale = layer._v_scale_float o = trtllm_batch_decode_with_kv_cache_mla( query=q, kv_cache=kv_c_and_k_pe_cache.unsqueeze(1), workspace_buffer=self._workspace_buffer, qk_nope_head_dim=self.qk_nope_head_dim, kv_lora_rank=self.kv_lora_rank, qk_rope_head_dim=self.qk_rope_head_dim, block_tables=attn_metadata.decode.block_table, seq_lens=attn_metadata.decode.seq_lens, max_seq_len=attn_metadata.max_seq_len, bmm1_scale=self.bmm1_scale, bmm2_scale=self.bmm2_scale, ) # Flatten the output for consistent shape o = o.view(-1, o.shape[-2], o.shape[-1]) # TODO: Return LSE pending support from Flashinfer API: # https://github.com/flashinfer-ai/flashinfer/pull/1566 return o, None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/__init__.py
vllm/v1/attention/backends/mla/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/triton_mla.py
vllm/v1/attention/backends/mla/triton_mla.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import ClassVar import torch from vllm.attention.backends.abstract import ( AttentionLayer, AttentionType, is_quantized_kv_cache, ) from vllm.attention.ops.triton_decode_attention import decode_attention_fwd from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.platforms.interface import DeviceCapability from vllm.v1.attention.backends.mla.common import ( MLACommonBackend, MLACommonImpl, MLACommonMetadata, ) logger = init_logger(__name__) class TritonMLABackend(MLACommonBackend): supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto"] @staticmethod def get_name() -> str: return "TRITON_MLA" @staticmethod def get_impl_cls() -> type["TritonMLAImpl"]: return TritonMLAImpl @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return True class TritonMLAImpl(MLACommonImpl[MLACommonMetadata]): can_return_lse_for_decode: bool = True 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments **mla_args, ) -> 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, **mla_args, ) unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap] if any(unsupported_features): raise NotImplementedError( "TritonMLAImpl does not support one of the following: " "alibi_slopes, sliding_window, logits_soft_cap" ) if attn_type != AttentionType.DECODER: raise NotImplementedError( "Encoder self-attention and " "encoder/decoder cross-attention " "are not implemented for " "TritonMLAImpl" ) if is_quantized_kv_cache(self.kv_cache_dtype): raise NotImplementedError( "TritonMLA V1 with FP8 KV cache not yet supported" ) def _flash_attn_varlen_diff_headdims( self, q, k, v, return_softmax_lse=False, softmax_scale=None, **kwargs ): return super()._flash_attn_varlen_diff_headdims( q, k, v, return_softmax_lse=return_softmax_lse, softmax_scale=softmax_scale, **kwargs, ) def _forward_decode( self, q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], kv_c_and_k_pe_cache: torch.Tensor, attn_metadata: MLACommonMetadata, layer: AttentionLayer, ) -> tuple[torch.Tensor, torch.Tensor | None]: assert kv_c_and_k_pe_cache.numel() > 0 assert attn_metadata.decode is not None if self.kv_cache_dtype.startswith("fp8"): raise NotImplementedError("FP8 Triton MLA not yet supported") if type(q) is tuple: q = torch.cat(q, dim=-1) assert isinstance(q, torch.Tensor) B = q.shape[0] q_num_heads = q.shape[1] o = torch.zeros( B, q_num_heads, self.kv_lora_rank, dtype=q.dtype, device=q.device ) lse = torch.zeros(B, q_num_heads, dtype=q.dtype, device=q.device) # For batch invariance, use only 1 split to ensure deterministic reduction num_kv_splits = 1 if vllm_is_batch_invariant() else 4 # TODO(lucas) Allocate ahead of time attn_logits = torch.empty( ( B, q_num_heads, num_kv_splits, # NOTE(lucas) idk why the +1 is here but sglang has it so we # just mirror that self.kv_lora_rank + 1, ), dtype=torch.float32, device=q.device, ) # Add a head dim of 1 kv_c_and_k_pe_cache = kv_c_and_k_pe_cache.unsqueeze(2) kv_c_cache = kv_c_and_k_pe_cache[..., : self.kv_lora_rank] PAGE_SIZE = kv_c_and_k_pe_cache.size(1) # Run MQA decode_attention_fwd( q, kv_c_and_k_pe_cache, kv_c_cache, o, lse, attn_metadata.decode.block_table, attn_metadata.decode.seq_lens, attn_logits, num_kv_splits, self.scale, PAGE_SIZE, ) return o, lse
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/attention/backends/mla/cutlass_mla.py
vllm/v1/attention/backends/mla/cutlass_mla.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os from typing import ClassVar import torch import vllm._custom_ops as ops from vllm.attention.backends.abstract import ( AttentionLayer, AttentionType, MultipleOf, is_quantized_kv_cache, ) from vllm.config.cache import CacheDType from vllm.logger import init_logger from vllm.platforms.interface import DeviceCapability from vllm.v1.attention.backends.mla.common import ( MLACommonBackend, MLACommonImpl, MLACommonMetadata, MLACommonMetadataBuilder, ) from vllm.v1.attention.backends.utils import AttentionCGSupport logger = init_logger(__name__) class CutlassMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]): # enable full CUDA Graph support for decode-only capture _cudagraph_support: ClassVar[AttentionCGSupport] = ( AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE ) class CutlassMLABackend(MLACommonBackend): supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ "auto", "fp8", "fp8_e4m3", ] @staticmethod def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [128] @staticmethod def get_name() -> str: return "CUTLASS_MLA" @staticmethod def get_impl_cls() -> type["CutlassMLAImpl"]: return CutlassMLAImpl @staticmethod def get_builder_cls() -> type["CutlassMLAMetadataBuilder"]: return CutlassMLAMetadataBuilder @classmethod def supports_compute_capability(cls, capability: DeviceCapability) -> bool: return capability.major == 10 class SM100Workspace: def __init__(self, initial_workspace_size): self._workspace_buf = torch.empty( initial_workspace_size, device="cuda", dtype=torch.uint8 ) self._block_size = 128 # Forced to 128 # Pre-compute sm_count to avoid recomputing it. Use device 0 as a proxy # (assumes all devices are similar) properties = torch.cuda.get_device_properties(torch.device("cuda:0")) self._sm_count = properties.multi_processor_count def get_buf(self): return self._workspace_buf def ensure_size(self, attn_metadata: MLACommonMetadata, num_kv_splits: int): batch_size = attn_metadata.num_reqs max_seq_len = attn_metadata.max_query_len workspace_size = ops.sm100_cutlass_mla_get_workspace_size( max_seq_len * self._block_size, batch_size, self._sm_count, num_kv_splits=num_kv_splits, ) if self._workspace_buf.shape[0] < workspace_size: self._workspace_buf.resize_(workspace_size) g_sm100_workspace = SM100Workspace(128 * 1024 * 1024) # 128MB MAX_HEADS = 128 class CutlassMLAImpl(MLACommonImpl[MLACommonMetadata]): can_return_lse_for_decode: bool = True 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, attn_type: str, kv_sharing_target_layer_name: str | None, # MLA Specific Arguments **mla_args, ) -> 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, q_pad_num_heads=MAX_HEADS, **mla_args, ) unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap] if any(unsupported_features): raise NotImplementedError( "CutlassMLAImpl does not support one of the following: " "alibi_slopes, sliding_window, logits_soft_cap" ) if attn_type != AttentionType.DECODER: raise NotImplementedError( "Encoder self-attention and " "encoder/decoder cross-attention " "are not implemented for " "CutlassMLAImpl" ) # TODO: Currently, num_kv_splits is limited to 16 to avoid hanging # issues. In case the code hangs, use: # FORCE_NUM_KV_SPLITS=1 force_num_kv_splits = os.environ.get("FORCE_NUM_KV_SPLITS", None) if force_num_kv_splits: logger.debug_once("Forcing num_kv_splits to %d", int(force_num_kv_splits)) self._num_kv_splits = int(force_num_kv_splits) else: self._num_kv_splits = -1 # => Auto-detect # Share workspace buffer across all executions self._workspace = g_sm100_workspace def _sm100_cutlass_mla_decode( self, q_nope: torch.Tensor, q_pe: torch.Tensor, kv_c_and_k_pe_cache: torch.Tensor, seq_lens: torch.Tensor, page_table: torch.Tensor, workspace: torch.Tensor, sm_scale: float, num_kv_splits: int, ) -> tuple[torch.Tensor, torch.Tensor]: assert q_nope.ndim == 3, f"q_nope must be a 3D tensor, but got {q_nope.ndim}" assert q_pe.ndim == 3, f"q_pe must be a 3D tensor, but got {q_pe.ndim}" assert kv_c_and_k_pe_cache.ndim == 3, ( "kv_c_and_k_pe_cache must be a 3D tensor, but got {}".format( kv_c_and_k_pe_cache.ndim ) ) B_q, H, D_q_nope = q_nope.shape B_q_2, H_2, D_q_pe = q_pe.shape assert (B_q == B_q_2) and (H == H_2) _, PAGE_SIZE, D_ckv = kv_c_and_k_pe_cache.shape D_latent = 512 D_rope = 64 assert D_q_nope == D_latent assert D_q_pe == D_rope assert D_ckv == D_latent + D_rope MAX_HEADS = 128 assert H <= MAX_HEADS, f"H must be <= {MAX_HEADS}, but got {H}" assert len(page_table.shape) == 2 B_block_table, block_num = page_table.shape assert B_block_table == B_q assert block_num > 0, f"block num must be greater than 0, got {block_num}" assert block_num % (128 / PAGE_SIZE) == 0 assert q_nope.dtype in (torch.float16, torch.bfloat16, torch.float8_e4m3fn), ( f"q_nope.dtype needs to be fp16 or bf16 or e4m3 but got {q_nope.dtype}." ) assert q_nope.dtype == q_pe.dtype == kv_c_and_k_pe_cache.dtype assert seq_lens.dtype == torch.int32, ( f"seq_lens.dtype needs to be int32 but got {seq_lens.dtype}." ) assert page_table.dtype == torch.int32, ( f"page_table.dtype needs to be int32 but got {page_table.dtype}." ) dtype = ( torch.bfloat16 if is_quantized_kv_cache(self.kv_cache_dtype) else q_nope.dtype ) out = q_nope.new_empty((B_q, MAX_HEADS, D_latent), dtype=dtype) lse = ( torch.empty((B_q, MAX_HEADS), dtype=torch.float32, device=q_nope.device) if self.need_to_return_lse_for_decode else torch.Tensor() ) ops.sm100_cutlass_mla_decode( out, lse, q_nope, q_pe, kv_c_and_k_pe_cache, seq_lens, page_table, workspace, sm_scale, num_kv_splits, ) if H < MAX_HEADS: # Extract the subsets of the outputs lse = lse[:, :H] if self.need_to_return_lse_for_decode else lse out = out[:, :H] return out, lse def _forward_decode( self, q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], kv_c_and_k_pe_cache: torch.Tensor, attn_metadata: MLACommonMetadata, layer: AttentionLayer, ) -> tuple[torch.Tensor, torch.Tensor | None]: assert kv_c_and_k_pe_cache.numel() > 0 assert attn_metadata.decode is not None if type(q) is tuple: q_nope, q_pe = q else: q_nope, q_pe = torch.split( q, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) # Adjust workspace size (if necessary) self._workspace.ensure_size(attn_metadata, self._num_kv_splits) # Run MLA o, lse = self._sm100_cutlass_mla_decode( q_nope, q_pe, kv_c_and_k_pe_cache, attn_metadata.decode.seq_lens, attn_metadata.decode.block_table, self._workspace.get_buf(), self.scale, self._num_kv_splits, ) return o, (lse if self.need_to_return_lse_for_decode else None)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu_model_runner.py
vllm/v1/worker/gpu_model_runner.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import functools import gc import itertools import time from collections import defaultdict from collections.abc import Iterator, Sequence from contextlib import contextmanager from copy import copy, deepcopy from functools import reduce from itertools import product from typing import TYPE_CHECKING, Any, NamedTuple, TypeAlias, cast import numpy as np import torch import torch.distributed import torch.nn as nn from tqdm import tqdm import vllm.envs as envs from vllm.attention.backends.abstract import ( AttentionBackend, AttentionMetadata, AttentionType, MultipleOf, ) from vllm.attention.layer import Attention, MLAAttention from vllm.compilation.counter import compilation_counter from vllm.compilation.cuda_graph import CUDAGraphStat, CUDAGraphWrapper from vllm.compilation.monitor import set_cudagraph_capturing_enabled from vllm.config import ( CompilationMode, CUDAGraphMode, VllmConfig, get_layers_from_vllm_config, update_config, ) from vllm.distributed.ec_transfer import get_ec_transfer, has_ec_transfer from vllm.distributed.eplb.eplb_state import EplbState from vllm.distributed.kv_transfer import get_kv_transfer_group, has_kv_transfer_group from vllm.distributed.kv_transfer.kv_connector.utils import copy_kv_blocks from vllm.distributed.parallel_state import ( get_dcp_group, get_pp_group, get_tp_group, graph_capture, is_global_first_rank, prepare_communication_buffer_for_model, ) from vllm.forward_context import ( BatchDescriptor, set_forward_context, ) from vllm.logger import init_logger from vllm.lora.layers import LoRAMapping, LoRAMappingType from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase from vllm.model_executor.layers.rotary_embedding import ( MRotaryEmbedding, XDRotaryEmbedding, ) from vllm.model_executor.model_loader import TensorizerLoader, get_model_loader from vllm.model_executor.models.interfaces import ( MultiModalEmbeddings, SupportsMRoPE, SupportsMultiModal, SupportsXDRoPE, is_mixture_of_experts, supports_eagle3, supports_mm_encoder_only, supports_mrope, supports_multimodal_pruning, supports_transcription, supports_xdrope, ) from vllm.model_executor.models.interfaces_base import ( VllmModelForPooling, is_pooling_model, is_text_generation_model, ) from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.inputs import ( BatchedTensorInputs, MultiModalKwargsItem, PlaceholderRange, ) from vllm.multimodal.utils import group_mm_kwargs_by_modality from vllm.pooling_params import PoolingParams from vllm.sampling_params import SamplingType from vllm.sequence import IntermediateTensors from vllm.tasks import GenerationTask, PoolingTask, SupportedTask from vllm.utils import length_from_prompt_token_ids_or_embeds from vllm.utils.jsontree import json_map_leaves from vllm.utils.math_utils import cdiv, round_up from vllm.utils.mem_constants import GiB_bytes from vllm.utils.mem_utils import DeviceMemoryProfiler from vllm.utils.nvtx_pytorch_hooks import PytHooks from vllm.utils.platform_utils import is_pin_memory_available from vllm.utils.torch_utils import ( get_dtype_size, kv_cache_dtype_str_to_dtype, supports_dynamo, ) from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadataBuilder from vllm.v1.attention.backends.utils import ( AttentionCGSupport, AttentionMetadataBuilder, CommonAttentionMetadata, create_fast_prefill_custom_backend, get_dcp_local_seq_lens, reorder_batch_to_split_decodes_and_prefills, split_attn_metadata, ) from vllm.v1.cudagraph_dispatcher import CudagraphDispatcher from vllm.v1.kv_cache_interface import ( AttentionSpec, ChunkedLocalAttentionSpec, CrossAttentionSpec, EncoderOnlyAttentionSpec, FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec, KVCacheSpec, MambaSpec, SlidingWindowSpec, UniformTypeKVCacheSpecs, ) from vllm.v1.outputs import ( EMPTY_MODEL_RUNNER_OUTPUT, AsyncModelRunnerOutput, DraftTokenIds, ECConnectorOutput, KVConnectorOutput, LogprobsLists, LogprobsTensors, ModelRunnerOutput, PoolerOutput, SamplerOutput, make_empty_encoder_model_runner_output, ) from vllm.v1.pool.metadata import PoolingMetadata, PoolingStates from vllm.v1.sample.logits_processor import LogitsProcessors, build_logitsprocs from vllm.v1.sample.logits_processor.interface import LogitsProcessor from vllm.v1.sample.metadata import SamplingMetadata from vllm.v1.sample.rejection_sampler import RejectionSampler from vllm.v1.sample.sampler import Sampler from vllm.v1.spec_decode.eagle import EagleProposer from vllm.v1.spec_decode.medusa import MedusaProposer from vllm.v1.spec_decode.metadata import SpecDecodeMetadata from vllm.v1.spec_decode.ngram_proposer import NgramProposer from vllm.v1.spec_decode.suffix_decoding import SuffixDecodingProposer from vllm.v1.structured_output.utils import apply_grammar_bitmask from vllm.v1.utils import CpuGpuBuffer, record_function_or_nullcontext from vllm.v1.worker.cp_utils import check_attention_cp_compatibility from vllm.v1.worker.dp_utils import coordinate_batch_across_dp from vllm.v1.worker.ec_connector_model_runner_mixin import ECConnectorModelRunnerMixin from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch from vllm.v1.worker.gpu_ubatch_wrapper import UBatchWrapper from vllm.v1.worker.kv_connector_model_runner_mixin import KVConnectorModelRunnerMixin from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin from vllm.v1.worker.ubatch_utils import ( UBatchSlices, check_ubatch_thresholds, maybe_create_ubatch_slices, ) from vllm.v1.worker.utils import is_residual_scattered_for_sp from vllm.v1.worker.workspace import lock_workspace from .utils import ( AttentionGroup, MultiModalBudget, add_kv_sharing_layers_to_kv_cache_groups, bind_kv_cache, sanity_check_mm_encoder_outputs, ) if TYPE_CHECKING: from vllm.model_executor.model_loader.tensorizer import TensorizerConfig from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput logger = init_logger(__name__) AttnMetadataDict: TypeAlias = dict[str, AttentionMetadata] # list when ubatching is enabled PerLayerAttnMetadata: TypeAlias = list[AttnMetadataDict] | AttnMetadataDict # Wrapper for ModelRunnerOutput to support overlapped execution. class AsyncGPUModelRunnerOutput(AsyncModelRunnerOutput): def __init__( self, model_runner_output: ModelRunnerOutput, sampled_token_ids: torch.Tensor, logprobs_tensors: LogprobsTensors | None, invalid_req_indices: list[int], async_output_copy_stream: torch.cuda.Stream, vocab_size: int, ): self._model_runner_output = model_runner_output self._invalid_req_indices = invalid_req_indices # Event on the copy stream so we can synchronize the non-blocking copy. self.async_copy_ready_event = torch.Event() # Keep a reference to the device tensor to avoid it being # deallocated until we finish copying it to the host. self._sampled_token_ids = sampled_token_ids self.vocab_size = vocab_size self._logprobs_tensors = logprobs_tensors # Initiate the copy on a separate stream, but do not synchronize it. default_stream = torch.cuda.current_stream() with torch.cuda.stream(async_output_copy_stream): async_output_copy_stream.wait_stream(default_stream) self.sampled_token_ids_cpu = self._sampled_token_ids.to( "cpu", non_blocking=True ) self._logprobs_tensors_cpu = ( self._logprobs_tensors.to_cpu_nonblocking() if self._logprobs_tensors else None ) self.async_copy_ready_event.record() def get_output(self) -> ModelRunnerOutput: """Copy the device tensors to the host and return a ModelRunnerOutput. This function blocks until the copy is finished. """ max_gen_len = self.sampled_token_ids_cpu.shape[-1] self.async_copy_ready_event.synchronize() # Release the device tensors once the copy has completed. del self._logprobs_tensors del self._sampled_token_ids if max_gen_len == 1: valid_sampled_token_ids = self.sampled_token_ids_cpu.tolist() for i in self._invalid_req_indices: valid_sampled_token_ids[i].clear() cu_num_tokens = None else: valid_sampled_token_ids, cu_num_tokens = RejectionSampler.parse_output( self.sampled_token_ids_cpu, self.vocab_size, self._invalid_req_indices, return_cu_num_tokens=self._logprobs_tensors_cpu is not None, ) output = self._model_runner_output output.sampled_token_ids = valid_sampled_token_ids if self._logprobs_tensors_cpu: output.logprobs = self._logprobs_tensors_cpu.tolists(cu_num_tokens) return output class AsyncGPUPoolingModelRunnerOutput(AsyncModelRunnerOutput): def __init__( self, model_runner_output: ModelRunnerOutput, raw_pooler_output: PoolerOutput, finished_mask: list[bool], async_output_copy_stream: torch.cuda.Stream, ): self._model_runner_output = model_runner_output self._finished_mask = finished_mask # Event on the copy stream so we can synchronize the non-blocking copy. self.async_copy_ready_event = torch.Event() # Keep a reference to the device tensors to avoid them being # deallocated until we finish copying it to the host. self._raw_pooler_output = raw_pooler_output # Initiate the copy on a separate stream, but do not synchronize it. default_stream = torch.cuda.current_stream() with torch.cuda.stream(async_output_copy_stream): async_output_copy_stream.wait_stream(default_stream) self._raw_pooler_output_cpu = json_map_leaves( lambda x: None if x is None else x.to("cpu", non_blocking=True), self._raw_pooler_output, ) self.async_copy_ready_event.record() def get_output(self) -> ModelRunnerOutput: """Copy the device tensors to the host and return a ModelRunnerOutput. This function blocks until the copy is finished. """ self.async_copy_ready_event.synchronize() # Release the device tensors once the copy has completed. del self._raw_pooler_output self._model_runner_output.pooler_output = [ out if include else None for out, include in zip(self._raw_pooler_output_cpu, self._finished_mask) ] return self._model_runner_output class ExecuteModelState(NamedTuple): """Ephemeral cached state transferred between execute_model() and sample_tokens(), after execute_model() returns None.""" scheduler_output: "SchedulerOutput" logits: torch.Tensor spec_decode_metadata: SpecDecodeMetadata | None spec_decode_common_attn_metadata: CommonAttentionMetadata | None hidden_states: torch.Tensor sample_hidden_states: torch.Tensor aux_hidden_states: list[torch.Tensor] | None ec_connector_output: ECConnectorOutput | None cudagraph_stats: CUDAGraphStat | None class GPUModelRunner( LoRAModelRunnerMixin, KVConnectorModelRunnerMixin, ECConnectorModelRunnerMixin ): def __init__( self, vllm_config: VllmConfig, device: torch.device, ): self.vllm_config = vllm_config self.model_config = vllm_config.model_config self.cache_config = vllm_config.cache_config self.compilation_config = vllm_config.compilation_config self.lora_config = vllm_config.lora_config self.load_config = vllm_config.load_config self.parallel_config = vllm_config.parallel_config self.scheduler_config = vllm_config.scheduler_config self.speculative_config = vllm_config.speculative_config self.observability_config = vllm_config.observability_config from vllm.model_executor.models.utils import set_cpu_offload_max_bytes set_cpu_offload_max_bytes(int(self.cache_config.cpu_offload_gb * 1024**3)) model_config = self.model_config cache_config = self.cache_config scheduler_config = self.scheduler_config parallel_config = self.parallel_config self.device = device self.pin_memory = is_pin_memory_available() self.dtype = self.model_config.dtype self.kv_cache_dtype = kv_cache_dtype_str_to_dtype( cache_config.cache_dtype, self.model_config ) self.is_pooling_model = model_config.runner_type == "pooling" self.enable_prompt_embeds = model_config.enable_prompt_embeds self.is_multimodal_raw_input_only_model = ( model_config.is_multimodal_raw_input_only_model ) # This will be overridden in load_model() self.is_multimodal_pruning_enabled = False self.max_model_len = model_config.max_model_len # Always set to false after the first forward pass self.calculate_kv_scales = self.cache_config.calculate_kv_scales self.dcp_world_size = self.parallel_config.decode_context_parallel_size self.dcp_rank = 0 if self.dcp_world_size <= 1 else get_dcp_group().rank_in_group self.max_num_tokens = scheduler_config.max_num_batched_tokens self.max_num_reqs = scheduler_config.max_num_seqs # Broadcast PP output for external_launcher (torchrun) # to make sure we are synced across pp ranks # TODO: Support overlapping mirco-batches # https://github.com/vllm-project/vllm/issues/18019 self.broadcast_pp_output = ( self.parallel_config.distributed_executor_backend == "external_launcher" and len(get_pp_group().ranks) > 1 ) # Model-related. self.num_query_heads = model_config.get_num_attention_heads(parallel_config) self.inputs_embeds_size = model_config.get_inputs_embeds_size() self.attention_chunk_size = model_config.attention_chunk_size # Only relevant for models using ALiBi (e.g, MPT) self.use_alibi = model_config.uses_alibi self.cascade_attn_enabled = not self.model_config.disable_cascade_attn self.is_mm_prefix_lm = self.model_config.is_mm_prefix_lm # Multi-modal data support self.mm_registry = MULTIMODAL_REGISTRY self.uses_mrope = model_config.uses_mrope self.uses_xdrope_dim = model_config.uses_xdrope_dim self.supports_mm_inputs = self.mm_registry.supports_multimodal_inputs( model_config ) if self.model_config.is_encoder_decoder: # Maximum length of the encoder input, only for encoder-decoder # models. self.max_encoder_len = scheduler_config.max_num_encoder_input_tokens else: self.max_encoder_len = 0 # Sampler self.sampler = Sampler(logprobs_mode=self.model_config.logprobs_mode) self.eplb_state: EplbState | None = None """ State of the expert parallelism load balancer. Will be lazily initialized when the model is loaded. """ # Lazy initializations # self.model: nn.Module # Set after load_model # Initialize in initialize_kv_cache self.kv_caches: list[torch.Tensor] = [] # Initialize in initialize_kv_cache_tensors self.cross_layers_kv_cache: torch.Tensor | None = None self.cross_layers_attn_backend: type[AttentionBackend] | None = None # indexes: [kv_cache_group_id][attn_group] self.attn_groups: list[list[AttentionGroup]] = [] # self.kv_cache_config: KVCacheConfig # mm_hash -> encoder_output self.encoder_cache: dict[str, torch.Tensor] = {} self.use_aux_hidden_state_outputs = False # Set up speculative decoding. # NOTE(Jiayi): currently we put the entire draft model on # the last PP rank. This is not ideal if there are many # layers in the draft model. if self.speculative_config and get_pp_group().is_last_rank: self.drafter: ( NgramProposer | SuffixDecodingProposer | EagleProposer | MedusaProposer ) if self.speculative_config.method == "ngram": self.drafter = NgramProposer(self.vllm_config) elif self.speculative_config.method == "suffix": self.drafter = SuffixDecodingProposer(self.vllm_config) elif self.speculative_config.use_eagle(): self.drafter = EagleProposer(self.vllm_config, self.device, self) if self.speculative_config.method == "eagle3": self.use_aux_hidden_state_outputs = ( self.drafter.eagle3_use_aux_hidden_state ) elif self.speculative_config.method == "medusa": self.drafter = MedusaProposer( vllm_config=self.vllm_config, device=self.device ) else: raise ValueError( "Unknown speculative decoding method: " f"{self.speculative_config.method}" ) self.rejection_sampler = RejectionSampler(self.sampler) self.num_spec_tokens = 0 if self.speculative_config: self.num_spec_tokens = self.speculative_config.num_speculative_tokens # Request states. self.requests: dict[str, CachedRequestState] = {} # NOTE(rob): num_prompt_logprobs only includes reqs # that are currently in the prefill phase. self.num_prompt_logprobs: dict[str, int] = {} self.comm_stream = torch.cuda.Stream() # Input Batch # NOTE(Chen): Ideally, we should initialize the input batch inside # `initialize_kv_cache` based on the kv cache config. However, as in # https://github.com/vllm-project/vllm/pull/18298, due to some unknown # reasons, we have to initialize the input batch before `load_model`, # quantization + weight offloading will fail otherwise. As a temporary # solution, we initialize the input batch here, and re-initialize it # in `initialize_kv_cache` if the block_sizes here is different from # the block_sizes in the kv cache config. logits_processors = model_config.logits_processors custom_logitsprocs: Sequence[str | type[LogitsProcessor]] = ( tuple(logits_processors) if logits_processors is not None else () ) self.input_batch = InputBatch( max_num_reqs=self.max_num_reqs, # We need to use the encoder length for encoder-decoer # because of KV cache for cross-attention. max_model_len=max(self.max_model_len, self.max_encoder_len), max_num_batched_tokens=self.max_num_tokens, device=self.device, pin_memory=self.pin_memory, vocab_size=self.model_config.get_vocab_size(), block_sizes=[self.cache_config.block_size], kernel_block_sizes=[self.cache_config.block_size], is_spec_decode=bool(self.vllm_config.speculative_config), logitsprocs=build_logitsprocs( self.vllm_config, self.device, self.pin_memory, self.is_pooling_model, custom_logitsprocs, ), # We currently don't know whether a particular custom logits processor # uses output token ids so we set this conservatively. logitsprocs_need_output_token_ids=bool(custom_logitsprocs), is_pooling_model=self.is_pooling_model, cp_kv_cache_interleave_size=self.parallel_config.cp_kv_cache_interleave_size, ) self.use_async_scheduling = self.scheduler_config.async_scheduling # Separate cuda stream for overlapping transfer of sampled token ids from # GPU to CPU when async scheduling is enabled. self.async_output_copy_stream: torch.cuda.Stream | None = None # cuda event to synchronize use of reused CPU tensors between steps # when async scheduling is enabled. self.prepare_inputs_event: torch.Event | None = None if self.use_async_scheduling: self.async_output_copy_stream = torch.cuda.Stream() self.prepare_inputs_event = torch.Event() # self.cudagraph_batch_sizes sorts in ascending order. if ( self.compilation_config.cudagraph_capture_sizes and self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE ): self.cudagraph_batch_sizes = sorted( self.compilation_config.cudagraph_capture_sizes ) # Cache the device properties. self._init_device_properties() # Persistent buffers for CUDA graphs. self.input_ids = self._make_buffer(self.max_num_tokens, dtype=torch.int32) self.positions = self._make_buffer(self.max_num_tokens, dtype=torch.int64) self.query_start_loc = self._make_buffer( self.max_num_reqs + 1, dtype=torch.int32 ) self.seq_lens = self._make_buffer(self.max_num_reqs, dtype=torch.int32) self.encoder_seq_lens = self._make_buffer(self.max_num_reqs, dtype=torch.int32) if self.dcp_world_size > 1: self.dcp_local_seq_lens = self._make_buffer( self.max_num_reqs, dtype=torch.int32 ) # Because inputs_embeds may be bfloat16 and we don't need a numpy # version of this tensor, avoid a RuntimeError by not creating a # numpy buffer. self.inputs_embeds = self._make_buffer( self.max_num_tokens, self.inputs_embeds_size, dtype=self.dtype, numpy=False ) self.is_token_ids = self._make_buffer(self.max_num_tokens, dtype=torch.bool) self.discard_request_mask = self._make_buffer( self.max_num_reqs, dtype=torch.bool ) self.num_decode_draft_tokens = self._make_buffer( self.max_num_reqs, dtype=torch.int32 ) self.num_accepted_tokens = self._make_buffer( self.max_num_reqs, dtype=torch.int64 ) # Only relevant for multimodal models if self.supports_mm_inputs: self.is_mm_embed = self._make_buffer(self.max_num_tokens, dtype=torch.bool) # Only relevant for models using M-RoPE (e.g, Qwen2-VL) if self.uses_mrope: # NOTE: `mrope_positions` is implemented with one additional dummy # position on purpose to make it non-contiguous so that it can work # with torch compile. # See detailed explanation in https://github.com/vllm-project/vllm/pull/12128#discussion_r1926431923 # NOTE: When M-RoPE is enabled, position ids are 3D regardless of # the modality of inputs. For text-only inputs, each dimension has # identical position IDs, making M-RoPE functionally equivalent to # 1D-RoPE. # See page 5 of https://arxiv.org/abs/2409.12191 self.mrope_positions = self._make_buffer( (3, self.max_num_tokens + 1), dtype=torch.int64 ) # Only relevant for models using XD-RoPE (e.g, HunYuan-VL) if self.uses_xdrope_dim > 0: # Similar to mrope but use assigned dimension number for RoPE, 4 as default. self.xdrope_positions = self._make_buffer( (self.uses_xdrope_dim, self.max_num_tokens + 1), dtype=torch.int64 ) # None in the first PP rank. The rest are set after load_model. self.intermediate_tensors: IntermediateTensors | None = None # OPTIMIZATION: Cache the tensors rather than creating them every step. # Keep in int64 to avoid overflow with long context self.arange_np = np.arange( max(self.max_num_reqs + 1, self.max_model_len, self.max_num_tokens), dtype=np.int64, ) # Layer pairings for cross-layer KV sharing. # If an Attention layer `layer_name` is in the keys of this dict, it # means this layer will perform attention using the keys and values # from the KV cache of `shared_kv_cache_layers[layer_name]`. self.shared_kv_cache_layers: dict[str, str] = {} self.kv_sharing_fast_prefill_eligible_layers: set[str] = set() self.kv_sharing_fast_prefill_logits_indices = None if self.cache_config.kv_sharing_fast_prefill: self.kv_sharing_fast_prefill_logits_indices = torch.zeros( self.max_num_tokens, dtype=torch.int32, device=self.device ) self.uniform_decode_query_len = 1 + self.num_spec_tokens # Cudagraph dispatcher for runtime cudagraph dispatching. self.cudagraph_dispatcher = CudagraphDispatcher(self.vllm_config) self.mm_budget = ( MultiModalBudget( self.model_config, self.scheduler_config, self.mm_registry, ) if self.supports_mm_inputs else None ) self.reorder_batch_threshold: int | None = None # Attention layers that are only in the KVCacheConfig of the runner # (e.g., KV sharing, encoder-only attention), but not in the # KVCacheConfig of the scheduler. self.runner_only_attn_layers: set[str] = set() # Cached outputs. self._draft_token_ids: list[list[int]] | torch.Tensor | None = None self.transfer_event = torch.Event() self.sampled_token_ids_pinned_cpu = torch.empty( (self.max_num_reqs, 1), dtype=torch.int64, device="cpu", pin_memory=self.pin_memory, ) # Pre-allocated tensor for copying valid sampled token counts to CPU, # with dedicated stream for overlapping and event for coordination. self.valid_sampled_token_count_event: torch.Event | None = None self.valid_sampled_token_count_copy_stream: torch.cuda.Stream | None = None if self.use_async_scheduling and self.num_spec_tokens: self.valid_sampled_token_count_event = torch.Event() self.valid_sampled_token_count_copy_stream = torch.cuda.Stream() self.valid_sampled_token_count_cpu = torch.empty( self.max_num_reqs, dtype=torch.int64, device="cpu", pin_memory=self.pin_memory, ) # Ephemeral state transferred between execute_model() and sample_tokens(). self.execute_model_state: ExecuteModelState | None = None self.kv_connector_output: KVConnectorOutput | None = None self.layerwise_nvtx_hooks_registered = False def reset_mm_cache(self) -> None: if self.mm_budget: self.mm_budget.reset_cache() @torch.inference_mode() def init_fp8_kv_scales(self) -> None: """ Re-initialize the KV cache and FP8 scales after waking from sleep. 1. Zero out the KV cache tensors to remove garbage data from re-allocation. 2. Reset Attention layer scaling factors (_k_scale, _v_scale) to 1.0. If these are left at 0.0 (default after wake_up), all KV cache values become effectively zero, causing gibberish output. """ if not self.cache_config.cache_dtype.startswith("fp8"): return kv_caches = getattr(self, "kv_caches", []) for cache_tensor in kv_caches: if cache_tensor is not None: cache_tensor.zero_() k_attr_names = ("_k_scale", "k_scale") v_attr_names = ("_v_scale", "v_scale") attn_layers = self.compilation_config.static_forward_context for name, module in attn_layers.items(): if isinstance(module, (Attention, MLAAttention)): # TODO: Generally, scale is 1.0 if user uses on-the-fly fp8 # kvcache quant. However, to get better accuracy, compression # frameworks like llm-compressors allow users to tune the # scale. We may need to restore the specific calibrated scales # here in the future. k_scale_val, v_scale_val = 1.0, 1.0 # Processing K Scale for attr in k_attr_names: if hasattr(module, attr): param = getattr(module, attr) if isinstance(param, torch.Tensor): param.fill_(k_scale_val) # Processing V Scale for attr in v_attr_names: if hasattr(module, attr): param = getattr(module, attr) if isinstance(param, torch.Tensor): param.fill_(v_scale_val) def _get_positions(self, num_tokens: Any): if isinstance(num_tokens, int): if self.uses_mrope: return self.mrope_positions.gpu[:, :num_tokens] if self.uses_xdrope_dim > 0: return self.xdrope_positions.gpu[:, :num_tokens] return self.positions.gpu[:num_tokens] else: if self.uses_mrope: return self.mrope_positions.gpu[:, num_tokens] if self.uses_xdrope_dim > 0: return self.xdrope_positions.gpu[:, num_tokens] return self.positions.gpu[num_tokens] def _make_buffer( self, *size: int | torch.SymInt, dtype: torch.dtype, numpy: bool = True ) -> CpuGpuBuffer: return CpuGpuBuffer( *size, dtype=dtype, device=self.device, pin_memory=self.pin_memory, with_numpy=numpy, ) def _init_model_kwargs(self): model_kwargs = dict[str, Any]() if not self.is_pooling_model: return model_kwargs num_reqs = self.input_batch.num_reqs pooling_params = self.input_batch.get_pooling_params() token_type_id_requests = dict[int, Any]() for i, param in enumerate(pooling_params): if ( param.extra_kwargs is not None and (token_types := param.extra_kwargs.get("compressed_token_type_ids")) is not None ): token_type_id_requests[i] = token_types if len(token_type_id_requests) == 0: return model_kwargs seq_lens = self.seq_lens.gpu[:num_reqs] token_type_ids = [] for i in range(num_reqs): pos = token_type_id_requests.get(i, seq_lens[i]) ids = (torch.arange(seq_lens[i]) >= pos).int() token_type_ids.append(ids) model_kwargs["token_type_ids"] = torch.concat(token_type_ids).to( device=self.device ) return model_kwargs def _may_reorder_batch(self, scheduler_output: "SchedulerOutput") -> None: """ Update the order of requests in the batch based on the attention backend's needs. For example, some attention backends (namely MLA) may want to separate requests based on if the attention computation will be compute-bound or memory-bound. Args: scheduler_output: The scheduler output. """ # Attention free models have zero kv_cache_goups, however models # like Mamba are also attention free but use the kv_cache for # keeping its internal state. This is why we check the number # of kv_cache groups instead of solely checking # for self.model_config.is_attention_free. if len(self.kv_cache_config.kv_cache_groups) == 0: return if self.reorder_batch_threshold is not None: reorder_batch_to_split_decodes_and_prefills( self.input_batch, scheduler_output, decode_threshold=self.reorder_batch_threshold, ) # Note: used for model runner override. def _init_device_properties(self) -> None: """Initialize attributes from torch.cuda.get_device_properties""" self.device_properties = torch.cuda.get_device_properties(self.device)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/tpu_worker.py
vllm/v1/worker/tpu_worker.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """A TPU worker class.""" import os from collections.abc import Callable from typing import Any, TypeVar import torch import torch.nn as nn import vllm.envs as envs from vllm.config import VllmConfig, set_current_vllm_config from vllm.distributed import ( ensure_model_parallel_initialized, init_distributed_environment, ) from vllm.distributed.kv_transfer import ( ensure_kv_transfer_initialized, ) from vllm.logger import init_logger from vllm.lora.request import LoRARequest from vllm.model_executor import set_random_seed from vllm.platforms import current_platform from vllm.platforms.tpu import USE_TPU_INFERENCE from vllm.tasks import SupportedTask from vllm.utils.math_utils import cdiv from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheConfig, KVCacheSpec from vllm.v1.outputs import ModelRunnerOutput from vllm.v1.utils import report_usage_stats from vllm.v1.worker.utils import bind_kv_cache logger = init_logger(__name__) _R = TypeVar("_R") if not USE_TPU_INFERENCE: logger.info("tpu_inference not found, using vLLM's TPUWorker.") import torch_xla.core.xla_model as xm import torch_xla.debug.profiler as xp import torch_xla.runtime as xr from vllm.v1.attention.backends.pallas import TPU_HEAD_SIZE_ALIGNMENT from vllm.v1.worker.tpu_model_runner import TPUModelRunner class TPUWorker: def __init__( self, vllm_config: VllmConfig, local_rank: int, rank: int, distributed_init_method: str, is_driver_worker: bool = False, ): self.is_driver_worker = is_driver_worker self.vllm_config = vllm_config self.model_config = vllm_config.model_config self.cache_config = vllm_config.cache_config self.lora_config = vllm_config.lora_config self.load_config = vllm_config.load_config self.parallel_config = vllm_config.parallel_config self.use_spmd = envs.VLLM_XLA_USE_SPMD self.original_parallel_config = None if self.use_spmd: # Under SPMD mode, distributed env is initialized as if there is # only one worker/device. self.original_parallel_config = self.parallel_config self.parallel_config.tensor_parallel_size = 1 self.parallel_config.pipeline_parallel_size = 1 self.parallel_config.world_size = 1 self.scheduler_config = vllm_config.scheduler_config self.device_config = vllm_config.device_config self.speculative_config = vllm_config.speculative_config self.observability_config = vllm_config.observability_config self.parallel_config.rank = rank self.local_rank = local_rank self.rank = rank self.distributed_init_method = distributed_init_method if self.cache_config.cache_dtype == "auto": self.cache_dtype = self.model_config.dtype else: self.cache_dtype = STR_DTYPE_TO_TORCH_DTYPE[self.cache_config.cache_dtype] if self.model_config.trust_remote_code: # note: lazy import to avoid importing torch before initializing from vllm.utils.import_utils import init_cached_hf_modules init_cached_hf_modules() # Delay profiler initialization to the start of the profiling. # This is because in vLLM V1, MP runtime is initialized before the # TPU Worker is initialized. The profiler server needs to start after # MP runtime is initialized. self.profiler = None self.profile_dir = None if vllm_config.profiler_config.profiler == "torch" and self.rank < 1: # For TPU, we can only have 1 active profiler session for 1 profiler # server. So we only profile on rank0. self.profile_dir = vllm_config.profiler_config.torch_profiler_dir logger.info( "Profiling enabled. Traces will be saved to: %s", self.profile_dir ) def initialize_cache(self, num_gpu_blocks: int, num_cpu_blocks: int) -> None: self.cache_config.num_gpu_blocks = num_gpu_blocks self.cache_config.num_cpu_blocks = num_cpu_blocks def init_device(self): os.environ["PJRT_DEVICE"] = "TPU" # Note: Currently the XLA compiler wrongly uses 2D ring strategy on 1D # ring, the xla tpu compiler flag # `xla_tpu_force_1d_allreduce_at_chunk_count` is a temporary solution to # fix this. It will be removed after the bug in XLA compiler is fixed. os.environ["LIBTPU_INIT_ARGS"] = ( os.environ.get("LIBTPU_INIT_ARGS", "") + " --xla_tpu_force_1d_allreduce_at_chunk_count=1" " --xla_jf_conv_input_fusion=False" ) # --xla_jf_conv_input_fusion=False is used to improve the perf of # quantized matmul. torch.set_grad_enabled(False) torch.set_default_dtype(self.model_config.dtype) # Initialize the distributed environment. self._init_tpu_worker_distributed_environment( self.vllm_config, self.rank, self.distributed_init_method, self.local_rank ) # Device initialization should happen after initializing # the distributed runtime. self.device = xm.xla_device() self.device_config.device = self.device # Set random seed. set_random_seed(self.model_config.seed) xm.set_rng_state(self.model_config.seed, self.device) # Increase the cache size limit, which is the maximum number of # dynamo graphs that can be compiled. # TODO (NickLucche) On gsm we compile 80+ graphs. # Re-evaluate limit, with MM we may get close to this limit. torch._dynamo.config.cache_size_limit = 128 # Use persistent cache to avoid XLA recompilation. # NOTE(woosuk): Set per-rank cache path since different ranks # can have slightly different XLA graphs. world_size = self.parallel_config.world_size rank = xr.global_ordinal() # The PyTorch/XLA compilation cache uses the Torch IR to generate keys. # Consequently, changes in optimization flags, which affect compilation # results, don't change the cache key. This can result in the wrong # compilation being used. To prevent this, disabling the XLA compilation # cache during development is recommended.We can disable it by # `export VLLM_XLA_CACHE_PATH=` if envs.VLLM_XLA_CACHE_PATH: per_rank_path = os.path.join( envs.VLLM_XLA_CACHE_PATH, f"tp{world_size}_rank{rank}" ) xr.initialize_cache(per_rank_path, readonly=False) # Init ModelRunner here, so that we have access to self.device. self.model_runner = TPUModelRunner( self.vllm_config, self.device, self.original_parallel_config ) if rank == 0: # If usage stat is enabled, collect relevant info. report_usage_stats(self.vllm_config) def determine_available_memory(self) -> int: kv_caches: dict[str, torch.Tensor] = {} kv_cache_spec = self.model_runner.get_kv_cache_spec() for layer_name, layer_spec in kv_cache_spec.items(): if isinstance(layer_spec, AttentionSpec): dtype = layer_spec.dtype # Use an empty tensor instead of `None` to force Dynamo to pass # it by reference, rather by specializing on the value `None`. tpu_kv_cache = torch.tensor([], dtype=dtype).to(self.device) kv_caches[layer_name] = tpu_kv_cache else: raise NotImplementedError( f"Unsupported KV cache spec '{type(layer_spec)}'" ) runner_kv_caches: list[torch.Tensor] = [] bind_kv_cache( kv_caches, self.vllm_config.compilation_config.static_forward_context, runner_kv_caches, ) # `max_num_tokens >= max_num_batched_tokens` due to padding. with self.model_runner.maybe_setup_dummy_loras(self.lora_config): self.model_runner.profile_run(self.model_runner.max_num_tokens) # Synchronize before measuring the memory usage. xm.wait_device_ops() # During the profiling run, the model runs without KV cache. After # the profiling run, the model always runs with KV cache. Here we clear # the dynamo cache and cached bytecode to ensure the model always has # one compiled bytecode. Having one FX graph/cached bytecode per # compiled model is required for `support_torch_compile` decorator to # skip dynamo guard. with set_current_vllm_config(self.vllm_config): self.model_runner.reset_dynamo_cache() # Get the maximum amount of memory used by the model weights and # intermediate activations. if self.use_spmd: # This is a workaround for the TPU SPMD mode. The get_memory_info # API doesn't work with SPMD mode in PyTorch/XLA. # TODO: use xm.get_memory_info for SPMD once it's supported in # PyTorch/XLA. import tpu_info chip_type, _ = tpu_info.device.get_local_chips() device_usage = tpu_info.metrics.get_chip_usage(chip_type) total_memory_size = device_usage[0].total_memory current_mem = device_usage[0].memory_usage else: m = xm.get_memory_info(self.device) total_memory_size = m["bytes_limit"] current_mem = m["bytes_used"] # Ideally we would use profiled = m["peak_bytes_used"] to # get weights + activations. But there is memory used during # compilation / weight loading that impacts the peak and # there is no way to reset peak memory in XLA, So we # use the heuristic of 2% of weights. profiled = current_mem * 1.02 # Calculate the TPU KV cache size based on profiling. usable_memory_size = int( total_memory_size * self.cache_config.gpu_memory_utilization ) tpu_kv_cache_bytes = max(usable_memory_size - profiled, 0) head_size = self.model_config.get_head_size() if head_size > 0: padded_head_size = ( cdiv(head_size, TPU_HEAD_SIZE_ALIGNMENT) * TPU_HEAD_SIZE_ALIGNMENT ) if padded_head_size != head_size: logger.warning_once("head size is padded to %d", padded_head_size) # We adjust the usable memory size for the KV cache to prevent OOM # errors, even after padding the head_size. tpu_kv_cache_bytes = tpu_kv_cache_bytes * head_size // padded_head_size return int(tpu_kv_cache_bytes) def sample_tokens(self, grammar_output: "GrammarOutput") -> ModelRunnerOutput: return self.model_runner.sample_tokens(grammar_output) def execute_model( self, scheduler_output: "SchedulerOutput" ) -> ModelRunnerOutput | None: return self.model_runner.execute_model(scheduler_output) def profile(self, is_start: bool = True): if self.rank < 1: if self.profile_dir is None: raise RuntimeError("Profiler is not enabled.") if is_start: if self.profiler is None: self.profiler = xp.start_server(9012) xp.start_trace(self.profile_dir) else: xp.stop_trace() def add_lora(self, lora_request: LoRARequest) -> bool: return self.model_runner.add_lora(lora_request) def load_model(self) -> None: self.model_runner.load_model() def update_config(self, overrides: dict[str, Any]) -> None: self.model_runner.update_config(overrides) def reload_weights(self) -> None: self.model_runner.reload_weights() def compile_or_warm_up_model(self) -> None: if not self.model_config.enforce_eager: self.model_runner.capture_model() # Reset the seed to ensure that the random state is not affected by # the model initialization and profiling. set_random_seed(self.model_config.seed) def reset_mm_cache(self) -> None: self.model_runner.reset_mm_cache() def get_model(self) -> nn.Module: return self.model_runner.get_model() def get_supported_tasks(self) -> tuple[SupportedTask, ...]: return self.model_runner.get_supported_tasks() def get_kv_cache_spec(self) -> dict[str, KVCacheSpec]: return self.model_runner.get_kv_cache_spec() def initialize_from_config(self, kv_cache_config: KVCacheConfig) -> None: """Allocate GPU KV cache with the specified kv_cache_config.""" # Init kv cache connector here, because it requires # `kv_cache_config`. # NOTE(Kuntai): This need to be done before `initialize_kv_cache`, # because `initialize_kv_cache` will inject kv cache groups not # related to kv cache connector (e.g. kv cache sharing layers). ensure_kv_transfer_initialized(self.vllm_config, kv_cache_config) self.model_runner.initialize_kv_cache(kv_cache_config) def check_health(self) -> None: # worker will always be healthy as long as it's running. return def _init_tpu_worker_distributed_environment( self, vllm_config: VllmConfig, rank: int, distributed_init_method: str | None = None, local_rank: int = -1, ) -> None: """Initialize the distributed environment.""" if self.use_spmd: xr.use_spmd() # NOTE(woosuk): This is just to initialize the TP group and broadcast # the input objects on CPU. The all-reduce and all-gather ops on TPU # are invoked by `xm.all_reduce` and `xm.all_gather` which use their # own context. parallel_config = vllm_config.parallel_config init_distributed_environment( world_size=parallel_config.world_size, rank=rank, local_rank=local_rank, distributed_init_method=distributed_init_method or "env://", backend=current_platform.dist_backend, ) ensure_model_parallel_initialized( parallel_config.tensor_parallel_size, parallel_config.pipeline_parallel_size ) def shutdown(self) -> None: self.model_runner.ensure_kv_transfer_shutdown() def apply_model(self, fn: Callable[[nn.Module], _R]) -> _R: """Apply a function on the model inside this worker.""" return fn(self.get_model()) if USE_TPU_INFERENCE: from tpu_inference.worker.tpu_worker import TPUWorker as TpuInferenceWorker TPUWorker = TpuInferenceWorker # type: ignore
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/lora_model_runner_mixin.py
vllm/v1/worker/lora_model_runner_mixin.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Define LoRA functionality mixin for model runners. """ from contextlib import contextmanager from typing import TypeAlias import numpy as np import torch import torch.nn as nn from vllm.config import VllmConfig from vllm.config.lora import LoRAConfig from vllm.logger import init_logger from vllm.lora.layers import LoRAMapping, LoRAMappingType from vllm.lora.request import LoRARequest from vllm.lora.worker_manager import LRUCacheWorkerLoRAManager from vllm.model_executor.models import supports_lora from vllm.v1.worker.gpu_input_batch import InputBatch as GPUInputBatch from vllm.v1.worker.tpu_input_batch import InputBatch as TPUInputBatch InputBatch: TypeAlias = TPUInputBatch | GPUInputBatch logger = init_logger(__name__) # Defined as a mixin for GPUModelRunner class LoRAModelRunnerMixin: def load_lora_model( self, model: nn.Module, vllm_config: VllmConfig, device: torch.device, ) -> nn.Module: if not supports_lora(model): raise ValueError(f"{model.__class__.__name__} does not support LoRA yet.") # Add LoRA Manager to the Model Runner self.lora_manager = LRUCacheWorkerLoRAManager( vllm_config, device, model.embedding_modules, ) return self.lora_manager.create_lora_manager(model, vllm_config) def _set_active_loras( self, prompt_lora_mapping: tuple[int, ...], token_lora_mapping: tuple[int, ...], lora_requests: set[LoRARequest], mapping_type: LoRAMappingType = LoRAMappingType.LANGUAGE, ) -> None: self._ensure_lora_enabled() # Set is_prefill to True, so we always use the SGMV kernels on # non-cuda platforms. # On cuda platforms we use the same kernels for prefill and # decode and this flag is generally ignored. lora_mapping = LoRAMapping( token_lora_mapping, prompt_lora_mapping, is_prefill=True, type=mapping_type, ) self.lora_manager.set_active_adapters(lora_requests, lora_mapping) def _ensure_lora_enabled(self) -> None: if not hasattr(self, "lora_manager"): raise RuntimeError("LoRA is not enabled. Use --enable-lora to enable LoRA.") def set_active_loras( self, input_batch: InputBatch, num_scheduled_tokens: np.ndarray, num_sampled_tokens: np.ndarray | None = None, mapping_type: LoRAMappingType = LoRAMappingType.LANGUAGE, ) -> None: if num_sampled_tokens is None: num_sampled_tokens = np.ones_like(num_scheduled_tokens, dtype=np.int32) prompt_lora_mapping: tuple[int, ...] # of size np.sum(num_sampled_tokens) token_lora_mapping: tuple[int, ...] # of size np.sum(num_scheduled_tokens) lora_requests: set[LoRARequest] prompt_lora_mapping, token_lora_mapping, lora_requests = ( input_batch.make_lora_inputs(num_scheduled_tokens, num_sampled_tokens) ) return self._set_active_loras( prompt_lora_mapping, token_lora_mapping, lora_requests, mapping_type ) @contextmanager def maybe_setup_dummy_loras( self, lora_config: LoRAConfig | None, remove_lora: bool = True ): if lora_config is None: yield else: # __enter__ code assert self.lora_manager is not None, "LoRA is not enabled" num_loras = lora_config.max_loras lora_warmup_rank = ( lora_config.max_lora_rank if lora_config.max_lora_rank < 8 else 8 ) # Make dummy lora requests lora_requests: set[LoRARequest] = { LoRARequest( lora_name=f"warmup_{lora_id}", lora_int_id=lora_id, lora_path="/not/a/real/path", ) for lora_id in range(1, num_loras + 1) } with self.lora_manager.dummy_lora_cache(): # Add the dummy LoRAs here so _set_active_loras doesn't try to # load from disk. for lr in lora_requests: self.lora_manager.add_dummy_lora(lr, rank=lora_warmup_rank) yield # __exit__ code if remove_lora: self.lora_manager.remove_all_adapters() @contextmanager def maybe_select_dummy_loras( self, lora_config: LoRAConfig | None, num_scheduled_tokens: np.ndarray, mapping_type: LoRAMappingType = LoRAMappingType.LANGUAGE, num_sampled_tokens: np.ndarray | None = None, activate_lora: bool = True, ): if num_sampled_tokens is None: num_sampled_tokens = np.ones_like(num_scheduled_tokens, dtype=np.int32) if lora_config is None: yield else: # __enter__ code assert self.lora_manager is not None, "LoRA is not enabled" num_reqs = len(num_scheduled_tokens) num_loras = lora_config.max_loras # Make prompt lora mapping # Assign LoRA IDs cyclically to simulate a worst-case scenario. if activate_lora: prompt_lora_mapping = ( np.arange(num_reqs, dtype=np.int32) % num_loras ) + 1 else: prompt_lora_mapping = np.zeros(num_reqs, dtype=np.int32) # Make sample lora mapping sample_lora_mapping = np.repeat(prompt_lora_mapping, num_sampled_tokens) # Make token lora mapping token_lora_mapping = np.repeat(prompt_lora_mapping, num_scheduled_tokens) # Make dummy lora requests lora_requests: set[LoRARequest] = { LoRARequest( lora_name=f"warmup_{lora_id}", lora_int_id=lora_id, lora_path="/not/a/real/path", ) for lora_id in range(1, num_loras + 1) } self._set_active_loras( tuple(sample_lora_mapping), tuple(token_lora_mapping), lora_requests, mapping_type, ) yield @contextmanager def maybe_dummy_run_with_lora( self, lora_config: LoRAConfig | None, num_scheduled_tokens: np.ndarray, num_sampled_tokens: np.ndarray, activate_lora: bool = True, remove_lora: bool = True, mapping_type: LoRAMappingType = LoRAMappingType.LANGUAGE, ): with ( self.maybe_setup_dummy_loras(lora_config, remove_lora), self.maybe_select_dummy_loras( lora_config, num_scheduled_tokens, mapping_type, num_sampled_tokens, activate_lora, ), ): yield def maybe_remove_all_loras(self, lora_config: LoRAConfig | None): if lora_config is None: return self.lora_manager.remove_all_adapters() def add_lora(self, lora_request: LoRARequest) -> bool: self._ensure_lora_enabled() return self.lora_manager.add_adapter(lora_request) def remove_lora(self, lora_id: int) -> bool: self._ensure_lora_enabled() return self.lora_manager.remove_adapter(lora_id) def pin_lora(self, lora_id: int) -> bool: self._ensure_lora_enabled() return self.lora_manager.pin_adapter(lora_id) def list_loras(self) -> set[int]: self._ensure_lora_enabled() return self.lora_manager.list_adapters()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu_ubatch_wrapper.py
vllm/v1/worker/gpu_ubatch_wrapper.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import threading from collections.abc import Callable from dataclasses import dataclass from typing import Any import torch import vllm.envs as envs from vllm.compilation.cuda_graph import CUDAGraphWrapper from vllm.config import CUDAGraphMode, VllmConfig from vllm.distributed import get_ep_group from vllm.distributed.device_communicators.pynccl_allocator import set_graph_pool_id from vllm.forward_context import ( DPMetadata, create_forward_context, get_forward_context, override_forward_context, ) from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors from vllm.utils.import_utils import has_deep_gemm from vllm.v1.worker.ubatching import UBatchContext, make_ubatch_contexts logger = init_logger(__name__) @dataclass class UbatchMetadata: context: UBatchContext input_ids: torch.Tensor positions: torch.Tensor inputs_embeds: torch.Tensor | None intermediate_tensors: IntermediateTensors | None num_tokens: int @dataclass class CUDAGraphMetaData: cudagraph: torch.cuda.CUDAGraph ubatch_metadata: UbatchMetadata outputs: Any | None = None class SMControlContextManager: def __init__( self, comm_sms: int, set_comm_sms: Callable[[int], None], set_compute_sms: Callable[[int], None], ): """ Context manager for controlling SM (Streaming Multiprocessor) allocation. Upon entering the context, it sets the number of SMs allocated for communication and computation to comm_sms and total_sms - comm_sms respectively. Upon exiting, it restores the allocation to use all available SMs (i.e. total_sms). Args: comm_sms (int): The number of SMs to allocate for communication. (The remainder will be used for computation.) set_comm_sms (Callable[[int], None]): A function that sets the number of SMs for communication. set_compute_sms (Callable[[int], None]): A function that sets the number of SMs for computation. """ assert current_platform.is_cuda(), ( "SM control is currently only supported on CUDA" ) props = torch.cuda.get_device_properties(torch.cuda.current_device()) total_sms = props.multi_processor_count assert comm_sms < total_sms self.total_sms = total_sms self.compute_sms = total_sms - comm_sms self.comm_sms = comm_sms self.set_comm_sms = set_comm_sms self.set_compute_sms = set_compute_sms def __enter__(self): self.set_comm_sms(self.comm_sms) self.set_compute_sms(self.compute_sms) def __exit__(self, exc_type, exc_value, traceback): self.set_comm_sms(self.total_sms) self.set_compute_sms(self.total_sms) class UBatchWrapper: def __init__( self, runnable: Callable, vllm_config: VllmConfig, runtime_mode: CUDAGraphMode, device: torch.cuda.device, ): self.runnable = runnable self.vllm_config = vllm_config self.compilation_config = vllm_config.compilation_config self.comm_stream = torch.cuda.Stream(device=device) # Ubatch threads plus the main thread self.ready_barrier = threading.Barrier( self.vllm_config.parallel_config.num_ubatches + 1 ) self.cudagraphs: dict[int, CUDAGraphMetaData] = {} self.cudagraph_wrapper = None self.graph_pool = None if runtime_mode is not CUDAGraphMode.NONE: self.cudagraph_wrapper = CUDAGraphWrapper( runnable, vllm_config, runtime_mode=runtime_mode ) self.graph_pool = current_platform.get_global_graph_pool() self.sm_control = self._create_sm_control_context(vllm_config) self.device = device @staticmethod def _create_sm_control_context(vllm_config: VllmConfig): comm_sms: int = envs.VLLM_DBO_COMM_SMS set_comm_sms = lambda sms: None if vllm_config.parallel_config.enable_expert_parallel: # Currently only DeepEP highthroughput supports SM control so this # only affects that case. ep_group = get_ep_group() device_communicator = ep_group.device_communicator all2all_manager = None if device_communicator is not None: all2all_manager = device_communicator.all2all_manager if all2all_manager is not None: max_sms_used = all2all_manager.max_sms_used() if max_sms_used is not None: comm_sms = min(comm_sms, max_sms_used) if comm_sms > 0 and all2all_manager is not None: set_comm_sms = lambda sms: all2all_manager.set_num_sms(sms) # TODO(lucas): support other kernels besides DeepGEMM set_compute_sms = lambda sms: None if has_deep_gemm() and comm_sms > 0: import deep_gemm as dg set_compute_sms = lambda sms: dg.set_num_sms(sms) return SMControlContextManager( comm_sms=comm_sms, set_comm_sms=set_comm_sms, set_compute_sms=set_compute_sms, ) def __getattr__(self, key: str): # allow accessing the attributes of the runnable. if hasattr(self.runnable, key): return getattr(self.runnable, key) raise AttributeError( f"Attribute {key} not exists in the runnable of " f"cudagraph wrapper: {self.runnable}" ) def unwrap(self) -> Callable: # in case we need to access the original runnable. return self.runnable def _capture_ubatches(self, ubatch_metadata, model) -> torch.Tensor: """ Capture a cudagraph for a microbatched run. The logic here is somewhat complicated because we need to make sure that each of the ubatch threads initialize the cuda context before we start the graph capture. The flow is as follows: 1. The main thread starts up each ubatch thread. Each thread will initialize its cuda context (torch.cuda.current_blas_handle()) before going to sleep upon entering the ubatch_context. 2. The main thread starts the graph capture and wakes up the first ubatch thread. 3. Each ubatch thread runs the model to completion and returns the completed output tensors back to the main thread. 4. The main thread stores the captured cudagraph along with its metadata and returns """ @torch.inference_mode() def _capture_ubatch_thread(results, ubatch_metadata): torch.cuda.set_device(self.device) ubatch_context = ubatch_metadata.context with torch.cuda.stream(ubatch_context.compute_stream): _ = torch.cuda.current_blas_handle() with torch.cuda.stream(ubatch_context.comm_stream): _ = torch.cuda.current_blas_handle() with ubatch_context: model_output = model( input_ids=ubatch_metadata.input_ids, positions=ubatch_metadata.positions, intermediate_tensors=ubatch_metadata.intermediate_tensors, inputs_embeds=ubatch_metadata.inputs_embeds, ) results.append((ubatch_metadata.context.id, model_output)) results: list[tuple[int, torch.Tensor]] = [] compute_stream = ubatch_metadata[0].context.compute_stream num_tokens = ubatch_metadata[0].num_tokens + ubatch_metadata[1].num_tokens # Ubatches will manually manage the forward context, so we override # it to None here so we can have it restored correctly later with override_forward_context(None): ubatch_threads = [] for metadata in ubatch_metadata: thread = threading.Thread( target=_capture_ubatch_thread, args=( results, metadata, ), ) ubatch_threads.append(thread) thread.start() self.ready_barrier.wait() # Wait for both threads to be ready # Capture the cudagraph cudagraph_metadata = CUDAGraphMetaData( cudagraph=torch.cuda.CUDAGraph(), ubatch_metadata=ubatch_metadata, ) if self.graph_pool is not None: set_graph_pool_id(self.graph_pool) else: set_graph_pool_id(current_platform.graph_pool_handle()) with torch.cuda.graph( cudagraph_metadata.cudagraph, stream=compute_stream, pool=self.graph_pool, ): ubatch_metadata[0].context.cpu_wait_event.set() for thread in ubatch_threads: thread.join() sorted_results = [value for position, value in sorted(results)] result = torch.cat(sorted_results, dim=0) cudagraph_metadata.outputs = result self.cudagraphs[num_tokens] = cudagraph_metadata return cudagraph_metadata.outputs def _run_ubatches(self, ubatch_metadata, model) -> torch.Tensor: @torch.inference_mode() def _ubatch_thread(results, model, ubatch_metadata): with ubatch_metadata.context: model_output = model( input_ids=ubatch_metadata.input_ids, positions=ubatch_metadata.positions, intermediate_tensors=ubatch_metadata.intermediate_tensors, inputs_embeds=ubatch_metadata.inputs_embeds, ) results.append((ubatch_metadata.context.id, model_output)) results: list[tuple[int, torch.Tensor]] = [] # Ubatch threads will manually manage the forward context, so we # override it to None here so we can have it restored correctly # after both threads have finished with override_forward_context(None): ubatch_threads = [] for metadata in ubatch_metadata: thread = threading.Thread( target=_ubatch_thread, args=( results, model, metadata, ), ) ubatch_threads.append(thread) thread.start() self.ready_barrier.wait() # Wait for both threads to be ready ubatch_metadata[0].context.cpu_wait_event.set() for thread in ubatch_threads: thread.join() sorted_results = [value for position, value in sorted(results)] result = torch.cat(sorted_results, dim=0) return result def _make_ubatch_metadata( self, ubatch_slices, attn_metadata, input_ids, positions, inputs_embeds, intermediate_tensors, compute_stream, dp_metadata, batch_descriptor, cudagraph_runtime_mode, ) -> list[UbatchMetadata]: # Create one forward context per ubatch forward_contexts = [] for i, ubatch_slice in enumerate(ubatch_slices): forward_contexts.append( create_forward_context( attn_metadata[i] if attn_metadata is not None else None, self.vllm_config, dp_metadata=dp_metadata[i], batch_descriptor=batch_descriptor, cudagraph_runtime_mode=cudagraph_runtime_mode, ) ) ubatch_ctxs = make_ubatch_contexts( num_micro_batches=len(ubatch_slices), comm_stream=self.comm_stream, compute_stream=compute_stream, forward_contexts=forward_contexts, ready_barrier=self.ready_barrier, ) ubatch_metadata: list[UbatchMetadata] = [] for i, ubatch_slice in enumerate(ubatch_slices): ( sliced_input_ids, sliced_positions, sliced_inputs_embeds, sliced_intermediate_tensors, ) = self._slice_model_inputs( ubatch_slice.token_slice, input_ids, positions, inputs_embeds, intermediate_tensors, ) ubatch_metadata.append( UbatchMetadata( context=ubatch_ctxs[i], input_ids=sliced_input_ids, positions=sliced_positions, inputs_embeds=sliced_inputs_embeds, intermediate_tensors=sliced_intermediate_tensors, num_tokens=ubatch_slice.token_slice.stop - ubatch_slice.token_slice.start, ) ) return ubatch_metadata def _slice_model_inputs( self, tokens_slice: slice, input_ids, positions, inputs_embeds, intermediate_tensors, ): sliced_input_ids = input_ids[tokens_slice] # if we are using mrope. Mrope adds an additional dimension to the # positions tensor if positions.ndim == 2: sliced_positions = positions[:, tokens_slice] else: sliced_positions = positions[tokens_slice] sliced_inputs_embeds = inputs_embeds[tokens_slice] if inputs_embeds else None sliced_intermediate_tensors = ( intermediate_tensors[tokens_slice] if intermediate_tensors else None ) return ( sliced_input_ids, sliced_positions, sliced_inputs_embeds, sliced_intermediate_tensors, ) def __call__(self, *args, **kwargs): forward_context = get_forward_context() batch_descriptor = forward_context.batch_descriptor ubatch_slices = forward_context.ubatch_slices cudagraph_runtime_mode = forward_context.cudagraph_runtime_mode # If there's no ubatching, just run the runnable object if ubatch_slices is None: # This is to account for the case where ubatching was aborted. # When we capture full graphs we only capture one graph per shape, # meaning that if we have a ubatched cudagraph for the current # num_tokens, we don't have a non-ubatched one. Without this # check, the cudagraph wrapper will try to capture a cudagraph # for this shape during a normal run. if cudagraph_runtime_mode is CUDAGraphMode.FULL: assert batch_descriptor is not None if batch_descriptor.num_tokens in self.cudagraphs: cudagraph_runtime_mode = CUDAGraphMode.NONE if cudagraph_runtime_mode in (CUDAGraphMode.NONE, CUDAGraphMode.PIECEWISE): return self.runnable(*args, **kwargs) else: assert self.cudagraph_wrapper is not None return self.cudagraph_wrapper(*args, **kwargs) attn_metadata = forward_context.attn_metadata num_tokens = ( ubatch_slices[0].token_slice.stop - ubatch_slices[0].token_slice.start ) * 2 input_ids = kwargs["input_ids"] positions = kwargs["positions"] intermediate_tensors = kwargs["intermediate_tensors"] inputs_embeds = kwargs["inputs_embeds"] compute_stream = torch.cuda.current_stream() dp_metadata = forward_context.dp_metadata # We shouldn't be here unless we are running with multiple DP ranks assert dp_metadata is not None ubatch_dp_metadata = [] for ubatch_slice in ubatch_slices: dp_size = self.vllm_config.parallel_config.data_parallel_size ubatch_num_tokens_across_dp = torch.tensor( [ubatch_slice.num_tokens] * dp_size, device="cpu", dtype=torch.int32 ) ubatch_dp_metadata.append( DPMetadata.make( self.vllm_config.parallel_config, ubatch_slice.num_tokens, ubatch_num_tokens_across_dp, ) ) if ( num_tokens not in self.cudagraphs and cudagraph_runtime_mode is CUDAGraphMode.FULL ): ubatch_metadata = self._make_ubatch_metadata( ubatch_slices=ubatch_slices, attn_metadata=attn_metadata, input_ids=input_ids, positions=positions, intermediate_tensors=intermediate_tensors, inputs_embeds=inputs_embeds, compute_stream=compute_stream, dp_metadata=ubatch_dp_metadata, batch_descriptor=batch_descriptor, cudagraph_runtime_mode=CUDAGraphMode.NONE, ) with self.sm_control: return self._capture_ubatches(ubatch_metadata, self.model) elif ( num_tokens in self.cudagraphs and cudagraph_runtime_mode is CUDAGraphMode.FULL ): cudagraph_metadata = self.cudagraphs[num_tokens] cudagraph_metadata.cudagraph.replay() return cudagraph_metadata.outputs else: ubatch_metadata = self._make_ubatch_metadata( ubatch_slices=ubatch_slices, attn_metadata=attn_metadata, input_ids=input_ids, positions=positions, intermediate_tensors=intermediate_tensors, inputs_embeds=inputs_embeds, compute_stream=compute_stream, dp_metadata=ubatch_dp_metadata, batch_descriptor=batch_descriptor, cudagraph_runtime_mode=CUDAGraphMode.NONE, ) with self.sm_control: return self._run_ubatches(ubatch_metadata, self.model)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/cpu_worker.py
vllm/v1/worker/cpu_worker.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os import platform from collections.abc import Callable from typing import Any import torch from vllm import envs from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.model_executor.utils import set_random_seed from vllm.platforms import CpuArchEnum, current_platform from vllm.platforms.cpu import CpuPlatform, LogicalCPUInfo from vllm.profiler.wrapper import TorchProfilerWrapper from vllm.v1.worker.cpu_model_runner import CPUModelRunner from vllm.v1.worker.gpu_worker import Worker, init_worker_distributed_environment logger = init_logger(__name__) class CPUWorker(Worker): def __init__( self, vllm_config: VllmConfig, local_rank: int, rank: int, distributed_init_method: str, is_driver_worker: bool = False, ): super().__init__( vllm_config, local_rank, rank, distributed_init_method, is_driver_worker=is_driver_worker, ) self.parallel_config.disable_custom_all_reduce = True # Torch profiler. Enabled and configured through profiler_config. self.profiler: Any | None = None profiler_config = vllm_config.profiler_config if profiler_config.profiler == "torch": worker_name = f"{vllm_config.instance_id}-rank-{self.rank}" self.profiler = TorchProfilerWrapper( profiler_config, worker_name=worker_name, local_rank=self.local_rank, activities=["CPU"], ) def init_device(self): # Setup OpenMP threads affinity. omp_cpuids = envs.VLLM_CPU_OMP_THREADS_BIND if omp_cpuids == "auto" and platform.system() == "Linux": cpu_arch = current_platform.get_cpu_architecture() if cpu_arch in (CpuArchEnum.POWERPC, CpuArchEnum.S390X): # For S390X/POWERPC SMT-8/4/2 self.local_omp_cpuid = self._get_autobind_cpu_ids( lambda cpus: [cpu for cpu in cpus if cpu.id % 8 < 4] ) elif cpu_arch == CpuArchEnum.X86: # For x86 SMT-2, use 1 CPU per core self.local_omp_cpuid = self._get_autobind_cpu_ids( lambda cpus: cpus[-1:] ) else: self.local_omp_cpuid = "nobind" elif omp_cpuids == "nobind": self.local_omp_cpuid = "nobind" else: local_dp_rank = self.parallel_config.data_parallel_rank_local omp_cpuids_list = omp_cpuids.split("|") if local_dp_rank is not None: world_size = self.parallel_config.world_size omp_cpuids_list = omp_cpuids_list[ local_dp_rank * world_size : (local_dp_rank + 1) * world_size ] self.local_omp_cpuid = omp_cpuids_list[self.rank] if self.local_omp_cpuid != "nobind": ret = torch.ops._C_utils.init_cpu_threads_env(self.local_omp_cpuid) if ret: logger.info(ret) # Note: unique identifier for creating allreduce shared memory os.environ["VLLM_DIST_IDENT"] = self.distributed_init_method.split(":")[-1] # Initialize the distributed environment. init_worker_distributed_environment( self.vllm_config, self.rank, self.distributed_init_method, self.local_rank, current_platform.dist_backend, ) # Set random seed. set_random_seed(self.model_config.seed) # Construct the model runner self.model_runner: CPUModelRunner = CPUModelRunner( self.vllm_config, torch.device("cpu") ) def sleep(self, level: int = 1) -> None: logger.warning("sleep mode is not supported on CPU, ignore it.") pass def wake_up(self, tags: list[str] | None = None) -> None: logger.warning("sleep mode is not supported on CPU, ignore it.") pass def determine_available_memory(self) -> int: return self.cache_config.cpu_kvcache_space_bytes or 0 def compile_or_warm_up_model(self) -> None: # Reset the seed to ensure that the random state is not affected by # the model initialization and profiling. set_random_seed(self.model_config.seed) self.model_runner.warming_up_model() def _get_autobind_cpu_ids( self, cpu_selector: Callable[[list[LogicalCPUInfo]], list[LogicalCPUInfo]] ) -> str: """ Return CPU ids to bind based on NUMA nodes. Currently for rank N, only CPU ids on the N-th node in available NUMA node list will be selected. Args: cpu_selector: a callable object to select CPUs from a CPU list of a physical core. The input is a LogicalCPUInfo list, sorted by the LogicalCPUInfo.id. A selected LogicalCPUInfo list should be returned. """ allowed_numa_nodes, logical_cpu_list = ( CpuPlatform.get_allowed_cpu_core_node_list() ) assert len(allowed_numa_nodes) >= self.parallel_config.world_size, ( f"No enough allowed NUMA nodes to bind threads of " f"{self.parallel_config.world_size} CPUWorkers. " f"Allowed NUMA nodes are {allowed_numa_nodes}. " "Please try to bind threads manually." ) # Get CPUs on NUMA node `allowed_numa_nodes[local_rank]` selected_numa_node = allowed_numa_nodes[self.local_rank] # type: ignore logical_cpu_list = [ x for x in logical_cpu_list if x.numa_node == selected_numa_node ] # Select CPUs from each physical core via cpu_selector core_to_cpus: dict[int, list[LogicalCPUInfo]] = {} for cpu_info in logical_cpu_list: if cpu_info.physical_core not in core_to_cpus: core_to_cpus[cpu_info.physical_core] = [] core_to_cpus[cpu_info.physical_core].append(cpu_info) logical_cpu_list = [] for cpu_list in core_to_cpus.values(): cpu_list = sorted(cpu_list, key=lambda x: x.id) logical_cpu_list.extend(cpu_selector(cpu_list)) logical_cpu_list = sorted(logical_cpu_list, key=lambda x: x.id) # Reserve CPUs for other processes reserve_cpu_num = envs.VLLM_CPU_NUM_OF_RESERVED_CPU if reserve_cpu_num is None: need_reserve = ( self.parallel_config.world_size > 1 or self.parallel_config.data_parallel_size_local > 1 ) reserve_cpu_num = 1 if need_reserve else 0 assert len(logical_cpu_list) > reserve_cpu_num, ( f"VLLM_CPU_NUM_OF_RESERVED_CPU ({reserve_cpu_num}) " f"should less than {len(logical_cpu_list)}." ) if reserve_cpu_num != 0: logical_cpu_list = logical_cpu_list[:-reserve_cpu_num] logger.info( "auto thread-binding list (id, physical core): %s", [(x.id, x.physical_core) for x in logical_cpu_list], ) return ",".join([str(x.id) for x in logical_cpu_list]) def profile(self, is_start: bool = True): if self.profiler is None: raise RuntimeError("Profiler is not enabled.") if is_start: self.profiler.start() else: self.profiler.stop()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/cpu_model_runner.py
vllm/v1/worker/cpu_model_runner.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from contextlib import contextmanager from typing import Any import torch import torch.nn as nn from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.model_executor.model_loader import get_model from vllm.v1.utils import CpuGpuBuffer from vllm.v1.worker.gpu_model_runner import GPUModelRunner logger = init_logger(__name__) class CPUModelRunner(GPUModelRunner): def __init__(self, vllm_config: VllmConfig, device: torch.device): with _torch_cuda_wrapper(): super().__init__(vllm_config, device) assert device == torch.device("cpu") assert self.speculative_config is None, "spec decode is not supported." self.use_cuda_graph = False self.cascade_attn_enabled = False self._postprocess_tensors() def _postprocess_tensors(self) -> None: # Note: replace device tensors with cpu tensors def replace_tensor(obj: Any, cpu_attr_name: str, device_attr_name) -> None: cpu_tensor = getattr(obj, cpu_attr_name, None) device_tensor = getattr(obj, device_attr_name, None) if cpu_tensor is not None and device_tensor is not None: assert isinstance(cpu_tensor, torch.Tensor) assert isinstance(device_tensor, torch.Tensor) setattr(obj, device_attr_name, cpu_tensor) for v in vars(self).values(): if isinstance(v, CpuGpuBuffer): v.gpu = v.cpu for k, v in vars(self.input_batch).items(): if k.endswith("_cpu_tensor") and isinstance(v, torch.Tensor): replace_tensor(self.input_batch, k, k[:-11]) for block_table in self.input_batch.block_table.block_tables: for v in vars(block_table).values(): if isinstance(v, CpuGpuBuffer): v.gpu = v.cpu def load_model(self, eep_scale_up: bool = False) -> None: logger.info("Starting to load model %s...", self.model_config.model) self.model = get_model(vllm_config=self.vllm_config) if self.lora_config: self.model = self.load_lora_model(self.model, self.vllm_config, self.device) def get_model(self) -> nn.Module: return self.model def warming_up_model(self) -> None: logger.info("Warming up model for the compilation...") # Only generate graph for the generic shape with _set_global_compilation_settings(self.vllm_config): self._dummy_run( min( max(16, self.max_num_reqs), self.scheduler_config.max_num_batched_tokens, ) ) logger.info("Warming up done.") def _init_device_properties(self) -> None: pass def _sync_device(self) -> None: pass def get_dp_padding(self, num_tokens: int) -> tuple[int, torch.Tensor | None]: # Note: For CPU backend, dp padding is not required for now. return 0, None @contextmanager def _torch_cuda_wrapper(): class _EventPlaceholder: def __init__(self, *args, **kwargs) -> None: self.record = lambda: None self.synchronize = lambda: None class _StreamPlaceholder: def __init__(self, *args, **kwargs) -> None: pass cuda_event = torch.Event cuda_stream = torch.cuda.Stream try: torch.Event = _EventPlaceholder torch.cuda.Stream = _StreamPlaceholder yield finally: torch.Event = cuda_event torch.cuda.Stream = cuda_stream @contextmanager def _set_global_compilation_settings(config: VllmConfig): import torch._inductor.config as torch_inductor_config inductor_config = config.compilation_config.inductor_compile_config # Note: The MKLDNN and CPPGEMM backend requires freezing parameters. freezing_value = torch_inductor_config.freezing try: if inductor_config.get("max_autotune", False): torch_inductor_config.freezing = True yield finally: torch_inductor_config.freezing = freezing_value
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/xpu_worker.py
vllm/v1/worker/xpu_worker.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os from typing import Any import torch import torch.distributed from vllm.config import VllmConfig from vllm.distributed import get_world_group from vllm.logger import init_logger from vllm.model_executor import set_random_seed from vllm.platforms import current_platform from vllm.profiler.wrapper import TorchProfilerWrapper from vllm.v1.worker.gpu_worker import Worker, init_worker_distributed_environment from vllm.v1.worker.xpu_model_runner import XPUModelRunner logger = init_logger(__name__) class XPUWorker(Worker): """A XPU worker class.""" def __init__( self, vllm_config: VllmConfig, local_rank: int, rank: int, distributed_init_method: str, is_driver_worker: bool = False, ): super().__init__( vllm_config, local_rank, rank, distributed_init_method, is_driver_worker ) device_config = self.device_config assert device_config.device_type == "xpu" assert current_platform.is_xpu() # Torch profiler. Enabled and configured through profiler_config. self.profiler: Any | None = None profiler_config = vllm_config.profiler_config if profiler_config.profiler == "torch": worker_name = f"{vllm_config.instance_id}-rank-{self.rank}" self.profiler = TorchProfilerWrapper( profiler_config, worker_name=worker_name, local_rank=self.local_rank, activities=["CPU", "XPU"], ) # we provide this function due to `torch.xpu.mem_get_info()` doesn't # return correct free_gpu_memory on intel client GPU. We need to # calculate/estiamte it. def xpu_get_mem_info(self): if current_platform.is_data_center_gpu(): return torch.xpu.mem_get_info() else: _, total_gpu_memory = torch.xpu.mem_get_info() # FIXME: memory_allocated() doesn't count non-torch allocations, # and we don't have any API to get it. so we mark it as 128MB. used_memory = torch.xpu.memory_allocated() non_torch_allocations = 128 * 1024 * 1024 free_gpu_memory = total_gpu_memory - (used_memory + non_torch_allocations) return free_gpu_memory, total_gpu_memory @torch.inference_mode() def determine_available_memory(self) -> int: """Profiles the peak memory usage of the model to determine how many KV blocks may be allocated without OOMs. The engine will first conduct a profiling of the existing memory usage. Then, it calculates the maximum possible number of GPU and CPU blocks that can be allocated with the remaining free memory. .. tip:: You may limit the usage of GPU memory by adjusting the `gpu_memory_utilization` parameter. """ # Profile the memory usage of the model and get the maximum number of # cache blocks that can be allocated with the remaining free memory. torch.xpu.empty_cache() torch.xpu.reset_peak_memory_stats() free_gpu_memory, total_gpu_memory = torch.xpu.mem_get_info() current_allocated_bytes = torch.xpu.memory_allocated() msg = ( "Before memory profiling run, " f"total GPU memory: {total_gpu_memory / 1024**2:.2f} MB, " f"model load takes {current_allocated_bytes / 1024**2:.2f} MB, " f"free gpu memory is {free_gpu_memory / 1024**2:.2f} MB." ) logger.info(msg) # Execute a forward pass with dummy inputs to profile the memory usage # of the model. self.model_runner.profile_run() free_gpu_memory, _ = self.xpu_get_mem_info() # NOTE(woosuk): Here we assume that the other processes using the same # GPU did not change their memory usage during the profiling. assert self.init_gpu_memory > free_gpu_memory, ( "Error in memory profiling. " f"Initial free memory {self.init_gpu_memory}, current free memory" f" {free_gpu_memory}. This happens when the GPU memory was " "not properly cleaned up before initializing the vLLM instance." ) # Get the peak memory allocation recorded by torch peak_memory = torch.xpu.memory_stats()["allocated_bytes.all.peak"] torch.xpu.empty_cache() torch_allocated_bytes = torch.xpu.memory_stats()["allocated_bytes.all.current"] total_allocated_bytes = self.xpu_get_mem_info()[1] - self.xpu_get_mem_info()[0] non_torch_allocations = total_allocated_bytes - torch_allocated_bytes if non_torch_allocations > 0: peak_memory += non_torch_allocations available_kv_cache_memory = ( total_gpu_memory * self.cache_config.gpu_memory_utilization - peak_memory ) msg = ( "After memory profiling run, " f"peak memory usage is {peak_memory / 1024**2:.2f} MB," f"torch mem is {torch_allocated_bytes / 1024**2:.2f} MB, " f"non-torch mem is {non_torch_allocations / 1024**2:.2f} MB, " f"free gpu memory is {free_gpu_memory / 1024**2:.2f} MB." ) logger.info(msg) return int(available_kv_cache_memory) def init_device(self): device = self.device_config.device if ( isinstance(device, torch.device) and device.type == "xpu" and current_platform.is_xpu() ): self.device = torch.device(f"xpu:{self.local_rank}") current_platform.set_device(self.device) current_platform.check_if_supports_dtype(self.model_config.dtype) torch.xpu.empty_cache() self.init_gpu_memory = torch.xpu.get_device_properties( self.local_rank ).total_memory else: raise RuntimeError(f"Not support device type: {self.device_config.device}") ENV_CCL_ATL_TRANSPORT = os.getenv("CCL_ATL_TRANSPORT", "ofi") ENV_LOCAL_WORLD_SIZE = os.getenv( "LOCAL_WORLD_SIZE", str(self.parallel_config.world_size) ) os.environ["CCL_ATL_TRANSPORT"] = ENV_CCL_ATL_TRANSPORT os.environ["LOCAL_WORLD_SIZE"] = ENV_LOCAL_WORLD_SIZE os.environ["LOCAL_RANK"] = str(self.local_rank) init_worker_distributed_environment( self.vllm_config, self.rank, self.distributed_init_method, self.local_rank, current_platform.dist_backend, ) # global all_reduce needed for overall oneccl warm up torch.distributed.all_reduce( torch.zeros(1).xpu(), group=get_world_group().device_group ) # Set random seed. set_random_seed(self.model_config.seed) # Construct the model runner self.model_runner = XPUModelRunner( # type: ignore self.vllm_config, self.device )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/tpu_input_batch.py
vllm/v1/worker/tpu_input_batch.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Datastructures defining a TPU input batch from typing import cast import numpy as np import torch from vllm.lora.request import LoRARequest from vllm.sampling_params import SamplingType from vllm.utils import length_from_prompt_token_ids_or_embeds from vllm.utils.collection_utils import swap_dict_values from vllm.v1.outputs import LogprobsTensors from vllm.v1.worker.block_table import MultiGroupBlockTable from vllm.v1.worker.gpu_input_batch import CachedRequestState _SAMPLING_EPS = 1e-5 class InputBatch: def __init__( self, max_num_reqs: int, max_model_len: int, max_num_batched_tokens: int, device: torch.device, pin_memory: bool, vocab_size: int, block_sizes: list[int], # The block_size of each kv cache group kernel_block_sizes: list[int], ): self.max_num_reqs = max_num_reqs self.max_model_len = max_model_len self.max_num_batched_tokens = max_num_batched_tokens self.device = device self.pin_memory = pin_memory self.vocab_size = vocab_size self._req_ids: list[str | None] = [] self.req_id_to_index: dict[str, int] = {} # TODO(woosuk): This buffer could be too large if max_model_len is big. # Find a way to reduce the CPU memory usage. # This buffer is not directly transferred to the GPU, so it does not # need to be pinned. self.token_ids_cpu_tensor = torch.zeros( (max_num_reqs, max_model_len), device="cpu", dtype=torch.int32, pin_memory=False, ) self.token_ids_cpu = self.token_ids_cpu_tensor.numpy() self.num_tokens_no_spec = np.zeros(max_num_reqs, dtype=np.int32) self.num_prompt_tokens = np.zeros(max_num_reqs, dtype=np.int32) self.num_computed_tokens_cpu_tensor = torch.zeros( (max_num_reqs,), device="cpu", dtype=torch.int32, pin_memory=pin_memory, ) self.num_computed_tokens_cpu = self.num_computed_tokens_cpu_tensor.numpy() # Block table. self.block_table = MultiGroupBlockTable( max_num_reqs=max_num_reqs, max_model_len=max_model_len, max_num_batched_tokens=max_num_batched_tokens, pin_memory=pin_memory, device=device, block_sizes=block_sizes, kernel_block_sizes=kernel_block_sizes, ) # Sampling-related. self.temperature = torch.empty( (max_num_reqs,), dtype=torch.float32, device=device ) self.temperature_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float32, device="cpu", pin_memory=pin_memory ) self.temperature_cpu = self.temperature_cpu_tensor.numpy() self.greedy_reqs: set[str] = set() self.random_reqs: set[str] = set() self.top_p = torch.empty((max_num_reqs,), dtype=torch.float32, device=device) self.top_p_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float32, device="cpu", pin_memory=pin_memory ) self.top_p_cpu = self.top_p_cpu_tensor.numpy() self.top_p_reqs: set[str] = set() self.top_k = torch.empty((max_num_reqs,), dtype=torch.int32, device=device) self.top_k_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.int32, device="cpu", pin_memory=pin_memory ) self.top_k_cpu = self.top_k_cpu_tensor.numpy() self.top_k_reqs: set[str] = set() self.min_p = torch.empty((max_num_reqs,), dtype=torch.float32, device=device) self.min_p_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float32, device="cpu", pin_memory=pin_memory ) self.min_p_cpu = self.min_p_cpu_tensor.numpy() self.min_p_reqs: set[str] = set() # Frequency penalty related data structures self.frequency_penalties = torch.empty( (max_num_reqs,), dtype=torch.float, device=device ) self.frequency_penalties_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float, device="cpu", pin_memory=pin_memory ) self.frequency_penalties_cpu = self.frequency_penalties_cpu_tensor.numpy() self.frequency_penalties_reqs: set[str] = set() # Presence penalty related data structures self.presence_penalties = torch.empty( (max_num_reqs,), dtype=torch.float, device=device ) self.presence_penalties_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float, device="cpu", pin_memory=pin_memory ) self.presence_penalties_cpu = self.presence_penalties_cpu_tensor.numpy() self.presence_penalties_reqs: set[str] = set() # Repetition penalty related data structures self.repetition_penalties = torch.empty( (max_num_reqs,), dtype=torch.float, device=device ) self.repetition_penalties_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float, device="cpu", pin_memory=pin_memory ) self.repetition_penalties_cpu = self.repetition_penalties_cpu_tensor.numpy() self.repetition_penalties_reqs: set[str] = set() # req_index -> (min_tokens, stop_token_ids) self.min_tokens: dict[int, tuple[int, set[int]]] = {} # lora related self.request_lora_mapping = np.zeros((self.max_num_reqs,), dtype=np.int64) self.lora_id_to_request_ids: dict[int, set[str]] = {} self.lora_id_to_lora_request: dict[int, LoRARequest] = {} # req_index -> generator # NOTE(woosuk): The indices of the requests that do not have their own # generator should not be included in the dictionary. self.generators: dict[int, torch.Generator] = {} self.num_logprobs: dict[str, int] = {} # To accumulate prompt logprobs tensor chunks across prefill steps. self.in_progress_prompt_logprobs_cpu: dict[str, LogprobsTensors] = {} self.logit_bias: list[dict[int, float] | None] = [None] * max_num_reqs self.has_allowed_token_ids: set[str] = set() # NOTE(lufang): In the mask tensor, if the corresponding token allowed, # the value is False. Since we use masked_fill_ to set -inf. self.allowed_token_ids_mask: torch.Tensor | None = None self.allowed_token_ids_mask_cpu_tensor: torch.Tensor | None = None # req_index -> bad_words_token_ids self.bad_words_token_ids: dict[int, list[list[int]]] = {} self.req_output_token_ids: list[list[int] | None] = [] @property def req_ids(self) -> list[str]: # None elements should only be present transiently # while performing state updates to the batch. return cast(list[str], self._req_ids) def add_request( self, request: "CachedRequestState", req_index: int | None = None, ) -> None: if req_index is None: req_index = self.num_reqs assert req_index < self.max_num_reqs req_id = request.req_id if req_index == len(self._req_ids): self._req_ids.append(req_id) self.req_output_token_ids.append(request.output_token_ids) else: self._req_ids[req_index] = req_id self.req_output_token_ids[req_index] = request.output_token_ids self.req_id_to_index[req_id] = req_index # Copy the prompt token ids and output token ids. num_prompt_tokens = length_from_prompt_token_ids_or_embeds( request.prompt_token_ids, request.prompt_embeds ) # TODO: copy prompt_embeds self.num_prompt_tokens[req_index] = num_prompt_tokens self.token_ids_cpu[req_index, :num_prompt_tokens] = request.prompt_token_ids start_idx = num_prompt_tokens end_idx = start_idx + len(request.output_token_ids) self.token_ids_cpu[req_index, start_idx:end_idx] = request.output_token_ids # Number of tokens without spec decode tokens. self.num_tokens_no_spec[req_index] = request.num_tokens self.num_computed_tokens_cpu[req_index] = request.num_computed_tokens self.block_table.add_row(request.block_ids, req_index) sampling_params = request.sampling_params assert sampling_params is not None, "pooling requests not supported yet" if sampling_params.sampling_type == SamplingType.GREEDY: # Should avoid division by zero later when apply_temperature. self.temperature_cpu[req_index] = 0.0 self.greedy_reqs.add(req_id) else: self.temperature_cpu[req_index] = sampling_params.temperature self.random_reqs.add(req_id) self.top_p_cpu[req_index] = sampling_params.top_p if sampling_params.top_p < 1: self.top_p_reqs.add(req_id) top_k = sampling_params.top_k if 0 < top_k < self.vocab_size: self.top_k_reqs.add(req_id) else: top_k = self.vocab_size self.top_k_cpu[req_index] = top_k self.min_p_cpu[req_index] = sampling_params.min_p self.frequency_penalties_cpu[req_index] = sampling_params.frequency_penalty if sampling_params.min_p > _SAMPLING_EPS: self.min_p_reqs.add(req_id) if sampling_params.frequency_penalty != 0.0: self.frequency_penalties_reqs.add(req_id) self.presence_penalties_cpu[req_index] = sampling_params.presence_penalty if sampling_params.presence_penalty != 0.0: self.presence_penalties_reqs.add(req_id) self.repetition_penalties_cpu[req_index] = sampling_params.repetition_penalty if sampling_params.repetition_penalty != 1.0: self.repetition_penalties_reqs.add(req_id) if sampling_params.min_tokens: self.min_tokens[req_index] = ( sampling_params.min_tokens, sampling_params.all_stop_token_ids, ) # NOTE(woosuk): self.generators should not include the requests that # do not have their own generator. if request.generator is not None: self.generators[req_index] = request.generator if sampling_params.logprobs is not None: self.num_logprobs[req_id] = sampling_params.logprobs if sampling_params.logit_bias is not None: self.logit_bias[req_index] = sampling_params.logit_bias if sampling_params.allowed_token_ids: self.has_allowed_token_ids.add(req_id) if self.allowed_token_ids_mask_cpu_tensor is None: # Lazy allocation for this tensor, which can be large. # False means we don't fill with -inf. self.allowed_token_ids_mask = torch.zeros( self.max_num_reqs, self.vocab_size, dtype=torch.bool, device=self.device, ) self.allowed_token_ids_mask_cpu_tensor = torch.zeros( self.max_num_reqs, self.vocab_size, dtype=torch.bool, device="cpu" ) self.allowed_token_ids_mask_cpu_tensor[req_index] = True # False means we don't fill with -inf. self.allowed_token_ids_mask_cpu_tensor[req_index][ sampling_params.allowed_token_ids ] = False if sampling_params.bad_words_token_ids: self.bad_words_token_ids[req_index] = sampling_params.bad_words_token_ids # Add request lora ID if request.lora_request: lora_id = request.lora_request.lora_int_id if lora_id not in self.lora_id_to_request_ids: self.lora_id_to_request_ids[lora_id] = set() self.request_lora_mapping[req_index] = lora_id self.lora_id_to_request_ids[lora_id].add(request.req_id) self.lora_id_to_lora_request[lora_id] = request.lora_request else: # No LoRA self.request_lora_mapping[req_index] = 0 def remove_request(self, req_id: str) -> int | None: """This method must always be followed by a call to condense().""" req_index = self.req_id_to_index.pop(req_id, None) if req_index is None: return None self._req_ids[req_index] = None self.req_output_token_ids[req_index] = None self.greedy_reqs.discard(req_id) self.random_reqs.discard(req_id) self.top_p_reqs.discard(req_id) self.top_k_reqs.discard(req_id) self.min_p_reqs.discard(req_id) self.min_tokens.pop(req_index, None) self.frequency_penalties_reqs.discard(req_id) self.presence_penalties_reqs.discard(req_id) self.repetition_penalties_reqs.discard(req_id) self.generators.pop(req_index, None) self.num_logprobs.pop(req_id, None) self.in_progress_prompt_logprobs_cpu.pop(req_id, None) # LoRA lora_id = self.request_lora_mapping[req_index] if lora_id != 0: self.lora_id_to_request_ids[lora_id].discard(req_id) if len(self.lora_id_to_request_ids[lora_id]) == 0: self.lora_id_to_request_ids.pop(lora_id) self.lora_id_to_lora_request.pop(lora_id) self.request_lora_mapping[req_index] = 0 self.logit_bias[req_index] = None self.has_allowed_token_ids.discard(req_id) if self.allowed_token_ids_mask_cpu_tensor is not None: # False means we don't fill with -inf. self.allowed_token_ids_mask_cpu_tensor[req_index].fill_(False) self.bad_words_token_ids.pop(req_index, None) return req_index def swap_states(self, i1: int, i2: int) -> None: old_id_i1 = self._req_ids[i1] old_id_i2 = self._req_ids[i2] self._req_ids[i1], self._req_ids[i2] = self._req_ids[i2], self._req_ids[i1] # noqa self.req_output_token_ids[i1], self.req_output_token_ids[i2] = ( self.req_output_token_ids[i2], self.req_output_token_ids[i1], ) assert old_id_i1 is not None and old_id_i2 is not None self.req_id_to_index[old_id_i1], self.req_id_to_index[old_id_i2] = ( self.req_id_to_index[old_id_i2], self.req_id_to_index[old_id_i1], ) self.num_tokens_no_spec[i1], self.num_tokens_no_spec[i2] = ( self.num_tokens_no_spec[i2], self.num_tokens_no_spec[i1], ) self.num_prompt_tokens[i1], self.num_prompt_tokens[i2] = ( self.num_prompt_tokens[i2], self.num_prompt_tokens[i1], ) self.num_computed_tokens_cpu[i1], self.num_computed_tokens_cpu[i2] = ( self.num_computed_tokens_cpu[i2], self.num_computed_tokens_cpu[i1], ) self.temperature_cpu[i1], self.temperature_cpu[i2] = ( self.temperature_cpu[i2], self.temperature_cpu[i1], ) self.top_p_cpu[i1], self.top_p_cpu[i2] = self.top_p_cpu[i2], self.top_p_cpu[i1] self.top_k_cpu[i1], self.top_k_cpu[i2] = self.top_k_cpu[i2], self.top_k_cpu[i1] self.frequency_penalties_cpu[i1], self.frequency_penalties_cpu[i2] = ( self.frequency_penalties_cpu[i2], self.frequency_penalties_cpu[i1], ) self.presence_penalties_cpu[i1], self.presence_penalties_cpu[i2] = ( self.presence_penalties_cpu[i2], self.presence_penalties_cpu[i1], ) self.repetition_penalties_cpu[i1], self.repetition_penalties_cpu[i2] = ( self.repetition_penalties_cpu[i2], self.repetition_penalties_cpu[i1], ) self.min_p_cpu[i1], self.min_p_cpu[i2] = self.min_p_cpu[i2], self.min_p_cpu[i1] # NOTE: the following is unsafe # self.token_ids_cpu[i1, ...], self.token_ids_cpu[i2, ...], =\ # self.token_ids_cpu[i2, ...], self.token_ids_cpu[i1, ...] # instead, we need to temporarily copy the data for one of the indices # TODO(lucas): optimize this by only copying valid indices tmp = self.token_ids_cpu[i1, ...].copy() self.token_ids_cpu[i1, ...] = self.token_ids_cpu[i2, ...] self.token_ids_cpu[i2, ...] = tmp swap_dict_values(self.generators, i1, i2) swap_dict_values(self.min_tokens, i1, i2) swap_dict_values(self.bad_words_token_ids, i1, i2) self.request_lora_mapping[i1], self.request_lora_mapping[i2] = ( self.request_lora_mapping[i2], self.request_lora_mapping[i1], ) self.logit_bias[i1], self.logit_bias[i2] = ( self.logit_bias[i2], self.logit_bias[i1], ) if self.allowed_token_ids_mask_cpu_tensor is not None: ( self.allowed_token_ids_mask_cpu_tensor[i1], self.allowed_token_ids_mask_cpu_tensor[i2], ) = ( self.allowed_token_ids_mask_cpu_tensor[i2], self.allowed_token_ids_mask_cpu_tensor[i1], ) self.block_table.swap_row(i1, i2) def condense(self, empty_req_indices: list[int]) -> None: """Move non-empty requests down into lower, empty indices. Args: empty_req_indices: empty batch indices, sorted descending. """ num_reqs = self.num_reqs if num_reqs == 0: # The batched states are empty. self._req_ids.clear() self.req_output_token_ids.clear() return # NOTE(woosuk): This function assumes that the empty_req_indices # is sorted in descending order. last_req_index = num_reqs + len(empty_req_indices) - 1 while empty_req_indices: # Find the largest non-empty index. while last_req_index in empty_req_indices: last_req_index -= 1 # Find the smallest empty index. empty_index = empty_req_indices.pop() if empty_index >= last_req_index: break # Swap the states. req_id = self._req_ids[last_req_index] output_token_ids = self.req_output_token_ids[last_req_index] assert req_id is not None self._req_ids[empty_index] = req_id self._req_ids[last_req_index] = None self.req_output_token_ids[empty_index] = output_token_ids self.req_output_token_ids[last_req_index] = None self.req_id_to_index[req_id] = empty_index num_tokens = self.num_tokens_no_spec[last_req_index] self.token_ids_cpu[empty_index, :num_tokens] = self.token_ids_cpu[ last_req_index, :num_tokens ] self.num_tokens_no_spec[empty_index] = self.num_tokens_no_spec[ last_req_index ] self.num_prompt_tokens[empty_index] = self.num_prompt_tokens[last_req_index] self.num_computed_tokens_cpu[empty_index] = self.num_computed_tokens_cpu[ last_req_index ] self.block_table.move_row(last_req_index, empty_index) self.temperature_cpu[empty_index] = self.temperature_cpu[last_req_index] self.top_p_cpu[empty_index] = self.top_p_cpu[last_req_index] self.top_k_cpu[empty_index] = self.top_k_cpu[last_req_index] self.frequency_penalties_cpu[empty_index] = self.frequency_penalties_cpu[ last_req_index ] self.presence_penalties_cpu[empty_index] = self.presence_penalties_cpu[ last_req_index ] self.repetition_penalties_cpu[empty_index] = self.repetition_penalties_cpu[ last_req_index ] self.min_p_cpu[empty_index] = self.min_p_cpu[last_req_index] generator = self.generators.pop(last_req_index, None) if generator is not None: self.generators[empty_index] = generator min_token = self.min_tokens.pop(last_req_index, None) if min_token is not None: self.min_tokens[empty_index] = min_token self.request_lora_mapping[empty_index] = self.request_lora_mapping[ last_req_index ] self.logit_bias[empty_index] = self.logit_bias[last_req_index] if self.allowed_token_ids_mask_cpu_tensor is not None: self.allowed_token_ids_mask_cpu_tensor[empty_index] = ( self.allowed_token_ids_mask_cpu_tensor[last_req_index] ) bad_words_token_ids = self.bad_words_token_ids.pop(last_req_index, None) if bad_words_token_ids is not None: self.bad_words_token_ids[empty_index] = bad_words_token_ids # Decrement last_req_index since it is now empty. last_req_index -= 1 # Trim lists to the batch size. del self._req_ids[self.num_reqs :] del self.req_output_token_ids[self.num_reqs :] def _make_prompt_token_ids_tensor(self) -> torch.Tensor: max_prompt_len = self.num_prompt_tokens[: self.num_reqs].max() prompt_token_ids_cpu_tensor = torch.empty( (self.num_reqs, max_prompt_len), device="cpu", dtype=torch.int64, pin_memory=self.pin_memory, ) prompt_token_ids = prompt_token_ids_cpu_tensor.numpy() prompt_token_ids[:] = self.token_ids_cpu[: self.num_reqs, :max_prompt_len] # Use the value of vocab_size as a pad since we don't have a # token_id of this value. for i in range(self.num_reqs): prompt_token_ids[i, self.num_prompt_tokens[i] :] = self.vocab_size return prompt_token_ids_cpu_tensor.to(device=self.device, non_blocking=True) def make_lora_inputs( self, num_scheduled_tokens: np.ndarray, num_sampled_tokens: np.ndarray ) -> tuple[tuple[int, ...], tuple[int, ...], set[LoRARequest]]: """ Given the num_scheduled_tokens for each request in the batch, return datastructures used to activate the current LoRAs. Returns: 1. prompt_lora_mapping: A tuple of size self.num_reqs where, prompt_lora_mapping[i] is the LoRA id to use for the ith prompt. 2. token_lora_mapping: A tuple of size np.sum(num_scheduled_tokens) where, token_lora_mapping[i] is the LoRA id to use for ith token. 3. lora_requests: Set of relevant LoRA requests. """ req_lora_mapping = self.request_lora_mapping[: self.num_reqs] prompt_lora_mapping = tuple(req_lora_mapping) token_lora_mapping = tuple(req_lora_mapping.repeat(num_scheduled_tokens)) active_lora_requests: set[LoRARequest] = set( self.lora_id_to_lora_request.values() ) return prompt_lora_mapping, token_lora_mapping, active_lora_requests @property def num_reqs(self) -> int: return len(self.req_id_to_index) @property def all_greedy(self) -> bool: return len(self.random_reqs) == 0 @property def all_random(self) -> bool: return len(self.greedy_reqs) == 0 @property def no_top_p(self) -> bool: return len(self.top_p_reqs) == 0 @property def no_top_k(self) -> bool: return len(self.top_k_reqs) == 0 @property def no_min_p(self) -> bool: return len(self.min_p_reqs) == 0 @property def no_penalties(self) -> bool: return ( len(self.presence_penalties_reqs) == 0 and len(self.frequency_penalties_reqs) == 0 and len(self.repetition_penalties_reqs) == 0 ) @property def max_num_logprobs(self) -> int | None: return max(self.num_logprobs.values()) if self.num_logprobs else None @property def no_allowed_token_ids(self) -> bool: return len(self.has_allowed_token_ids) == 0
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/kv_connector_model_runner_mixin.py
vllm/v1/worker/kv_connector_model_runner_mixin.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Define KV connector functionality mixin for model runners. """ import copy from collections.abc import Generator from contextlib import AbstractContextManager, contextmanager, nullcontext from typing import TYPE_CHECKING import torch from vllm.attention.backends.abstract import AttentionBackend from vllm.config import VllmConfig from vllm.config.cache import CacheDType from vllm.distributed.kv_transfer import ( ensure_kv_transfer_shutdown, get_kv_transfer_group, has_kv_transfer_group, ) from vllm.distributed.kv_transfer.kv_connector.base import KVConnectorBase from vllm.forward_context import get_forward_context, set_forward_context from vllm.logger import init_logger from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheConfig from vllm.v1.outputs import ( EMPTY_MODEL_RUNNER_OUTPUT, KVConnectorOutput, ModelRunnerOutput, ) from vllm.v1.worker.utils import AttentionGroup if TYPE_CHECKING: from vllm.v1.core.sched.output import SchedulerOutput logger = init_logger(__name__) # Defined as a kv connector functionality mixin for ModelRunner (GPU, TPU) class KVConnectorModelRunnerMixin: @staticmethod def maybe_setup_kv_connector(scheduler_output: "SchedulerOutput"): # Update KVConnector with the KVConnector metadata forward(). if has_kv_transfer_group(): kv_connector = get_kv_transfer_group() assert isinstance(kv_connector, KVConnectorBase) assert scheduler_output.kv_connector_metadata is not None kv_connector.bind_connector_metadata(scheduler_output.kv_connector_metadata) # Background KV cache transfers happen here. # These transfers are designed to be async and the requests # involved may be disjoint from the running requests. # Do this here to save a collective_rpc. kv_connector.start_load_kv(get_forward_context()) @staticmethod def ensure_kv_transfer_shutdown() -> None: # has_kv_transfer_group can be None during interpreter shutdown. if has_kv_transfer_group and has_kv_transfer_group(): # type: ignore[truthy-function] ensure_kv_transfer_shutdown() @staticmethod def maybe_wait_for_kv_save() -> None: if has_kv_transfer_group(): get_kv_transfer_group().wait_for_save() @staticmethod def get_finished_kv_transfers( scheduler_output: "SchedulerOutput", ) -> tuple[set[str] | None, set[str] | None]: if has_kv_transfer_group(): return get_kv_transfer_group().get_finished( scheduler_output.finished_req_ids ) return None, None @staticmethod def kv_connector_no_forward( scheduler_output: "SchedulerOutput", vllm_config: VllmConfig ) -> ModelRunnerOutput: # KV send/recv even if no work to do. with ( set_forward_context(None, vllm_config), KVConnectorModelRunnerMixin._get_kv_connector_output( scheduler_output, wait_for_save=False ) as kv_connector_output, ): pass if kv_connector_output.is_empty(): return EMPTY_MODEL_RUNNER_OUTPUT output = copy.copy(EMPTY_MODEL_RUNNER_OUTPUT) output.kv_connector_output = kv_connector_output return output @staticmethod def maybe_get_kv_connector_output( scheduler_output: "SchedulerOutput", ) -> AbstractContextManager[KVConnectorOutput | None]: return ( KVConnectorModelRunnerMixin._get_kv_connector_output(scheduler_output) if has_kv_transfer_group() else nullcontext() ) # This context manager must be used within an active forward context. # It encapsulates the entire KV connector lifecycle within execute_model @staticmethod @contextmanager def _get_kv_connector_output( scheduler_output: "SchedulerOutput", wait_for_save: bool = True ) -> Generator[KVConnectorOutput, None, None]: output = KVConnectorOutput() # Update KVConnector with the KVConnector metadata forward(). kv_connector = get_kv_transfer_group() assert isinstance(kv_connector, KVConnectorBase) assert scheduler_output.kv_connector_metadata is not None kv_connector.bind_connector_metadata(scheduler_output.kv_connector_metadata) # Background KV cache transfers happen here. # These transfers are designed to be async and the requests # involved may be disjoint from the running requests. # Do this here to save a collective_rpc. kv_connector.start_load_kv(get_forward_context()) try: yield output finally: if wait_for_save: kv_connector.wait_for_save() output.finished_sending, output.finished_recving = ( kv_connector.get_finished(scheduler_output.finished_req_ids) ) output.invalid_block_ids = kv_connector.get_block_ids_with_load_errors() output.kv_connector_stats = kv_connector.get_kv_connector_stats() output.kv_cache_events = kv_connector.get_kv_connector_kv_cache_events() kv_connector.clear_connector_metadata() @staticmethod def use_uniform_kv_cache( attn_groups: list[list[AttentionGroup]], cache_dtype: CacheDType, ) -> bool: """ Determines whether a uniform KV layout should be used. A uniform layout means all layers KV caches will share the same underlying tensor, where for a given block number, the respective KV data for all layers will be contiguous. This will allow efficient KV transfer of per-block KV data for all layers at once. Note this layout will only be applied given 3 conditions: 1. The KV Cache config contains just a single group where all layers have the same page size. 2. A KV connector is configured, and the KV connector instance prefers to use this layout (prefer_cross_layer_blocks() returns True) 2. The flash attention backend supports this layout (get_kv_cache_stride_order(True) includes a placement for a num_layers dimension) Note that the actual placement of the num_layers dimensions in the unified layers tensors will be determined by the attention backend. Thus, the layers KV data may still not be contiguous per block if the attention backend does not support it. Args: attn_groups: The list of attention groups for this model cache_dtype: The KV cache dtype Returns: True if we should use a uniform KV cache layout. """ if not has_kv_transfer_group(): return False if not get_kv_transfer_group().prefer_cross_layer_blocks: return False if len(attn_groups) != 1 or len(attn_groups[0]) != 1: return False attn_group = attn_groups[0][0] kv_cache_spec = attn_group.kv_cache_spec if not isinstance(kv_cache_spec, AttentionSpec): return False attn_backend = attn_group.backend kv_cache_shape = attn_backend.get_kv_cache_shape( 1234, kv_cache_spec.block_size, kv_cache_spec.num_kv_heads, kv_cache_spec.head_size, cache_dtype_str=cache_dtype, ) try: kv_cache_stride_order = attn_backend.get_kv_cache_stride_order( include_num_layers_dimension=True ) except (AttributeError, NotImplementedError): return False # check that attention backend include a layers dimension return len(kv_cache_stride_order) == len(kv_cache_shape) + 1 @staticmethod def allocate_uniform_kv_caches( kv_cache_config: KVCacheConfig, attn_groups: list[list[AttentionGroup]], cache_dtype: CacheDType, device: torch.device, kernel_block_sizes: list[int], ) -> tuple[dict[str, torch.Tensor], torch.Tensor, type[AttentionBackend]]: """ Initializes and reshapes KV caches for the simple case where all layers have the same layout. This function assumes use_uniform_kv_cache() returned True. Args: kv_cache_config: The KV cache config attn_groups: The list of attention groups for this model cache_dtype: The KV cache dtype device: The torch device to allocate on. kernel_block_sizes: The kernel block sizes for each KV cache group. Returns: A tuple (kv_caches, cross_layers_kv_cache, attn_backend) where: kv_caches is a dict mapping between layer names to their corresponding memory buffer for KV cache. cross_layers_kv_cache is the cross layers kv cache tensor attn_backend is the attention backend matching this tensor """ attn_group = attn_groups[0][0] kv_cache_spec = attn_group.kv_cache_spec assert isinstance(kv_cache_spec, AttentionSpec) tensor_sizes = set( kv_cache_tensor.size for kv_cache_tensor in kv_cache_config.kv_cache_tensors ) assert len(tensor_sizes) == 1 tensor_size = tensor_sizes.pop() page_size = kv_cache_spec.page_size_bytes assert tensor_size % page_size == 0 num_blocks = tensor_size // page_size num_layers = len(kv_cache_config.kv_cache_tensors) total_size = tensor_size * num_layers assert len(kernel_block_sizes) == 1 kernel_block_size = kernel_block_sizes[0] num_blocks_per_kv_block = kv_cache_spec.block_size // kernel_block_size kernel_num_blocks = num_blocks * num_blocks_per_kv_block attn_backend = attn_group.backend kv_cache_shape = attn_backend.get_kv_cache_shape( kernel_num_blocks, kernel_block_size, kv_cache_spec.num_kv_heads, kv_cache_spec.head_size, cache_dtype_str=cache_dtype, ) # prepend a num_layers dimension into the shape kv_cache_shape = (num_layers,) + kv_cache_shape try: kv_cache_stride_order = attn_backend.get_kv_cache_stride_order( include_num_layers_dimension=True ) assert len(kv_cache_stride_order) == len(kv_cache_shape) except (AttributeError, NotImplementedError): kv_cache_stride_order = tuple(range(len(kv_cache_shape))) kv_cache_shape = tuple(kv_cache_shape[i] for i in kv_cache_stride_order) logger.info("Allocating a cross layer KV cache of shape %s", kv_cache_shape) # allocate one contiguous buffer for all layers cross_layers_kv_cache = ( torch.zeros(total_size, dtype=torch.int8, device=device) .view(kv_cache_spec.dtype) .view(kv_cache_shape) ) # Maintain original KV shape view. inv_order = [ kv_cache_stride_order.index(i) for i in range(len(kv_cache_stride_order)) ] permuted_kv_cache = cross_layers_kv_cache.permute(*inv_order) kv_caches = {} for i, kv_cache_tensor in enumerate(kv_cache_config.kv_cache_tensors): tensor = permuted_kv_cache[i] for layer_name in kv_cache_tensor.shared_by: kv_caches[layer_name] = tensor return kv_caches, cross_layers_kv_cache, attn_backend
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/ec_connector_model_runner_mixin.py
vllm/v1/worker/ec_connector_model_runner_mixin.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Define EC connector functionality mixin for model runners. """ from collections.abc import Generator from contextlib import AbstractContextManager, contextmanager, nullcontext from typing import TYPE_CHECKING import torch from vllm.distributed.ec_transfer import get_ec_transfer, has_ec_transfer from vllm.distributed.ec_transfer.ec_connector.base import ECConnectorBase from vllm.logger import init_logger from vllm.v1.outputs import ECConnectorOutput if TYPE_CHECKING: from vllm.v1.core.sched.output import SchedulerOutput logger = init_logger(__name__) # Defined as a EC connector functionality mixin for ModelRunner (GPU, TPU) class ECConnectorModelRunnerMixin: @staticmethod def maybe_save_ec_to_connector( encoder_cache: dict[str, torch.Tensor], mm_hash: str, ): if not has_ec_transfer(): logger.debug("Not have ec transfer please check") return connector = get_ec_transfer() connector.save_caches(encoder_cache=encoder_cache, mm_hash=mm_hash) @staticmethod def get_finished_ec_transfers( scheduler_output: "SchedulerOutput", ) -> tuple[set[str] | None, set[str] | None]: if has_ec_transfer(): return get_ec_transfer().get_finished(scheduler_output.finished_req_ids) return None, None @staticmethod def maybe_get_ec_connector_output( scheduler_output: "SchedulerOutput", encoder_cache: dict[str, torch.Tensor], **kwargs, ) -> AbstractContextManager[ECConnectorOutput | None]: return ( ECConnectorModelRunnerMixin._get_ec_connector_output( scheduler_output, encoder_cache, **kwargs ) if has_ec_transfer() else nullcontext() ) # This context manager must be used within an active forward context. # It encapsulates the entire EC connector lifecycle within execute_model @staticmethod @contextmanager def _get_ec_connector_output( scheduler_output: "SchedulerOutput", encoder_cache: dict[str, torch.Tensor], **kwargs, ) -> Generator[ECConnectorOutput, None, None]: output = ECConnectorOutput() ec_connector = get_ec_transfer() assert isinstance(ec_connector, ECConnectorBase) assert scheduler_output.ec_connector_metadata is not None ec_connector.bind_connector_metadata(scheduler_output.ec_connector_metadata) if not ec_connector.is_producer: ec_connector.start_load_caches(encoder_cache, **kwargs) try: yield output finally: output.finished_sending, output.finished_recving = ( ec_connector.get_finished(scheduler_output.finished_req_ids) ) ec_connector.clear_connector_metadata()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/block_table.py
vllm/v1/worker/block_table.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import numpy as np import torch from vllm.distributed import get_dcp_group, get_pcp_group from vllm.logger import init_logger from vllm.utils.math_utils import cdiv from vllm.v1.utils import CpuGpuBuffer logger = init_logger(__name__) class BlockTable: def __init__( self, block_size: int, max_num_reqs: int, max_num_blocks_per_req: int, max_num_batched_tokens: int, pin_memory: bool, device: torch.device, kernel_block_size: int, cp_kv_cache_interleave_size: int, ): """ Args: block_size: Block size used for KV cache memory allocation max_num_reqs: Maximum number of concurrent requests supported. max_num_blocks_per_req: Maximum number of blocks per request. max_num_batched_tokens: Maximum number of tokens in a batch. pin_memory: Whether to pin memory for faster GPU transfers. device: Target device for the block table. kernel_block_size: The block_size of underlying attention kernel. Will be the same as `block_size` if `block_size` is supported by the attention kernel. """ self.max_num_reqs = max_num_reqs self.max_num_batched_tokens = max_num_batched_tokens self.pin_memory = pin_memory self.device = device if kernel_block_size == block_size: # Standard case: allocation and computation use same block size # No block splitting needed, direct mapping self.block_size = block_size self.blocks_per_kv_block = 1 self.use_hybrid_blocks = False else: # Hybrid case: allocation block size differs from kernel block size # Memory blocks are subdivided to match kernel requirements # Example: 32-token memory blocks with 16-token kernel blocks # → Each memory block corresponds to 2 kernel blocks if block_size % kernel_block_size != 0: raise ValueError( f"kernel_block_size {kernel_block_size} must divide " f"kv_manager_block_size size {block_size} evenly" ) self.block_size = kernel_block_size self.blocks_per_kv_block = block_size // kernel_block_size self.use_hybrid_blocks = True self.max_num_blocks_per_req = max_num_blocks_per_req * self.blocks_per_kv_block self.block_table = self._make_buffer( self.max_num_reqs, self.max_num_blocks_per_req, dtype=torch.int32 ) self.num_blocks_per_row = np.zeros(max_num_reqs, dtype=np.int32) self.slot_mapping = self._make_buffer( self.max_num_batched_tokens, dtype=torch.int64 ) if self.use_hybrid_blocks: self._kernel_block_arange = np.arange(0, self.blocks_per_kv_block).reshape( 1, -1 ) else: self._kernel_block_arange = None try: self.pcp_world_size = get_pcp_group().world_size self.pcp_rank = get_pcp_group().rank_in_group except AssertionError: # PCP might not be initialized in testing self.pcp_world_size = 1 self.pcp_rank = 0 try: self.dcp_world_size = get_dcp_group().world_size self.dcp_rank = get_dcp_group().rank_in_group except AssertionError: # DCP might not be initialized in testing self.dcp_world_size = 1 self.dcp_rank = 0 self.cp_kv_cache_interleave_size = cp_kv_cache_interleave_size def append_row( self, block_ids: list[int], row_idx: int, ) -> None: if not block_ids: return if self.use_hybrid_blocks: block_ids = self.map_to_kernel_blocks( np.array(block_ids), self.blocks_per_kv_block, self._kernel_block_arange ) num_blocks = len(block_ids) start = self.num_blocks_per_row[row_idx] self.num_blocks_per_row[row_idx] += num_blocks self.block_table.np[row_idx, start : start + num_blocks] = block_ids def add_row(self, block_ids: list[int], row_idx: int) -> None: self.num_blocks_per_row[row_idx] = 0 self.append_row(block_ids, row_idx) def move_row(self, src: int, tgt: int) -> None: num_blocks = self.num_blocks_per_row[src] block_table_np = self.block_table.np block_table_np[tgt, :num_blocks] = block_table_np[src, :num_blocks] self.num_blocks_per_row[tgt] = num_blocks def swap_row(self, src: int, tgt: int) -> None: src_tgt, tgt_src = [src, tgt], [tgt, src] self.num_blocks_per_row[src_tgt] = self.num_blocks_per_row[tgt_src] self.block_table.np[src_tgt] = self.block_table.np[tgt_src] def compute_slot_mapping( self, req_indices: np.ndarray, positions: np.ndarray ) -> None: # E.g., [0, 1, 0, 1, 2, 3, 4, 0, 1, 2] # -> [0, 0, K, K, K + 1, K + 1, K + 2, 2 * K, 2 * K, 2 * K + 1] # where K is the max_num_blocks_per_req and the block size is 2. # NOTE(woosuk): We can't simply use `token_indices // block_size` # here because M (max_model_len) is not necessarily divisible by # block_size. total_cp_world_size = self.pcp_world_size * self.dcp_world_size total_cp_rank = self.pcp_rank * self.dcp_world_size + self.dcp_rank if total_cp_world_size > 1: # Note(hc): The DCP implement store kvcache with an interleave # style, the kvcache for the token whose token_idx is i is # always stored on the GPU whose dcp_rank equals i % cp_world_size: # Use a "virtual block" which equals to world_size * block_size # for block_table_indices calculation. virtual_block_size = self.block_size * total_cp_world_size block_table_indices = ( req_indices * self.max_num_blocks_per_req + positions // virtual_block_size ) block_numbers = self.block_table.np.ravel()[block_table_indices] # Use virtual_block_size for mask calculation, which marks local # tokens. virtual_block_offsets = positions % virtual_block_size mask = ( virtual_block_offsets // self.cp_kv_cache_interleave_size % total_cp_world_size == total_cp_rank ) # Calculate local block_offsets block_offsets = ( virtual_block_offsets // (total_cp_world_size * self.cp_kv_cache_interleave_size) * self.cp_kv_cache_interleave_size + virtual_block_offsets % self.cp_kv_cache_interleave_size ) # Calculate slot_mapping slot_mapping = block_numbers * self.block_size + block_offsets # Write final slots, use -1 for not-local self.slot_mapping.np[: req_indices.shape[0]] = np.where( mask, slot_mapping, -1 ) else: block_table_indices = ( req_indices * self.max_num_blocks_per_req + positions // self.block_size ) block_numbers = self.block_table.np.ravel()[block_table_indices] block_offsets = positions % self.block_size np.add( block_numbers * self.block_size, block_offsets, out=self.slot_mapping.np[: req_indices.shape[0]], ) def commit_block_table(self, num_reqs: int) -> None: self.block_table.copy_to_gpu(num_reqs) def commit_slot_mapping(self, num_tokens: int) -> None: self.slot_mapping.copy_to_gpu(num_tokens) def clear(self) -> None: self.block_table.gpu.fill_(0) self.block_table.cpu.fill_(0) @staticmethod def map_to_kernel_blocks( kv_manager_block_ids: np.ndarray, blocks_per_kv_block: int, kernel_block_arange: np.ndarray, ) -> np.ndarray: """Convert kv_manager_block_id IDs to kernel block IDs. Example: # kv_manager_block_ids: 32 tokens, # Kernel block size: 16 tokens # blocks_per_kv_block = 2 >>> kv_manager_block_ids = np.array([0, 1, 2]) >>> Result: [0, 1, 2, 3, 4, 5] # Each kv_manager_block_id maps to 2 kernel block id: # kv_manager_block_id 0 → kernel block id [0, 1] # kv_manager_block_id 1 → kernel block id [2, 3] # kv_manager_block_id 2 → kernel block id [4, 5] """ if blocks_per_kv_block == 1: return kv_manager_block_ids kernel_block_ids = ( kv_manager_block_ids.reshape(-1, 1) * blocks_per_kv_block + kernel_block_arange ) return kernel_block_ids.reshape(-1) def get_device_tensor(self, num_reqs: int) -> torch.Tensor: """Returns the device tensor of the block table.""" return self.block_table.gpu[:num_reqs] def get_cpu_tensor(self) -> torch.Tensor: """Returns the CPU tensor of the block table.""" return self.block_table.cpu def get_numpy_array(self) -> np.ndarray: """Returns the numpy array of the block table.""" return self.block_table.np def _make_buffer( self, *size: int | torch.SymInt, dtype: torch.dtype ) -> CpuGpuBuffer: return CpuGpuBuffer( *size, dtype=dtype, device=self.device, pin_memory=self.pin_memory ) class MultiGroupBlockTable: """The BlockTables for each KV cache group.""" def __init__( self, max_num_reqs: int, max_model_len: int, max_num_batched_tokens: int, pin_memory: bool, device: torch.device, block_sizes: list[int], kernel_block_sizes: list[int], num_speculative_tokens: int = 0, cp_kv_cache_interleave_size: int = 1, ) -> None: # Note(hc): each dcp rank only store # (max_model_len//dcp_world_size) tokens in kvcache, # so the block_size which used for calc max_num_blocks_per_req # must be multiplied by dcp_world_size. try: pcp_world_size = get_pcp_group().world_size except AssertionError: # PCP might not be initialized in testing pcp_world_size = 1 try: dcp_world_size = get_dcp_group().world_size except AssertionError: # DCP might not be initialized in testing dcp_world_size = 1 if len(kernel_block_sizes) != len(block_sizes): raise ValueError( f"kernel_block_sizes length ({len(kernel_block_sizes)}) " f"must match block_sizes length ({len(block_sizes)})" ) total_cp_world_size = dcp_world_size * pcp_world_size self.block_tables = [ BlockTable( block_size, max_num_reqs, max( cdiv(max_model_len, block_size * total_cp_world_size), 1 + num_speculative_tokens, ), max_num_batched_tokens, pin_memory, device, kernel_block_size, cp_kv_cache_interleave_size, ) for block_size, kernel_block_size in zip(block_sizes, kernel_block_sizes) ] def append_row(self, block_ids: tuple[list[int], ...], row_idx: int) -> None: for i, block_table in enumerate(self.block_tables): block_table.append_row(block_ids[i], row_idx) def add_row(self, block_ids: tuple[list[int], ...], row_idx: int) -> None: for i, block_table in enumerate(self.block_tables): block_table.add_row(block_ids[i], row_idx) def move_row(self, src: int, tgt: int) -> None: for block_table in self.block_tables: block_table.move_row(src, tgt) def swap_row(self, src: int, tgt: int) -> None: for block_table in self.block_tables: block_table.swap_row(src, tgt) def compute_slot_mapping( self, req_indices: np.ndarray, positions: np.ndarray ) -> None: for block_table in self.block_tables: block_table.compute_slot_mapping(req_indices, positions) def commit_block_table(self, num_reqs: int) -> None: for block_table in self.block_tables: block_table.commit_block_table(num_reqs) def commit_slot_mapping(self, num_tokens: int) -> None: for block_table in self.block_tables: block_table.commit_slot_mapping(num_tokens) def clear(self) -> None: for block_table in self.block_tables: block_table.clear() def __getitem__(self, idx: int) -> "BlockTable": """Returns the BlockTable for the i-th KV cache group.""" return self.block_tables[idx]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/tpu_model_runner.py
vllm/v1/worker/tpu_model_runner.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import bisect import gc import time from typing import TYPE_CHECKING, Any, cast from unittest.mock import patch import numpy as np import torch import torch.nn as nn # TPU XLA related import torch_xla import torch_xla.core.xla_model as xm import torch_xla.distributed.spmd as xs import torch_xla.runtime as xr import vllm.envs as envs from vllm.attention.backends.abstract import AttentionType from vllm.attention.layer import Attention, MLAAttention from vllm.attention.layers.chunked_local_attention import ChunkedLocalAttention from vllm.compilation.wrapper import TorchCompileWithNoGuardsWrapper from vllm.config import ( ParallelConfig, VllmConfig, get_layers_from_vllm_config, update_config, ) from vllm.distributed.kv_transfer import get_kv_transfer_group, has_kv_transfer_group from vllm.distributed.kv_transfer.kv_connector.utils import copy_kv_blocks from vllm.forward_context import set_forward_context from vllm.logger import init_logger from vllm.lora.layers import BaseLayerWithLoRA, LoRAMappingType from vllm.lora.request import LoRARequest from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase from vllm.model_executor.model_loader import get_model_loader from vllm.model_executor.model_loader.tpu import TPUModelLoader from vllm.model_executor.models.interfaces import ( SupportsMultiModal, supports_transcription, ) from vllm.model_executor.models.interfaces_base import ( is_pooling_model, is_text_generation_model, ) from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.inputs import ( BatchedTensorInputs, MultiModalKwargsItem, PlaceholderRange, ) from vllm.multimodal.utils import group_mm_kwargs_by_modality from vllm.sequence import IntermediateTensors from vllm.tasks import GenerationTask, PoolingTask, SupportedTask from vllm.utils.math_utils import cdiv, prev_power_of_2 from vllm.utils.platform_utils import is_pin_memory_available from vllm.v1.attention.backends.pallas import ( TPU_STR_DTYPE_TO_TORCH_DTYPE, PallasAttentionBackend, PallasMetadata, get_page_size_bytes, ) from vllm.v1.kv_cache_interface import ( AttentionSpec, FullAttentionSpec, KVCacheConfig, KVCacheSpec, MLAAttentionSpec, SlidingWindowSpec, ) from vllm.v1.outputs import ( EMPTY_MODEL_RUNNER_OUTPUT, LogprobsLists, LogprobsTensors, ModelRunnerOutput, ) from vllm.v1.sample.tpu.metadata import TPUSupportedSamplingMetadata from vllm.v1.sample.tpu.sampler import Sampler as TPUSampler from vllm.v1.worker.kv_connector_model_runner_mixin import ( KVConnectorModelRunnerMixin, KVConnectorOutput, ) from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin from vllm.v1.worker.tpu_input_batch import CachedRequestState, InputBatch from .utils import ( MultiModalBudget, add_kv_sharing_layers_to_kv_cache_groups, bind_kv_cache, sanity_check_mm_encoder_outputs, ) if TYPE_CHECKING: from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput logger = init_logger(__name__) INVALID_TOKEN_ID = -1 # Smallest output size MIN_NUM_SEQS = 8 ######################################################### # Ways to avoid recompilation ######################################################### # # The model executor has two primary components: # 1. preparing the model and sampler inputs # 2. executing the model and sampler. # The core idea is to avoid any TPU computation during input preparation. For # better compilation tracking and increased flexibility, the model execution and # sampler are divided into several distinct components. # # Below are the detailed steps: # # Step 1 # It is recommended to avoid TPU operations when preparing the model and sampler # inputs. CPU tensors can be prepared and transferred to the XLA device using # cpu_tensor.to(xla_device), which only triggers CPU to TPU transfers and avoids # compilation. # # Step 2 # The TPU execution should be decomposed into subgraphs (4 at the moment): # 1. the main model # 2. selecting hidden states for each request # 3. sampler # 4. encoder. # Each subgraph should be decorated in a torch.compile. This is used to make # sure that we have the same subgraph topology in both dummy_run and # xecute_model. The results from these subgraphs should either be passed to # other subgraphs, or transferred from TPU to CPU using xla_tensor.cpu() for # subsequent processing on the CPU. # # Step 3 # The dummy_run should be comprehensive, ensuring all potential input shapes and # branch predictions are included as subgraph inputs to facilitate # pre-compilation. class TPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin): def __init__( self, vllm_config: VllmConfig, device: torch.device, original_parallel_config: ParallelConfig | None = None, ): self.vllm_config = vllm_config self.model_config = vllm_config.model_config self.cache_config = vllm_config.cache_config self.lora_config = vllm_config.lora_config self.load_config = vllm_config.load_config self.parallel_config = vllm_config.parallel_config self.original_parallel_config = original_parallel_config self.scheduler_config = vllm_config.scheduler_config self.speculative_config = vllm_config.speculative_config self.observability_config = vllm_config.observability_config self.device_config = vllm_config.device_config model_config = self.model_config cache_config = self.cache_config scheduler_config = self.scheduler_config parallel_config = self.parallel_config self.device = device self.check_recompilation = envs.VLLM_XLA_CHECK_RECOMPILATION # SPMD Related self.use_spmd = envs.VLLM_XLA_USE_SPMD if self.use_spmd: num_devices = xr.global_runtime_device_count() mesh_shape = (num_devices, 1) device_ids = np.array(range(num_devices)) self.mesh = xs.Mesh(device_ids, mesh_shape, ("x", "y")) self.enforce_eager = model_config.enforce_eager self.num_xla_graphs = 0 self._update_num_xla_graphs("init") self.pin_memory = is_pin_memory_available() self.dtype = self.model_config.dtype if cache_config.cache_dtype == "auto": model_dtype = self.dtype if isinstance(model_dtype, str): self.kv_cache_dtype = TPU_STR_DTYPE_TO_TORCH_DTYPE[model_dtype] else: self.kv_cache_dtype = model_dtype else: self.kv_cache_dtype = TPU_STR_DTYPE_TO_TORCH_DTYPE[cache_config.cache_dtype] self._hidden_states_dtype = self.dtype self.sliding_window = model_config.get_sliding_window() self.block_size = cache_config.block_size self.max_model_len = model_config.max_model_len self.most_model_len = envs.VLLM_TPU_MOST_MODEL_LEN self.max_num_blocks_per_req = cdiv(self.max_model_len, self.block_size) self.num_blocks_per_most_len_req = ( cdiv(self.most_model_len, self.block_size) if self.most_model_len is not None else None ) # InputBatch needs to work with sampling tensors greater than padding # to avoid dynamic shapes. Also, avoid suboptimal alignment. self.max_num_reqs = max(scheduler_config.max_num_seqs, MIN_NUM_SEQS) self.num_tokens_paddings = _get_token_paddings( min_token_size=16, max_token_size=scheduler_config.max_num_batched_tokens, padding_gap=envs.VLLM_TPU_BUCKET_PADDING_GAP, ) # In case `max_num_tokens < max(num_tokens_paddings)` use the actual # padded max value to pre-allocate data structures and pre-compile. self.max_num_tokens = self.num_tokens_paddings[-1] # Model-related. self.num_attn_layers = model_config.get_num_layers_by_block_type( parallel_config, "attention" ) self.num_query_heads = model_config.get_num_attention_heads(parallel_config) self.num_kv_heads = model_config.get_num_kv_heads(parallel_config) self.head_size = model_config.get_head_size() self.inputs_embeds_size = model_config.get_inputs_embeds_size() self.vocab_size = model_config.get_vocab_size() # Multi-modal data support self.mm_registry = MULTIMODAL_REGISTRY self.uses_mrope = model_config.uses_mrope self.supports_mm_inputs = self.mm_registry.supports_multimodal_inputs( model_config ) # TODO: Support M-RoPE (e.g, Qwen2-VL) assert not self.uses_mrope, "TPU does not support M-RoPE yet." self._num_slices_per_kv_cache_update_block = ( _get_num_slices_per_kv_cache_update_block( get_page_size_bytes( block_size=self.block_size, num_kv_heads=self.num_kv_heads, head_size=self.head_size, kv_cache_dtype=self.kv_cache_dtype, ) ) ) # Lazy initialization self.model: nn.Module # Set after load_model self.kv_caches: list[torch.Tensor] = [] # mm_hash -> encoder_output self.encoder_cache: dict[str, torch.Tensor] = {} # Request states. self.requests: dict[str, CachedRequestState] = {} # NOTE(rob): num_prompt_logprobs only includes reqs # that are currently in the prefill phase. self.num_prompt_logprobs: dict[str, int] = {} # Initialize input batch early to avoid AttributeError in _update_states self.input_batch = InputBatch( max_num_reqs=self.max_num_reqs, max_model_len=self.max_model_len, max_num_batched_tokens=self.max_num_tokens, device=self.device, pin_memory=self.pin_memory, vocab_size=self.model_config.get_vocab_size(), block_sizes=[self.block_size], kernel_block_sizes=[self.cache_config.block_size], ) # Cached torch/numpy tensor # The pytorch tensor and numpy array share the same buffer. # Sometimes the numpy op is faster so we create both. self.input_ids_cpu = torch.zeros( self.max_num_tokens, dtype=torch.int32, device="cpu" ) self.positions_cpu = torch.zeros( self.max_num_tokens, dtype=torch.int32, device="cpu" ) self.positions_np = self.positions_cpu.numpy() self.block_table_cpu = torch.zeros( (self.max_num_reqs, self.max_num_blocks_per_req), dtype=torch.int32, device="cpu", ) # adjust num_reqs to avoid SMEM OOM. self.num_reqs_most_model_len = ( min( PallasAttentionBackend.get_max_num_seqs( self.most_model_len, self.block_size ), self.max_num_reqs, ) if self.most_model_len is not None else None ) self.num_reqs_max_model_len = min( PallasAttentionBackend.get_max_num_seqs( self.max_model_len, self.block_size ), self.max_num_reqs, ) self.query_start_loc_cpu = torch.zeros( self.max_num_tokens + 1, dtype=torch.int32, device="cpu", pin_memory=self.pin_memory, ) self.query_start_loc_np = self.query_start_loc_cpu.numpy() self.seq_lens_cpu = torch.zeros( self.max_num_tokens, dtype=torch.int32, device="cpu", pin_memory=self.pin_memory, ) self.seq_lens_np = self.seq_lens_cpu.numpy() # Only relevant for multimodal models if self.supports_mm_inputs: self.is_mm_embed_cpu = torch.zeros( self.max_num_tokens, dtype=torch.bool, device="cpu", pin_memory=self.pin_memory, ) # Range tensor with values [0 .. self.max_num_tokens - 1]. # Used to initialize positions / context_lens / seq_lens # Keep in int64 to avoid overflow with long context self.arange_np = np.arange(self.max_num_tokens, dtype=np.int64) self.num_reqs_paddings = _get_req_paddings( min_req_size=MIN_NUM_SEQS, max_req_size=self.max_num_reqs ) # Layer pairings for cross-layer KV sharing. # If an Attention layer `layer_name` is in the keys of this dict, it # means this layer will perform attention using the keys and values # from the KV cache of `shared_kv_cache_layers[layer_name]`. self.shared_kv_cache_layers: dict[str, str] = {} # tensors for structured decoding self.grammar_bitmask_cpu = torch.zeros( (self.max_num_reqs, cdiv(self.vocab_size, 32)), dtype=torch.int32, device="cpu", pin_memory=self.pin_memory, ) self.require_structured_out_cpu = torch.zeros( (self.max_num_reqs, 1), dtype=torch.bool, device="cpu", pin_memory=self.pin_memory, ) self.structured_decode_arange = torch.arange( 0, 32, device="cpu", pin_memory=self.pin_memory ) self.mm_budget = ( MultiModalBudget( self.model_config, self.scheduler_config, self.mm_registry, ) if self.supports_mm_inputs else None ) if not self.use_spmd: self.sample_from_logits_func = torch.compile( self.sample_from_logits, backend="openxla", fullgraph=True, dynamic=False, ) else: self.sample_from_logits_func = self.sample_from_logits # For passing scheduler_output between successive # execute_model() and sample_tokens() calls. self.scheduler_output: SchedulerOutput | None = None self.mm_embed_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None def reset_mm_cache(self) -> None: if self.mm_budget: self.mm_budget.reset_cache() def _update_num_xla_graphs(self, case_str): check_comp = self.check_recompilation and not self.enforce_eager if not check_comp: return total_cached_graphs = xr.get_num_cached_compilation_graph() new_compiled_graphs = total_cached_graphs - self.num_xla_graphs if new_compiled_graphs == 0: return logger.info( "Add new %d compiled XLA graphs due to %s", new_compiled_graphs, case_str ) self.num_xla_graphs += new_compiled_graphs def _verify_num_xla_graphs(self, case_str): check_comp = self.check_recompilation and not self.enforce_eager if not check_comp: return curr_cached_graph = xr.get_num_cached_compilation_graph() assert self.num_xla_graphs == curr_cached_graph, ( "Recompilation after warm up is detected during {}." " num_xla_graphs = {} curr_cached_graph = {}".format( case_str, self.num_xla_graphs, curr_cached_graph ) ) def _update_states(self, scheduler_output: "SchedulerOutput") -> bool: """Update the cached states and the persistent batch with the scheduler output. The updated states are used by the `_prepare_inputs` function to create the input GPU tensors for the model. Returns: True if there is a new/resumed/paused/finished request. If False, we can skip copying SamplingMetadata to the GPU. """ # Remove finished requests from the cached states. for req_id in scheduler_output.finished_req_ids: self.requests.pop(req_id, None) self.num_prompt_logprobs.pop(req_id, None) # Remove the finished requests from the persistent batch. # NOTE(woosuk): There could be an edge case where finished_req_ids and # scheduled_req_ids overlap. This happens when a request is aborted and # then resubmitted with the same ID. In this case, we treat them as two # distinct requests - clearing the cached states for the first request # and handling the second as a new request. removed_req_indices: list[int] = [] for req_id in scheduler_output.finished_req_ids: req_index = self.input_batch.remove_request(req_id) if req_index is not None: removed_req_indices.append(req_index) # Free the cached encoder outputs. for mm_hash in scheduler_output.free_encoder_mm_hashes: self.encoder_cache.pop(mm_hash, None) # Remove the unscheduled requests from the persistent batch. # NOTE(woosuk): The unscheduled requests are either preempted requests # or running requests that are not scheduled in this step. We remove # them from the persistent batch but keep their cached states since # they will be scheduled again sometime in the future. scheduled_req_ids = scheduler_output.num_scheduled_tokens.keys() cached_req_ids = self.input_batch.req_id_to_index.keys() unscheduled_req_ids = cached_req_ids - scheduled_req_ids # NOTE(woosuk): The persistent batch optimization assumes that # consecutive batches contain mostly the same requests. If batches # have low request overlap (e.g., alternating between two distinct # sets of requests), this optimization becomes very inefficient. for req_id in unscheduled_req_ids: req_index = self.input_batch.remove_request(req_id) assert req_index is not None removed_req_indices.append(req_index) req_ids_to_add: list[str] = [] # Add new requests to the cached states. for new_req_data in scheduler_output.scheduled_new_reqs: assert new_req_data.sampling_params is not None, ( "Pooling is not supported in TPU yet" ) req_id = new_req_data.req_id sampling_params = new_req_data.sampling_params self.requests[req_id] = CachedRequestState( req_id=req_id, prompt_token_ids=new_req_data.prompt_token_ids, prompt_embeds=new_req_data.prompt_embeds, mm_features=new_req_data.mm_features, sampling_params=sampling_params, pooling_params=None, generator=None, block_ids=new_req_data.block_ids, num_computed_tokens=new_req_data.num_computed_tokens, output_token_ids=[], lora_request=new_req_data.lora_request, ) if sampling_params and sampling_params.prompt_logprobs is not None: self.num_prompt_logprobs[req_id] = ( self.input_batch.vocab_size if sampling_params.prompt_logprobs == -1 else sampling_params.prompt_logprobs ) req_ids_to_add.append(req_id) # Update the states of the running/resumed requests. req_data = scheduler_output.scheduled_cached_reqs for i, req_id in enumerate(req_data.req_ids): req_state = self.requests[req_id] num_computed_tokens = req_data.num_computed_tokens[i] new_block_ids = req_data.new_block_ids[i] resumed_from_preemption = req_id in req_data.resumed_req_ids # Update the cached states. req_state.num_computed_tokens = num_computed_tokens if not resumed_from_preemption: if new_block_ids is not None: # Append the new blocks to the existing block IDs. for block_ids, new_ids in zip(req_state.block_ids, new_block_ids): block_ids.extend(new_ids) else: assert new_block_ids is not None # The request is resumed from preemption. # Replace the existing block IDs with the new ones. req_state.block_ids = new_block_ids req_index = self.input_batch.req_id_to_index.get(req_id) if req_index is None: # The request is not in the persistent batch. # The request was either preempted and resumed later, or was not # scheduled in the previous step and needs to be added again. req_ids_to_add.append(req_id) continue # Update the persistent batch. self.input_batch.num_computed_tokens_cpu[req_index] = num_computed_tokens if new_block_ids is not None: self.input_batch.block_table.append_row(new_block_ids, req_index) # Add the new or resumed requests to the persistent batch. # The smaller empty indices are filled first. removed_req_indices = sorted(removed_req_indices, reverse=True) for req_id in req_ids_to_add: req_state = self.requests[req_id] # Fill the empty index or append to the end req_index = removed_req_indices.pop() if removed_req_indices else None self.input_batch.add_request(req_state, req_index) # Condense the batched states if there are empty indices. if removed_req_indices: self.input_batch.condense(removed_req_indices) return len(unscheduled_req_ids) > 0 or len(req_ids_to_add) > 0 def get_model(self) -> nn.Module: return self.model def get_supported_generation_tasks(self) -> list[GenerationTask]: model = self.get_model() supported_tasks = list[GenerationTask]() if is_text_generation_model(model): supported_tasks.append("generate") if supports_transcription(model): if model.supports_transcription_only: return ["transcription"] supported_tasks.append("transcription") return supported_tasks def get_supported_pooling_tasks(self) -> list[PoolingTask]: model = self.get_model() if not is_pooling_model(model): return [] return list(model.pooler.get_supported_tasks()) def get_supported_tasks(self) -> tuple[SupportedTask, ...]: tasks = list[SupportedTask]() if self.model_config.runner_type == "generate": tasks.extend(self.get_supported_generation_tasks()) if self.model_config.runner_type == "pooling": tasks.extend(self.get_supported_pooling_tasks()) return tuple(tasks) def get_kv_cache_spec(self) -> dict[str, KVCacheSpec]: """ Generates the KVCacheSpec by parsing the kv cache format from each Attention module in the static forward context. Returns: KVCacheSpec: A dictionary mapping layer names to their KV cache format. Layers that do not need KV cache are not included. """ layers = get_layers_from_vllm_config( self.vllm_config, AttentionLayerBase, # type: ignore[type-abstract] ) block_size = self.vllm_config.cache_config.block_size cache_dtype_str = self.vllm_config.cache_config.cache_dtype kv_cache_spec: dict[str, KVCacheSpec] = {} for layer_name, attn_module in layers.items(): # Classic Attention path if isinstance(attn_module, Attention): if ( kv_tgt_layer := attn_module.kv_sharing_target_layer_name ) is not None: # The layer doesn't need its own KV cache and will use that of # the target layer. We skip creating a KVCacheSpec for it, so # that KV cache management logic will act as this layer does # not exist, and doesn't allocate KV cache for the layer. This # enables the memory saving of cross-layer kv sharing, allowing # a given amount of memory to accommodate longer context lengths # or enable more requests to be processed simultaneously. self.shared_kv_cache_layers[layer_name] = kv_tgt_layer continue if attn_module.attn_type == AttentionType.DECODER: if isinstance(attn_module, ChunkedLocalAttention): logger.warning_once( "Using irope in Pallas is not supported yet, it " "will fall back to global attention for long context." ) if attn_module.sliding_window is not None: kv_cache_spec[layer_name] = SlidingWindowSpec( block_size=block_size, num_kv_heads=attn_module.num_kv_heads, head_size=attn_module.head_size, dtype=self.kv_cache_dtype, sliding_window=attn_module.sliding_window, ) else: kv_cache_spec[layer_name] = FullAttentionSpec( block_size=block_size, num_kv_heads=attn_module.num_kv_heads, head_size=attn_module.head_size, dtype=self.kv_cache_dtype, ) elif attn_module.attn_type in ( AttentionType.ENCODER, AttentionType.ENCODER_ONLY, ): # encoder-only attention does not need KV cache. continue elif attn_module.attn_type == AttentionType.ENCODER_DECODER: raise NotImplementedError else: raise ValueError(f"Unknown attention type: {attn_module.attn_type}") # MLAAttention path elif isinstance(attn_module, MLAAttention): if layer_name in kv_cache_spec: continue kv_cache_spec[layer_name] = MLAAttentionSpec( block_size=block_size, num_kv_heads=1, head_size=attn_module.head_size, dtype=self.kv_cache_dtype, cache_dtype_str=cache_dtype_str, ) else: continue return kv_cache_spec def _get_slot_mapping_metadata( self, num_reqs, num_scheduled_tokens_per_req ) -> np.ndarray: """ Computes metadata for mapping slots to blocks in the key-value (KV) cache for a batch of requests. This function determines, for each request in the batch, how the scheduled tokens are distributed across memory blocks, and generates metadata needed to map slices of tokens to their corresponding positions in the KV cache. Args: num_reqs (int): Number of requests in the current batch. num_scheduled_tokens_per_req (int or np.ndarray): Number of tokens to be scheduled for each request. Returns: np.ndarray: A 2D array of shape (total_block_len, 3), where each row contains: - kv_cache_start_index (int): The starting index in the KV cache for the corresponding slice. - new_kv_start_index (int): The starting index in the new KV cache for the corresponding slice. - slice_len (int): The length of the slice. """ slices_start = self.input_batch.num_computed_tokens_cpu[:num_reqs] slices_end = ( self.input_batch.num_computed_tokens_cpu[:num_reqs] + num_scheduled_tokens_per_req ) local_block_start_idx = slices_start // self.block_size local_block_end_idx = (slices_end - 1) // self.block_size no_repeat_req_indices = self.arange_np[:num_reqs] global_block_start_idx = ( no_repeat_req_indices * self.max_num_blocks_per_req + local_block_start_idx ) block_lens = local_block_end_idx - local_block_start_idx + 1 global_block_start_idx = np.repeat(global_block_start_idx, block_lens) slice_arange = np.concatenate([self.arange_np[:n] for n in block_lens]) global_block_indices = global_block_start_idx + slice_arange block_table_cpu = self.input_batch.block_table[0].get_cpu_tensor() block_numbers = block_table_cpu.flatten()[global_block_indices].numpy() total_block_len = np.sum(block_lens) slot_mapping_slices = np.repeat( np.array([[0, self.block_size]], dtype=np.int32), total_block_len, axis=0 ) cu_block_lens = np.zeros(len(block_lens) + 1, dtype=np.int32) np.cumsum(block_lens, out=cu_block_lens[1:]) for req_idx in range(num_reqs): slot_mapping_slices[cu_block_lens[req_idx]][0] = ( slices_start[req_idx] % self.block_size ) slot_mapping_slices[cu_block_lens[req_idx + 1] - 1][1] = ( slices_end[req_idx] - 1 ) % self.block_size + 1 slice_lens = slot_mapping_slices[:, 1] - slot_mapping_slices[:, 0] cu_slices_lens = np.zeros(len(slice_lens) + 1, dtype=np.int32) np.cumsum(slice_lens, out=cu_slices_lens[1:]) kv_cache_start_indices = slot_mapping_slices[:, 0] + ( block_numbers * self.block_size ) new_kv_start_indices = cu_slices_lens[:-1] slot_mapping_metadata = np.stack( [kv_cache_start_indices, new_kv_start_indices, slice_lens], axis=1 ) return slot_mapping_metadata def _prepare_inputs(self, scheduler_output: "SchedulerOutput", start_index: int): assert scheduler_output.total_num_scheduled_tokens > 0 num_reqs = self.input_batch.num_reqs assert num_reqs > 0 assert start_index < num_reqs # Get the number of scheduled tokens for each request. use_max_model_len = self.most_model_len is None num_scheduled_tokens_per_req = [] max_num_scheduled_tokens_all_reqs = 0 end_index = start_index # Use either most_model_len or max_model_len depending on request size. for i in range(start_index, num_reqs): req_id = self.input_batch.req_ids[i] assert req_id is not None num_tokens = scheduler_output.num_scheduled_tokens[req_id] if ( not use_max_model_len and self.most_model_len is not None and num_tokens > self.most_model_len ): use_max_model_len = True num_scheduled_tokens_per_req.append(num_tokens) if use_max_model_len: if len(num_scheduled_tokens_per_req) > self.num_reqs_max_model_len: num_scheduled_tokens_per_req = num_scheduled_tokens_per_req[ : self.num_reqs_max_model_len ] end_index = start_index + self.num_reqs_max_model_len else: end_index = num_reqs else: assert self.num_reqs_most_model_len is not None if len(num_scheduled_tokens_per_req) > self.num_reqs_most_model_len: num_scheduled_tokens_per_req = num_scheduled_tokens_per_req[ : self.num_reqs_most_model_len ] end_index = start_index + self.num_reqs_most_model_len else: end_index = num_reqs max_num_scheduled_tokens_all_reqs = max(num_scheduled_tokens_per_req) num_scheduled_tokens_per_req = np.array( num_scheduled_tokens_per_req, dtype=np.int32 ) total_num_scheduled_tokens = sum(num_scheduled_tokens_per_req) assert max_num_scheduled_tokens_all_reqs > 0 num_reqs = len(num_scheduled_tokens_per_req) # Get request indices. # E.g., [2, 5, 3] -> [0, 0, 1, 1, 1, 1, 1, 2, 2, 2] # For each scheduled token, what are the corresponding req index. req_indices = np.repeat(self.arange_np[:num_reqs], num_scheduled_tokens_per_req) # Get batched arange.
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/ubatch_utils.py
vllm/v1/worker/ubatch_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import TypeAlias import numpy as np from vllm.config import ParallelConfig @dataclass class UBatchSlice: request_slice: slice token_slice: slice def is_empty(self) -> bool: return ( self.request_slice.start == self.request_slice.stop or self.token_slice.start == self.token_slice.stop ) @property def num_tokens(self) -> int: return self.token_slice.stop - self.token_slice.start UBatchSlices: TypeAlias = list[UBatchSlice] def is_last_ubatch_empty( orig_num_tokens: int, padded_num_tokens: int, num_ubatches: int ) -> bool: return (padded_num_tokens // num_ubatches) * (num_ubatches - 1) >= orig_num_tokens def check_ubatch_thresholds( config: ParallelConfig, num_tokens: int, uniform_decode: bool ) -> bool: if not config.use_ubatching: return False if uniform_decode: return num_tokens >= config.dbo_decode_token_threshold else: return num_tokens >= config.dbo_prefill_token_threshold # This pads the last ubatch slice out to the total number of tokens # (num_tokens + padding) since we do `create_ubatch_slices` before applying DP padding. def _pad_out_ubatch_slices( ubatch_slices: UBatchSlices, num_total_tokens: int, num_reqs_padded: int ) -> UBatchSlices: last_slice = ubatch_slices[-1] padded_last_request_slice = slice(last_slice.request_slice.start, num_reqs_padded) padded_last_token_slice = slice(last_slice.token_slice.start, num_total_tokens) return ubatch_slices[:-1] + [ UBatchSlice(padded_last_request_slice, padded_last_token_slice) ] def maybe_create_ubatch_slices( should_ubatch: bool, num_scheduled_tokens: np.ndarray, num_tokens_padded: int, num_reqs_padded: int, num_ubatches: int, split_point: list[int] | int | None = None, ) -> tuple[UBatchSlices | None, UBatchSlices | None]: if not should_ubatch: return None, None if split_point is None: split_point = int(num_tokens_padded) // num_ubatches token_split_points = [split_point * i for i in range(1, num_ubatches)] # TODO(lucas): Refactor the gpu_model_runner.py so we can pass # in cu_num_tokens directly (i.e. query_start_loc) cu_num_tokens = np.zeros(len(num_scheduled_tokens) + 1, dtype=np.int32) np.cumsum(num_scheduled_tokens, dtype=np.int32, out=cu_num_tokens[1:]) ubatch_slices = [] start_token = 0 # Add the end point to the split points to make iteration easier all_points = token_split_points + [cu_num_tokens[-1]] for end_token in all_points: token_slice = slice(start_token, end_token) # Determine request slices using exclusive stop semantics # Ubatch includes requests whose tokens overlap [start_token, end_token) # Start at the request that contains the start_token # or the request starting exactly at start_token (if on boundary) req_start = int(np.searchsorted(cu_num_tokens, start_token, side="right") - 1) # Stop at the request that starts at or after end_token req_stop = int(np.searchsorted(cu_num_tokens, end_token, side="left")) req_slice = slice(req_start, req_stop) ubatch_slices.append(UBatchSlice(req_slice, token_slice)) start_token = end_token ubatch_slices_padded = _pad_out_ubatch_slices( ubatch_slices, num_tokens_padded, num_reqs_padded ) assert sum(s.num_tokens for s in ubatch_slices_padded) == num_tokens_padded return ubatch_slices, ubatch_slices_padded
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu_input_batch.py
vllm/v1/worker/gpu_input_batch.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Datastructures defining a GPU input batch from dataclasses import dataclass from typing import cast import numpy as np import torch from vllm.lora.request import LoRARequest from vllm.multimodal.inputs import MultiModalFeatureSpec from vllm.pooling_params import PoolingParams from vllm.sampling_params import SamplingParams, SamplingType from vllm.utils import length_from_prompt_token_ids_or_embeds from vllm.utils.collection_utils import swap_dict_values from vllm.v1.outputs import LogprobsTensors from vllm.v1.pool.metadata import PoolingMetadata, PoolingStates from vllm.v1.sample.logits_processor import ( BatchUpdateBuilder, LogitsProcessors, MoveDirectionality, ) from vllm.v1.sample.metadata import SamplingMetadata from vllm.v1.spec_decode.utils import is_spec_decode_unsupported from vllm.v1.utils import copy_slice from vllm.v1.worker.block_table import MultiGroupBlockTable @dataclass class CachedRequestState: req_id: str prompt_token_ids: list[int] | None mm_features: list[MultiModalFeatureSpec] sampling_params: SamplingParams | None generator: torch.Generator | None block_ids: tuple[list[int], ...] num_computed_tokens: int output_token_ids: list[int] mrope_positions: torch.Tensor | None = None mrope_position_delta: int | None = None xdrope_positions: torch.Tensor | None = None lora_request: LoRARequest | None = None prompt_embeds: torch.Tensor | None = None # Used when both async_scheduling and spec_decode are enabled. prev_num_draft_len: int = 0 # for pooling models pooling_params: PoolingParams | None = None pooling_states: PoolingStates | None = None def __post_init__(self): self.num_prompt_tokens = length_from_prompt_token_ids_or_embeds( self.prompt_token_ids, self.prompt_embeds ) if self.pooling_params is not None: self.pooling_states = PoolingStates() @property def num_tokens(self) -> int: return self.num_prompt_tokens + len(self.output_token_ids) def get_token_id(self, idx: int) -> int: if idx < self.num_prompt_tokens: if self.prompt_token_ids is None: raise ValueError( f"Tried to access token index {idx}, but that token was " "provided via prompt_embeds, and its ID is unknown." ) return self.prompt_token_ids[idx] if idx - self.num_prompt_tokens < len(self.output_token_ids): return self.output_token_ids[idx - self.num_prompt_tokens] return -1 class InputBatch: def __init__( self, max_num_reqs: int, max_model_len: int, max_num_batched_tokens: int, device: torch.device, pin_memory: bool, vocab_size: int, block_sizes: list[int], # The block_size of each kv cache group kernel_block_sizes: list[int], logitsprocs: LogitsProcessors | None = None, logitsprocs_need_output_token_ids: bool = False, is_spec_decode: bool = False, is_pooling_model: bool = False, num_speculative_tokens: int = 0, cp_kv_cache_interleave_size: int = 1, ): self.is_pooling_model = is_pooling_model self.is_spec_decode = is_spec_decode self.max_num_reqs = max_num_reqs self.max_model_len = max_model_len self.max_num_batched_tokens = max_num_batched_tokens self.device = device self.pin_memory = pin_memory self.vocab_size = vocab_size self._req_ids: list[str | None] = [] self.req_id_to_index: dict[str, int] = {} # TODO(woosuk): This buffer could be too large if max_model_len is big. # Find a way to reduce the CPU memory usage. # This buffer is not directly transferred to the GPU, so it does not # need to be pinned. self.token_ids_cpu_tensor = torch.zeros( (max_num_reqs, max_model_len), device="cpu", dtype=torch.int32, pin_memory=False, ) self.token_ids_cpu = self.token_ids_cpu_tensor.numpy() self.is_token_ids_tensor = torch.zeros( (max_num_reqs, max_model_len), device="cpu", dtype=bool, pin_memory=False ) self.is_token_ids = self.is_token_ids_tensor.numpy() # Store prompt embeddings per request to avoid OOM from large upfront # allocation if max_model_len is big. # Maps req_index -> tensor of shape (num_prompt_tokens, hidden_size) self.req_prompt_embeds: dict[int, torch.Tensor] = {} self.num_tokens_no_spec = np.zeros(max_num_reqs, dtype=np.int32) self.num_prompt_tokens = np.zeros(max_num_reqs, dtype=np.int32) self.num_computed_tokens_cpu_tensor = torch.zeros( (max_num_reqs,), device="cpu", dtype=torch.int32, pin_memory=pin_memory, ) self.num_computed_tokens_cpu = self.num_computed_tokens_cpu_tensor.numpy() # Block table. self.block_table = MultiGroupBlockTable( max_num_reqs=max_num_reqs, max_model_len=max_model_len, max_num_batched_tokens=max_num_batched_tokens, pin_memory=pin_memory, device=device, block_sizes=block_sizes, kernel_block_sizes=kernel_block_sizes, num_speculative_tokens=num_speculative_tokens, cp_kv_cache_interleave_size=cp_kv_cache_interleave_size, ) # Sampling-related. self.temperature = torch.empty( (max_num_reqs,), dtype=torch.float32, device=device ) self.temperature_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float32, device="cpu", pin_memory=pin_memory ) self.temperature_cpu = self.temperature_cpu_tensor.numpy() self.greedy_reqs: set[str] = set() self.random_reqs: set[str] = set() self.top_p = torch.empty((max_num_reqs,), dtype=torch.float32, device=device) self.top_p_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float32, device="cpu", pin_memory=pin_memory ) self.top_p_cpu = self.top_p_cpu_tensor.numpy() self.top_p_reqs: set[str] = set() self.top_k = torch.empty((max_num_reqs,), dtype=torch.int32, device=device) self.top_k_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.int32, device="cpu", pin_memory=pin_memory ) self.top_k_cpu = self.top_k_cpu_tensor.numpy() self.top_k_reqs: set[str] = set() # IDs of requests which do not support spec decoding self.spec_decode_unsupported_reqs: set[str] = set() # Frequency penalty related data structures self.frequency_penalties = torch.empty( (max_num_reqs,), dtype=torch.float, device=device ) self.frequency_penalties_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float, device="cpu", pin_memory=pin_memory ) self.frequency_penalties_cpu = self.frequency_penalties_cpu_tensor.numpy() self.frequency_penalties_reqs: set[str] = set() # Presence penalty related data structures self.presence_penalties = torch.empty( (max_num_reqs,), dtype=torch.float, device=device ) self.presence_penalties_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float, device="cpu", pin_memory=pin_memory ) self.presence_penalties_cpu = self.presence_penalties_cpu_tensor.numpy() self.presence_penalties_reqs: set[str] = set() # Repetition penalty related data structures self.repetition_penalties = torch.empty( (max_num_reqs,), dtype=torch.float, device=device ) self.repetition_penalties_cpu_tensor = torch.empty( (max_num_reqs,), dtype=torch.float, device="cpu", pin_memory=pin_memory ) self.repetition_penalties_cpu = self.repetition_penalties_cpu_tensor.numpy() self.repetition_penalties_reqs: set[str] = set() # Speculative decoding self.num_accepted_tokens_cpu_tensor = torch.ones( (max_num_reqs,), dtype=torch.int64, device="cpu", pin_memory=pin_memory ) self.num_accepted_tokens_cpu = self.num_accepted_tokens_cpu_tensor.numpy() # lora related self.request_lora_mapping = np.zeros((self.max_num_reqs,), dtype=np.int64) self.lora_id_to_request_ids: dict[int, set[str]] = {} self.lora_id_to_lora_request: dict[int, LoRARequest] = {} # req_index -> generator # NOTE(woosuk): The indices of the requests that do not have their own # generator should not be included in the dictionary. self.generators: dict[int, torch.Generator] = {} self.num_logprobs: dict[str, int] = {} # To accumulate prompt logprobs tensor chunks across prefill steps. self.in_progress_prompt_logprobs_cpu: dict[str, LogprobsTensors] = {} # Internal representation of per-step batch state changes, used for # reordering persistent batch and generating logitsprocs batch state # updates. Should reset each step. self.batch_update_builder = BatchUpdateBuilder() # TODO convert this to LogitsProcessor self.has_allowed_token_ids: set[str] = set() # NOTE(lufang): In the mask tensor, if the corresponding token allowed, # the value is False. Since we use masked_fill_ to set -inf. self.allowed_token_ids_mask: torch.Tensor | None = None self.allowed_token_ids_mask_cpu_tensor: torch.Tensor | None = None # req_index -> bad_words_token_ids self.bad_words_token_ids: dict[int, list[list[int]]] = {} self.logits_processing_needs_token_ids = np.zeros(max_num_reqs, dtype=bool) self.req_output_token_ids: list[list[int] | None] = [] # Store provided logitsprocs. If none are provided, initialize empty # data structure self.logitsprocs = logitsprocs or LogitsProcessors() self.logitsprocs_need_output_token_ids = logitsprocs_need_output_token_ids # Store last speculative tokens for sampler. self.spec_token_ids: list[list[int]] = [[] for _ in range(max_num_reqs)] # This is updated each time the batch constituents change. self.sampling_metadata = self._make_sampling_metadata() # for pooling models self.pooling_params: dict[str, PoolingParams] = {} self.pooling_states: dict[str, PoolingStates] = {} # Cached reference to the GPU tensor of previously sampled tokens self.prev_sampled_token_ids: torch.Tensor | None = None self.prev_req_id_to_index: dict[str, int] | None = None # These are used to update output_token_ids with real sampled # ids from prior step, if required by current sampling params # (e.g. penalties). self.sampled_token_ids_cpu: torch.Tensor | None = None self.async_copy_ready_event: torch.Event | None = None @property def req_ids(self) -> list[str]: # None elements should only be present transiently # while performing state updates to the batch. return cast(list[str], self._req_ids) def _register_add_request(self, request: "CachedRequestState") -> int: """Track add-request operations for logits processors. Not applicable to pooling models. """ # Fill the next empty index if there is one. if (new_req_index := self.batch_update_builder.pop_removed()) is None: # Append to end otherwise. new_req_index = self.num_reqs assert new_req_index < self.max_num_reqs self.batch_update_builder.batch_changed = True if request.sampling_params: # Detailed added request metadata is only required for non-pooling # models, to support logitsprocs. self.batch_update_builder.added.append( ( new_req_index, request.sampling_params, request.prompt_token_ids, request.output_token_ids, ) ) return new_req_index def add_request( self, request: "CachedRequestState", ) -> int: req_index = self._register_add_request(request) req_id = request.req_id if req_index == len(self._req_ids): self._req_ids.append(req_id) self.req_output_token_ids.append(request.output_token_ids) self.spec_token_ids.append([]) else: self._req_ids[req_index] = req_id self.req_output_token_ids[req_index] = request.output_token_ids self.spec_token_ids[req_index].clear() self.req_id_to_index[req_id] = req_index # Copy the prompt token ids and output token ids. num_prompt_tokens = length_from_prompt_token_ids_or_embeds( request.prompt_token_ids, request.prompt_embeds ) self.num_prompt_tokens[req_index] = num_prompt_tokens start_idx = num_prompt_tokens end_idx = start_idx + len(request.output_token_ids) if request.prompt_token_ids is not None: self.token_ids_cpu[req_index, :num_prompt_tokens] = request.prompt_token_ids self.is_token_ids[req_index, :num_prompt_tokens] = True else: self.is_token_ids[req_index, :num_prompt_tokens] = False if request.prompt_embeds is not None: self.req_prompt_embeds[req_index] = request.prompt_embeds self.token_ids_cpu[req_index, start_idx:end_idx] = request.output_token_ids self.is_token_ids[req_index, start_idx:end_idx] = True # Number of tokens without spec decode tokens. self.num_tokens_no_spec[req_index] = request.num_tokens self.num_computed_tokens_cpu[req_index] = request.num_computed_tokens self.block_table.add_row(request.block_ids, req_index) if sampling_params := request.sampling_params: if self.is_spec_decode and is_spec_decode_unsupported(sampling_params): self.spec_decode_unsupported_reqs.add(req_id) if sampling_params.sampling_type == SamplingType.GREEDY: # Should avoid division by zero later when apply_temperature. self.temperature_cpu[req_index] = 0.0 self.greedy_reqs.add(req_id) else: self.temperature_cpu[req_index] = sampling_params.temperature self.random_reqs.add(req_id) self.top_p_cpu[req_index] = sampling_params.top_p if sampling_params.top_p < 1: self.top_p_reqs.add(req_id) top_k = sampling_params.top_k if 0 < top_k < self.vocab_size: self.top_k_reqs.add(req_id) else: top_k = self.vocab_size self.top_k_cpu[req_index] = top_k self.frequency_penalties_cpu[req_index] = sampling_params.frequency_penalty if sampling_params.frequency_penalty != 0.0: self.frequency_penalties_reqs.add(req_id) self.presence_penalties_cpu[req_index] = sampling_params.presence_penalty if sampling_params.presence_penalty != 0.0: self.presence_penalties_reqs.add(req_id) self.repetition_penalties_cpu[req_index] = ( sampling_params.repetition_penalty ) if sampling_params.repetition_penalty != 1.0: self.repetition_penalties_reqs.add(req_id) # NOTE(woosuk): self.generators should not include the requests that # do not have their own generator. if request.generator is not None: self.generators[req_index] = request.generator if sampling_params.logprobs is not None: self.num_logprobs[req_id] = ( self.vocab_size if sampling_params.logprobs == -1 else sampling_params.logprobs ) if sampling_params.allowed_token_ids: self.has_allowed_token_ids.add(req_id) if self.allowed_token_ids_mask_cpu_tensor is None: # Lazy allocation for this tensor, which can be large. # False means we don't fill with -inf. self.allowed_token_ids_mask = torch.zeros( self.max_num_reqs, self.vocab_size, dtype=torch.bool, device=self.device, ) self.allowed_token_ids_mask_cpu_tensor = torch.zeros( self.max_num_reqs, self.vocab_size, dtype=torch.bool, device="cpu", ) self.allowed_token_ids_mask_cpu_tensor[req_index] = True # False means we don't fill with -inf. self.allowed_token_ids_mask_cpu_tensor[req_index][ sampling_params.allowed_token_ids ] = False if sampling_params.bad_words_token_ids: self.bad_words_token_ids[req_index] = ( sampling_params.bad_words_token_ids ) elif pooling_params := request.pooling_params: pooling_states = request.pooling_states assert pooling_states is not None self.pooling_params[req_id] = pooling_params self.pooling_states[req_id] = pooling_states self.logits_processing_needs_token_ids[req_index] = ( pooling_params.requires_token_ids ) else: raise NotImplementedError("Unrecognized request type") # Speculative decoding: by default 1 token is generated. self.num_accepted_tokens_cpu[req_index] = 1 # Add request lora ID if request.lora_request: lora_id = request.lora_request.lora_int_id if lora_id not in self.lora_id_to_request_ids: self.lora_id_to_request_ids[lora_id] = set() self.request_lora_mapping[req_index] = lora_id self.lora_id_to_request_ids[lora_id].add(request.req_id) self.lora_id_to_lora_request[lora_id] = request.lora_request else: # No LoRA self.request_lora_mapping[req_index] = 0 return req_index def remove_request(self, req_id: str) -> int | None: """This method must always be followed by a call to condense(). Args: req_id: request to remove Returns: Removed request index, or `None` if `req_id` not recognized """ req_index = self.req_id_to_index.pop(req_id, None) if req_index is None: return None self.batch_update_builder.removed_append(req_index) self._req_ids[req_index] = None self.req_output_token_ids[req_index] = None self.spec_token_ids[req_index].clear() # LoRA lora_id = self.request_lora_mapping[req_index] if lora_id != 0: lora_req_ids = self.lora_id_to_request_ids[lora_id] lora_req_ids.discard(req_id) if not lora_req_ids: del self.lora_id_to_request_ids[lora_id] del self.lora_id_to_lora_request[lora_id] self.request_lora_mapping[req_index] = 0 if self.is_pooling_model: self.pooling_params.pop(req_id, None) self.pooling_states.pop(req_id, None) return req_index self.greedy_reqs.discard(req_id) self.random_reqs.discard(req_id) self.top_p_reqs.discard(req_id) self.top_k_reqs.discard(req_id) self.spec_decode_unsupported_reqs.discard(req_id) self.frequency_penalties_reqs.discard(req_id) self.presence_penalties_reqs.discard(req_id) self.repetition_penalties_reqs.discard(req_id) self.generators.pop(req_index, None) self.num_logprobs.pop(req_id, None) self.in_progress_prompt_logprobs_cpu.pop(req_id, None) if self.prev_req_id_to_index is not None: self.prev_req_id_to_index.pop(req_id, None) self.has_allowed_token_ids.discard(req_id) if self.allowed_token_ids_mask_cpu_tensor is not None: # False means we don't fill with -inf. self.allowed_token_ids_mask_cpu_tensor[req_index].fill_(False) self.bad_words_token_ids.pop(req_index, None) return req_index def swap_states(self, i1: int, i2: int) -> None: old_id_i1 = self._req_ids[i1] old_id_i2 = self._req_ids[i2] self._req_ids[i1], self._req_ids[i2] = self._req_ids[i2], self._req_ids[i1] # noqa self.req_output_token_ids[i1], self.req_output_token_ids[i2] = ( self.req_output_token_ids[i2], self.req_output_token_ids[i1], ) self.spec_token_ids[i1], self.spec_token_ids[i2] = ( self.spec_token_ids[i2], self.spec_token_ids[i1], ) assert old_id_i1 is not None and old_id_i2 is not None self.req_id_to_index[old_id_i1], self.req_id_to_index[old_id_i2] = ( self.req_id_to_index[old_id_i2], self.req_id_to_index[old_id_i1], ) self.num_tokens_no_spec[i1], self.num_tokens_no_spec[i2] = ( self.num_tokens_no_spec[i2], self.num_tokens_no_spec[i1], ) self.num_prompt_tokens[i1], self.num_prompt_tokens[i2] = ( self.num_prompt_tokens[i2], self.num_prompt_tokens[i1], ) self.num_computed_tokens_cpu[i1], self.num_computed_tokens_cpu[i2] = ( self.num_computed_tokens_cpu[i2], self.num_computed_tokens_cpu[i1], ) # NOTE: the following is unsafe # self.token_ids_cpu[i1, ...], self.token_ids_cpu[i2, ...], =\ # self.token_ids_cpu[i2, ...], self.token_ids_cpu[i1, ...] # instead, we need to temporarily copy the data for one of the indices # TODO(lucas): optimize this by only copying valid indices tmp = self.token_ids_cpu[i1, ...].copy() self.token_ids_cpu[i1, ...] = self.token_ids_cpu[i2, ...] self.token_ids_cpu[i2, ...] = tmp self.is_token_ids[[i1, i2], ...] = self.is_token_ids[[i2, i1], ...] # Swap prompt embeddings if they exist embeds_i1 = self.req_prompt_embeds.get(i1) embeds_i2 = self.req_prompt_embeds.get(i2) if embeds_i1 is not None: self.req_prompt_embeds[i2] = embeds_i1 else: self.req_prompt_embeds.pop(i2, None) if embeds_i2 is not None: self.req_prompt_embeds[i1] = embeds_i2 else: self.req_prompt_embeds.pop(i1, None) self.block_table.swap_row(i1, i2) self.request_lora_mapping[i1], self.request_lora_mapping[i2] = ( self.request_lora_mapping[i2], self.request_lora_mapping[i1], ) if self.is_pooling_model: # Sampling and logits parameters don't apply to pooling models. return # For autoregressive models, track detailed request reordering info # to support logitsprocs. self.batch_update_builder.moved.append((i1, i2, MoveDirectionality.SWAP)) self.temperature_cpu[i1], self.temperature_cpu[i2] = ( self.temperature_cpu[i2], self.temperature_cpu[i1], ) self.top_p_cpu[i1], self.top_p_cpu[i2] = self.top_p_cpu[i2], self.top_p_cpu[i1] self.top_k_cpu[i1], self.top_k_cpu[i2] = self.top_k_cpu[i2], self.top_k_cpu[i1] self.frequency_penalties_cpu[i1], self.frequency_penalties_cpu[i2] = ( self.frequency_penalties_cpu[i2], self.frequency_penalties_cpu[i1], ) self.presence_penalties_cpu[i1], self.presence_penalties_cpu[i2] = ( self.presence_penalties_cpu[i2], self.presence_penalties_cpu[i1], ) self.repetition_penalties_cpu[i1], self.repetition_penalties_cpu[i2] = ( self.repetition_penalties_cpu[i2], self.repetition_penalties_cpu[i1], ) self.num_accepted_tokens_cpu[i1], self.num_accepted_tokens_cpu[i2] = ( self.num_accepted_tokens_cpu[i2], self.num_accepted_tokens_cpu[i1], ) swap_dict_values(self.generators, i1, i2) swap_dict_values(self.bad_words_token_ids, i1, i2) if self.allowed_token_ids_mask_cpu_tensor is not None: ( self.allowed_token_ids_mask_cpu_tensor[i1], self.allowed_token_ids_mask_cpu_tensor[i2], ) = ( self.allowed_token_ids_mask_cpu_tensor[i2], self.allowed_token_ids_mask_cpu_tensor[i1], ) def condense(self) -> None: """Slide non-empty requests down into lower, empty indices. Any consecutive empty indices at the very end of the list are not filled. Returns: swaps: list of (from,to) swap tuples for moved requests empty_req_indices: indices not filled by condensation """ num_reqs = self.num_reqs if not (empty_req_indices := self.batch_update_builder.removed): # All removed requests were replaced by added requests, or else no # requests were removed at all. No condense() needed return if num_reqs == 0: # The batched states are empty. self._req_ids.clear() self.req_output_token_ids.clear() self.spec_token_ids.clear() return # NOTE(woosuk): This function assumes that the empty_req_indices # is sorted in descending order. last_req_index = num_reqs + len(empty_req_indices) - 1 while empty_req_indices: # Find the largest non-empty index. while last_req_index in empty_req_indices: last_req_index -= 1 # Find the smallest empty index. empty_index = self.batch_update_builder.peek_removed() assert empty_index is not None if empty_index >= last_req_index: break # Move active request down into empty request # index. self.batch_update_builder.pop_removed() req_id = self._req_ids[last_req_index] output_token_ids = self.req_output_token_ids[last_req_index] assert req_id is not None self._req_ids[empty_index] = req_id self._req_ids[last_req_index] = None self.req_output_token_ids[empty_index] = output_token_ids self.req_output_token_ids[last_req_index] = None self.req_id_to_index[req_id] = empty_index num_tokens = self.num_tokens_no_spec[last_req_index] + len( self.spec_token_ids[last_req_index] ) (self.spec_token_ids[last_req_index], self.spec_token_ids[empty_index]) = ( self.spec_token_ids[empty_index], self.spec_token_ids[last_req_index], ) self.spec_token_ids[last_req_index].clear() self.token_ids_cpu[empty_index, :num_tokens] = self.token_ids_cpu[ last_req_index, :num_tokens ] self.is_token_ids[empty_index, :num_tokens] = self.is_token_ids[ last_req_index, :num_tokens ] if last_req_index in self.req_prompt_embeds: self.req_prompt_embeds[empty_index] = self.req_prompt_embeds.pop( last_req_index ) self.num_tokens_no_spec[empty_index] = self.num_tokens_no_spec[ last_req_index ] self.num_prompt_tokens[empty_index] = self.num_prompt_tokens[last_req_index] self.num_computed_tokens_cpu[empty_index] = self.num_computed_tokens_cpu[ last_req_index ] self.block_table.move_row(last_req_index, empty_index) self.request_lora_mapping[empty_index] = self.request_lora_mapping[ last_req_index ] if self.is_pooling_model: last_req_index -= 1 # Sampling state not used by pooling models. continue # Autoregressive models require detailed tracking of condense # operations to support logitsprocs self.batch_update_builder.moved.append( (last_req_index, empty_index, MoveDirectionality.UNIDIRECTIONAL) ) self.temperature_cpu[empty_index] = self.temperature_cpu[last_req_index] self.top_p_cpu[empty_index] = self.top_p_cpu[last_req_index] self.top_k_cpu[empty_index] = self.top_k_cpu[last_req_index] self.frequency_penalties_cpu[empty_index] = self.frequency_penalties_cpu[ last_req_index ] self.presence_penalties_cpu[empty_index] = self.presence_penalties_cpu[ last_req_index ] self.repetition_penalties_cpu[empty_index] = self.repetition_penalties_cpu[ last_req_index ] self.num_accepted_tokens_cpu[empty_index] = self.num_accepted_tokens_cpu[ last_req_index ] generator = self.generators.pop(last_req_index, None) if generator is not None: self.generators[empty_index] = generator # TODO convert these to LogitsProcessors if self.allowed_token_ids_mask_cpu_tensor is not None: self.allowed_token_ids_mask_cpu_tensor[empty_index] = ( self.allowed_token_ids_mask_cpu_tensor[last_req_index] ) bad_words_token_ids = self.bad_words_token_ids.pop(last_req_index, None) if bad_words_token_ids is not None: self.bad_words_token_ids[empty_index] = bad_words_token_ids # Decrement last_req_index since it is now empty. last_req_index -= 1 # Trim lists to the batch size. del self._req_ids[num_reqs:] del self.req_output_token_ids[num_reqs:] del self.spec_token_ids[num_reqs:] def refresh_metadata(self): """Apply any batch updates to sampling metadata.""" if self.is_pooling_model: batch_changed = self.batch_update_builder.reset() if batch_changed: self.sampling_metadata = self._make_sampling_metadata() return # For non-pooling models - generate and apply logitsprocs update; # reset batch update tracking. # Update sampling metadata if batch state is changed. batch_update = self.batch_update_builder.get_and_reset(self.num_reqs) for logit_proc in self.logitsprocs.all: logit_proc.update_state(batch_update) if batch_update: self.sampling_metadata = self._make_sampling_metadata() def _make_sampling_metadata(self) -> SamplingMetadata: num_reqs = self.num_reqs if not self.all_greedy: temperature = copy_slice( self.temperature_cpu_tensor, self.temperature, num_reqs ) else: temperature = None if not self.no_top_p: copy_slice(self.top_p_cpu_tensor, self.top_p, num_reqs) if not self.no_top_k: copy_slice(self.top_k_cpu_tensor, self.top_k, num_reqs) if not self.no_penalties: # Since syncing these tensors is expensive only copy them # if necessary i.e. if there are requests which require # penalties to be applied during sampling. copy_slice( self.frequency_penalties_cpu_tensor, self.frequency_penalties, num_reqs ) copy_slice( self.presence_penalties_cpu_tensor, self.presence_penalties, num_reqs ) copy_slice( self.repetition_penalties_cpu_tensor, self.repetition_penalties, num_reqs, ) needs_prompt_token_ids = ( not self.no_penalties or self.logits_processing_needs_token_ids[:num_reqs].any() )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/ubatching.py
vllm/v1/worker/ubatching.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import threading from typing import Optional import torch from vllm import forward_context from vllm.forward_context import ForwardContext from vllm.logger import init_logger from vllm.utils.torch_utils import current_stream logger = init_logger(__name__) _THREAD_ID_TO_CONTEXT: dict = {} # Here we hardcode the number of microbatches to 2 for default. _NUM_UBATCHES: int = 2 _CURRENT_CONTEXTS: list[Optional["UBatchContext"]] = [] class UBatchContext: """ Context manager for micro-batching synchronization using threading events. """ def __init__( self, id: int, comm_stream: torch.cuda.Stream, compute_stream: torch.cuda.Stream, forward_context: ForwardContext, ready_barrier: threading.Barrier, cpu_wait_event: threading.Event, cpu_signal_event: threading.Event, gpu_comm_done_event: torch.Event, gpu_compute_done_event: torch.Event, schedule: str = "default", ): self.id = id self.comm_stream = comm_stream self.compute_stream = compute_stream self.forward_context = forward_context self.ready_barrier = ready_barrier self.cpu_wait_event = cpu_wait_event self.cpu_signal_event = cpu_signal_event self.current_stream = compute_stream self.gpu_comm_done_event = gpu_comm_done_event self.gpu_compute_done_event = gpu_compute_done_event self.schedule = schedule self.recv_hook = None def __enter__(self): global _CURRENT_CONTEXTS, _THREAD_ID_TO_CONTEXT _THREAD_ID_TO_CONTEXT[threading.get_ident()] = self.id _CURRENT_CONTEXTS[self.id] = self # _NUM_UBATCHES is set in make_ubatch_contexts self.ready_barrier.wait() self.cpu_wait_event.wait() self.cpu_wait_event.clear() self._restore_context() # Assume we want to start on the compute stream self.update_stream(self.compute_stream) return self def __exit__(self, exc_type, exc_val, exc_tb): global _CURRENT_CONTEXTS, _THREAD_ID_TO_CONTEXT _CURRENT_CONTEXTS[self.id] = None del _THREAD_ID_TO_CONTEXT[threading.get_ident()] self.maybe_run_recv_hook() self.cpu_signal_event.set() self.cpu_wait_event.clear() return False def _restore_context(self): forward_context._forward_context = self.forward_context def update_stream(self, stream): self.current_stream = stream if current_stream() != self.current_stream: torch.cuda.set_stream(self.current_stream) def _signal_comm_done(self): self.gpu_comm_done_event.record(self.comm_stream) def _signal_compute_done(self): self.gpu_compute_done_event.record(self.compute_stream) def _wait_compute_done(self): self.comm_stream.wait_event(self.gpu_compute_done_event) def _wait_comm_done(self): self.compute_stream.wait_event(self.gpu_comm_done_event) def _cpu_yield(self): # It is critical for correctness that only one thread is running # at a time. These asserts just make sure that this is the only # thread running before waking the other one up and going to sleep assert forward_context._forward_context == self.forward_context assert current_stream() == self.current_stream assert not self.cpu_wait_event.is_set() self.cpu_signal_event.set() self.cpu_wait_event.wait() self.cpu_wait_event.clear() self._restore_context() def switch_to_comm(self): self.update_stream(self.comm_stream) def switch_to_compute(self): self.update_stream(self.compute_stream) def switch_to_comm_sync(self): self._signal_compute_done() self.update_stream(self.comm_stream) self._wait_compute_done() def switch_to_compute_sync(self): self._signal_comm_done() self.update_stream(self.compute_stream) self._wait_comm_done() def maybe_run_recv_hook(self): if self.recv_hook is not None: self.recv_hook() self.recv_hook = None def yield_(self): self.current_stream = current_stream() self._cpu_yield() self.update_stream(self.current_stream) def yield_and_switch_from_compute_to_comm(self): assert current_stream() == self.compute_stream self._signal_compute_done() self._cpu_yield() assert self.current_stream == self.compute_stream self.update_stream(self.comm_stream) self._wait_compute_done() def yield_and_switch_from_comm_to_compute(self): assert current_stream() == self.comm_stream self._signal_comm_done() self._cpu_yield() assert self.current_stream == self.comm_stream self.update_stream(self.compute_stream) self._wait_comm_done() def dbo_enabled() -> bool: return len(_THREAD_ID_TO_CONTEXT) > 0 def dbo_current_ubatch_id() -> int: if len(_THREAD_ID_TO_CONTEXT) == 0: return 0 return _THREAD_ID_TO_CONTEXT[threading.get_ident()] def _register_ubatch_function(func): def wrapper(*args, **kwargs): if len(_THREAD_ID_TO_CONTEXT) > 0: ctx_idx = _THREAD_ID_TO_CONTEXT[threading.get_ident()] ctx = _CURRENT_CONTEXTS[ctx_idx] func(ctx, *args, **kwargs) return wrapper dbo_maybe_run_recv_hook = _register_ubatch_function(UBatchContext.maybe_run_recv_hook) dbo_yield = _register_ubatch_function(UBatchContext.yield_) dbo_yield_and_switch_from_compute_to_comm = _register_ubatch_function( UBatchContext.yield_and_switch_from_compute_to_comm ) dbo_yield_and_switch_from_comm_to_compute = _register_ubatch_function( UBatchContext.yield_and_switch_from_comm_to_compute ) dbo_switch_to_comm = _register_ubatch_function(UBatchContext.switch_to_comm) dbo_switch_to_compute = _register_ubatch_function(UBatchContext.switch_to_compute) dbo_switch_to_comm_sync = _register_ubatch_function(UBatchContext.switch_to_comm_sync) dbo_switch_to_compute_sync = _register_ubatch_function( UBatchContext.switch_to_compute_sync ) def dbo_register_recv_hook(recv_hook): if len(_THREAD_ID_TO_CONTEXT) > 0: ctx_idx = _THREAD_ID_TO_CONTEXT[threading.get_ident()] next_ctx = _CURRENT_CONTEXTS[(ctx_idx + 1) % _NUM_UBATCHES] next_ctx.recv_hook = recv_hook def dbo_get_previous_event(func, *args, **kwargs): if len(_THREAD_ID_TO_CONTEXT) > 0: ctx_idx = _THREAD_ID_TO_CONTEXT[threading.get_ident()] ctx = _CURRENT_CONTEXTS[ctx_idx] # execute callable on the ubatch compute stream to record/wait events there with torch.cuda.stream(ctx.compute_stream): return func(*args, **kwargs) def make_ubatch_contexts( num_micro_batches: int, compute_stream: torch.cuda.Stream, comm_stream: torch.cuda.Stream, forward_contexts: list[ForwardContext], ready_barrier: threading.Barrier, schedule: str = "default", ) -> list[UBatchContext]: global _NUM_UBATCHES, _CURRENT_CONTEXTS assert num_micro_batches > 1, "num_micro_batches must be greater than 1" _NUM_UBATCHES = num_micro_batches # Ensure the global context list is large enough if len(_CURRENT_CONTEXTS) < num_micro_batches: _CURRENT_CONTEXTS.extend([None] * (num_micro_batches - len(_CURRENT_CONTEXTS))) """ Create a context manager for micro-batching synchronization. """ cpu_events = [threading.Event() for _ in range(num_micro_batches)] gpu_comm_done_events = [torch.Event() for _ in range(num_micro_batches)] gpu_compute_done_events = [torch.Event() for _ in range(num_micro_batches)] ctxs = [] for i in range(num_micro_batches): ctx = UBatchContext( id=i, compute_stream=compute_stream, comm_stream=comm_stream, forward_context=forward_contexts[i], ready_barrier=ready_barrier, cpu_wait_event=cpu_events[i], cpu_signal_event=cpu_events[(i + 1) % num_micro_batches], gpu_comm_done_event=gpu_comm_done_events[i], gpu_compute_done_event=gpu_compute_done_events[i], schedule=schedule, ) ctxs.append(ctx) return ctxs
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/utils.py
vllm/v1/worker/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections import defaultdict from dataclasses import dataclass, field import torch from typing_extensions import deprecated from vllm.attention.backends.abstract import AttentionBackend from vllm.attention.layer import Attention from vllm.config import CacheConfig, ModelConfig, SchedulerConfig, VllmConfig from vllm.logger import init_logger from vllm.model_executor.models.interfaces import MultiModalEmbeddings from vllm.model_executor.models.utils import extract_layer_index from vllm.multimodal.cache import processor_only_cache_from_config from vllm.multimodal.registry import MultiModalRegistry from vllm.platforms import current_platform from vllm.utils.mem_constants import GiB_bytes from vllm.utils.mem_utils import MemorySnapshot from vllm.v1.attention.backends.utils import AttentionMetadataBuilder from vllm.v1.core.encoder_cache_manager import compute_mm_encoder_budget from vllm.v1.kv_cache_interface import KVCacheGroupSpec, KVCacheSpec logger = init_logger(__name__) class MultiModalBudget: """Helper class to calculate budget information for multi-modal models.""" def __init__( self, model_config: ModelConfig, scheduler_config: SchedulerConfig, mm_registry: MultiModalRegistry, ) -> None: super().__init__() self.model_config = model_config self.scheduler_config = scheduler_config self.mm_registry = mm_registry self.cache = cache = processor_only_cache_from_config(model_config, mm_registry) self.max_model_len = model_config.max_model_len self.max_num_reqs = scheduler_config.max_num_seqs self.mm_limits = mm_registry.get_mm_limits_per_prompt(model_config, cache=cache) max_tokens_by_modality = mm_registry.get_max_tokens_per_item_by_modality( model_config, cache=cache, profiler_limits=self.mm_limits, ) encoder_compute_budget, encoder_cache_size = compute_mm_encoder_budget( scheduler_config, max_tokens_by_modality, ) self.encoder_compute_budget = encoder_compute_budget self.encoder_cache_size = encoder_cache_size max_items_per_prompt_by_modality = dict[str, int]() max_items_per_batch_by_modality = dict[str, int]() for modality, max_tokens in max_tokens_by_modality.items(): ( max_items_per_prompt, max_items_per_batch, ) = self.get_max_items(modality, max_tokens) max_items_per_prompt_by_modality[modality] = max_items_per_prompt max_items_per_batch_by_modality[modality] = max_items_per_batch self.max_tokens_by_modality = max_tokens_by_modality self.max_items_per_prompt_by_modality = max_items_per_prompt_by_modality self.max_items_per_batch_by_modality = max_items_per_batch_by_modality def get_modality_with_max_tokens(self) -> str: max_tokens_by_modality = self.max_tokens_by_modality modality, _ = max(max_tokens_by_modality.items(), key=lambda x: x[1]) return modality def get_encoder_budget(self) -> int: return min(self.encoder_compute_budget, self.encoder_cache_size) def get_max_items( self, modality: str, max_tokens_per_item: int, ) -> tuple[int, int]: if max_tokens_per_item == 0: return 0, 0 # Check how many items of this modality can be supported by # the encoder budget. encoder_budget = self.get_encoder_budget() # TODO: handle encoder-decoder models once we support them. if encoder_budget == 0: return 0, 0 max_encoder_items_per_batch = encoder_budget // max_tokens_per_item # Check how many items of this modality can be supported by # the decoder budget. mm_limit = self.mm_limits[modality] max_items_per_prompt = max( 1, min(mm_limit, self.max_model_len // max_tokens_per_item), ) scheduler_config = self.scheduler_config max_num_reqs = self.max_num_reqs if not scheduler_config.enable_chunked_prefill: max_num_reqs = min( max_num_reqs, scheduler_config.max_num_batched_tokens // max_tokens_per_item, ) max_decoder_items_per_batch = max_num_reqs * max_items_per_prompt max_items_per_batch = max( 1, min(max_encoder_items_per_batch, max_decoder_items_per_batch), ) return max_items_per_prompt, max_items_per_batch def reset_cache(self) -> None: if self.cache is not None: self.cache.clear_cache() @dataclass class AttentionGroup: backend: type[AttentionBackend] layer_names: list[str] kv_cache_spec: KVCacheSpec kv_cache_group_id: int # When ubatching is enabled we will have a metadata builder for each ubatch # so that if they use internal persistent buffers for cudagraphs, and they # won't have to worry about conflicting with the other ubatches. metadata_builders: list[AttentionMetadataBuilder] = field( default_factory=lambda: [] ) def create_metadata_builders( self, vllm_config, device, kernel_block_size: int | None, num_metadata_builders: int = 1, ): kv_cache_spec_builder = ( self.kv_cache_spec.copy_with_new_block_size(kernel_block_size) if kernel_block_size is not None else self.kv_cache_spec ) self.metadata_builders = [ self.backend.get_builder_cls()( kv_cache_spec_builder, self.layer_names, vllm_config, device, ) for _ in range(num_metadata_builders) ] def get_metadata_builder(self, ubatch_id: int = 0) -> AttentionMetadataBuilder: assert len(self.metadata_builders) > ubatch_id return self.metadata_builders[ubatch_id] def sanity_check_mm_encoder_outputs( mm_embeddings: MultiModalEmbeddings, expected_num_items: int, ) -> None: """ Perform sanity checks for the result of [`vllm.model_executor.models.SupportsMultiModal.embed_multimodal`][]. """ assert isinstance(mm_embeddings, (list, tuple, torch.Tensor)), ( "Expected multimodal embeddings to be a list/tuple of 2D tensors, " f"or a single 3D tensor, but got {type(mm_embeddings)} " "instead. This is most likely due to incorrect implementation " "of the model's `embed_multimodal` method." ) assert len(mm_embeddings) == expected_num_items, ( "Expected number of multimodal embeddings to match number of " f"input items: {expected_num_items}, but got {len(mm_embeddings)=} " "instead. This is most likely due to incorrect implementation " "of the model's `embed_multimodal` method." ) assert all(e.ndim == 2 for e in mm_embeddings), ( "Expected multimodal embeddings to be a sequence of 2D tensors, " f"but got tensors with shapes {[e.shape for e in mm_embeddings]} " "instead. This is most likely due to incorrect implementation " "of the model's `embed_multimodal` method." ) @deprecated("`scatter_mm_placeholders` is deprecated and will be removed in v0.15.0.") def scatter_mm_placeholders( embeds: torch.Tensor, is_embed: torch.Tensor | None, ) -> torch.Tensor: """ Scatter the multimodal embeddings into a contiguous tensor that represents the placeholder tokens. [`vllm.multimodal.processing.PromptUpdateDetails.is_embed`][]. Args: embeds: The multimodal embeddings. Shape: `(num_embeds, embed_dim)` is_embed: A boolean mask indicating which positions in the placeholder tokens need to be filled with multimodal embeddings. Shape: `(num_placeholders, num_embeds)` """ if is_embed is None: return embeds placeholders = embeds.new_full( (is_embed.shape[0], embeds.shape[-1]), fill_value=torch.nan, ) placeholders[is_embed] = embeds return placeholders @deprecated("`gather_mm_placeholders` is deprecated and will be removed in v0.15.0.") def gather_mm_placeholders( placeholders: torch.Tensor, is_embed: torch.Tensor | None, ) -> torch.Tensor: """ Reconstructs the embeddings from the placeholder tokens. This is the operation of [`scatter_mm_placeholders`] [vllm.v1.worker.utils.scatter_mm_placeholders]. """ if is_embed is None: return placeholders return placeholders[is_embed] def request_memory(init_snapshot: MemorySnapshot, cache_config: CacheConfig) -> float: """ Calculate the amount of memory required by vLLM, then validate that the current amount of free memory is sufficient for that. """ requested_memory = init_snapshot.total_memory * cache_config.gpu_memory_utilization if init_snapshot.free_memory < requested_memory: GiB = lambda b: round(b / GiB_bytes, 2) raise ValueError( f"Free memory on device {init_snapshot.device_} " f"({GiB(init_snapshot.free_memory)}/" f"{GiB(init_snapshot.total_memory)} GiB) on startup " f"is less than desired GPU memory utilization " f"({cache_config.gpu_memory_utilization}, " f"{GiB(requested_memory)} GiB). Decrease GPU memory " f"utilization or reduce GPU memory used by other processes." ) return requested_memory def add_kv_sharing_layers_to_kv_cache_groups( shared_kv_cache_layers: dict[str, str], kv_cache_groups: list[KVCacheGroupSpec], runner_only_attn_layers: set[str] | None = None, ) -> None: """ Sets up KV cache sharing by reusing the allocated KV caches in `kv_caches` for layers that do not allocate its own KV cache, based on the mapping in `shared_kv_cache_layers`. Adds these layers to the corresponding KV cache group, which is needed to ensure that attention metadata is assigned later. Args: shared_kv_cache_layers: Layer pairings for cross-layer KV sharing. If an Attention layer `layer_name` is in the keys of this dict, it means this layer will perform attention using the keys and values from the KV cache of `shared_kv_cache_layers[layer_name]`. kv_cache_groups: The KV cache groups of the model. """ layer_to_kv_cache_group: dict[str, KVCacheGroupSpec] = {} for kv_cache_group in kv_cache_groups: for layer_name in kv_cache_group.layer_names: layer_to_kv_cache_group[layer_name] = kv_cache_group for layer_name, target_layer_name in shared_kv_cache_layers.items(): tgt_kv_cache_group = layer_to_kv_cache_group[target_layer_name] tgt_kv_cache_group.layer_names.append(layer_name) if runner_only_attn_layers is not None: runner_only_attn_layers.add(layer_name) def bind_kv_cache( kv_caches: dict[str, torch.Tensor], forward_context: dict[str, Attention], runner_kv_caches: list[torch.Tensor], num_attn_module: int = 1, ) -> None: """ Bind the allocated KV cache to both ModelRunner and forward context so that the KV cache can be used in the forward pass. This function: 1) Fills the ModelRunner's kv cache list (`runner_kv_caches`) with kv_caches. 2) Associates each attention layer in the `forward_context` with its corresponding KV cache in kv_caches. Args: kv_caches: The allocated kv_caches with layer names as keys. forward_context: The global forward context containing all Attention layers with layer names as keys. runner_kv_caches: The kv_cache declared by ModelRunner. """ # Bind kv_caches to ModelRunner assert len(runner_kv_caches) == 0 # Convert kv_caches dict to a list of tensors in the order of layer_index. index2name = defaultdict(list) for layer_name in kv_caches: index2name[extract_layer_index(layer_name, num_attn_module)].append(layer_name) for layer_index in sorted(index2name.keys()): layer_names = index2name[layer_index] if len(layer_names) > 1: # One typical case is encoder-decoder model, e.g., bart. # The cross attention and self attention in the same decoder layer # has different layer_name but the same layer_index. # TODO - analyze where runner_kv_caches is used and the right # way to ensure it properly reflects multiple attention layers # in the same decoder block. if ( current_platform.is_cuda_alike() or current_platform.is_xpu() or current_platform.is_cpu() ): # We know that the GPU / CPU runner is not impacted by this # case. Some test code depends on runner_kv_caches, but # not in a way that's impacted by ignoring this. pass else: raise NotImplementedError layer_name = layer_names[0] runner_kv_caches.append(kv_caches[layer_name]) # Bind kv_caches to forward context for layer_name, kv_cache in kv_caches.items(): # NOTE: Use list because of v0 PP virtual engine. forward_context[layer_name].kv_cache = [kv_cache] def is_residual_scattered_for_sp( vllm_config: VllmConfig, num_input_tokens: int ) -> bool: """Check if the residual tensor is scattered for sequence parallelism. The residual tensor is scattered across tensor parallel ranks when sequence parallelism and tensor parallelism is enabled. This follows the same logic as SequenceParallelismPass.is_applicable_for_range(): - In full-graph compilation mode (no splitting ops or using inductor graph partition), SP is always applied - Otherwise, SP is only applied for specific shapes in compile_sizes """ if not vllm_config.compilation_config.pass_config.enable_sp: return False tp = vllm_config.parallel_config.tensor_parallel_size if tp == 1: return False # When sequence parallelism is enabled, we always pad num_input_tokens # to be a multiple of tensor_parallel_size (tp) earlier. assert num_input_tokens % tp == 0 if ( not vllm_config.compilation_config.splitting_ops or vllm_config.compilation_config.use_inductor_graph_partition ): return True compile_sizes = vllm_config.compilation_config.compile_sizes if compile_sizes is None: return False return num_input_tokens in compile_sizes
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/xpu_model_runner.py
vllm/v1/worker/xpu_model_runner.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from contextlib import contextmanager from typing import TYPE_CHECKING import torch from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.v1.worker.gpu_model_runner import GPUModelRunner if TYPE_CHECKING: pass logger = init_logger(__name__) class XPUModelRunner(GPUModelRunner): """A model runner for XPU devices.""" def __init__( self, vllm_config: VllmConfig, device: torch.device, ): with _torch_cuda_wrapper(): super().__init__(vllm_config, device) # FIXME: To be verified. self.cascade_attn_enabled = False def _init_device_properties(self) -> None: self.num_sms = None def _sync_device(self) -> None: torch.xpu.synchronize() @contextmanager def _torch_cuda_wrapper(): try: # replace cuda APIs with xpu APIs, this should work by default torch.cuda.Stream = torch.xpu.Stream torch.cuda.default_stream = torch.xpu.current_stream torch.cuda.current_stream = torch.xpu.current_stream torch.cuda.stream = torch.xpu.stream yield finally: pass
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/workspace.py
vllm/v1/worker/workspace.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import inspect import os from itertools import accumulate from math import prod from typing import Optional import torch import vllm.envs as envs from vllm.logger import init_logger from vllm.utils.math_utils import round_up from vllm.v1.worker.ubatching import dbo_current_ubatch_id logger = init_logger(__name__) def _compute_bytes(shape: tuple[int, ...], dtype: torch.dtype) -> int: return prod(shape) * dtype.itemsize # Constants _MB = 1024**2 _GiB = 1024**3 # Global workspace manager instance _manager: Optional["WorkspaceManager"] = None class WorkspaceManager: """Manager for workspace allocation. Manages workspace buffers for DBO (Dual Batch Overlap) execution. Can be locked to prevent further growth during execution. """ def __init__(self, device: torch.device, num_ubatches: int | None = None): self._device = device # Cache num ubatches at init based on configuration (default to 1) self._num_ubatches = num_ubatches if num_ubatches is not None else 1 self._current_workspaces: list[torch.Tensor | None] = [None, None] self._locked: bool = False @staticmethod def _workspace_size_bytes(workspace: torch.Tensor | None) -> int: """Get size of workspace in bytes.""" if workspace is None: return 0 return workspace.numel() * workspace.element_size() def lock(self) -> None: """Lock the workspace to prevent further growth. After locking, any attempt to allocate a larger workspace will raise an assertion error. This ensures workspace size is fixed during execution. """ self._locked = True if envs.VLLM_DEBUG_WORKSPACE: logger.info( "[WORKSPACE DEBUG] Workspace locked. Current sizes: %s", [ self._workspace_size_bytes(ws) / _MB for ws in self._current_workspaces if ws is not None ], ) def is_locked(self) -> bool: """Check if workspace is locked.""" return self._locked def get_simultaneous( self, *shapes_and_dtypes: tuple[tuple[int, ...], torch.dtype] ) -> list[torch.Tensor]: """Get multiple workspace tensors simultaneously from a single allocation. Args: *shapes_and_dtypes: One or more (shape, dtype) tuples. Returns: List of tensor views into the workspace buffer, one per shape/dtype pair. """ actual_bytes = [_compute_bytes(s, d) for s, d in shapes_and_dtypes] aligned_bytes = [round_up(actual, 256) for actual in actual_bytes] total_bytes = sum(aligned_bytes) # Calculate cumulative offsets using itertools.accumulate offsets = list(accumulate([0] + aligned_bytes[:-1])) current_workspace = self._ensure_workspace_size(total_bytes) return [ current_workspace[offsets[i] : offsets[i] + actual_bytes[i]] .view(shapes_and_dtypes[i][1]) .reshape(shapes_and_dtypes[i][0]) for i in range(len(shapes_and_dtypes)) ] def _ensure_workspace_size(self, required_bytes: int) -> torch.Tensor: """Ensure workspace is allocated and large enough, return current workspace. Args: required_bytes: The number of bytes required. Returns: The current workspace tensor. """ ubatch_id = dbo_current_ubatch_id() current_workspace = self._current_workspaces[ubatch_id] current_size = self._workspace_size_bytes(current_workspace) if current_size < required_bytes: def get_caller_info() -> str: """Find first frame outside WorkspaceManager.""" curr_frame = inspect.currentframe() if curr_frame is None: return "unknown" # Walk up the stack skipping WorkspaceManager frames curr_frame = curr_frame.f_back while curr_frame is not None: # TODO: This only catches instance methods (self), missing # classmethods and staticmethods. Once Python 3.11+ is the # minimum supported version, use co_qualname instead: # qualname = curr_frame.f_code.co_qualname # if qualname.startswith("WorkspaceManager."): if isinstance(curr_frame.f_locals.get("self"), WorkspaceManager): curr_frame = curr_frame.f_back continue filename = os.path.basename(curr_frame.f_code.co_filename) return ( f"{filename}:{curr_frame.f_lineno}:{curr_frame.f_code.co_name}" ) return "unknown" if self._locked: raise AssertionError( f"Workspace is locked but allocation from '{get_caller_info()}' " f"requires {required_bytes / _MB:.2f} MB, current size is " f"{current_size / _MB:.2f} MB. " "Workspace growth is not allowed after locking." ) for ubatch_id in range(self._num_ubatches): current_workspace = self._current_workspaces[ubatch_id] if ( current_workspace is None or self._workspace_size_bytes(current_workspace) < required_bytes ): # Delete old tensor before allocating new one to avoid # memory spike from resize_(). resize_() allocates new # memory before freeing old, which can cause OOM. # Must clear the list reference first since local var # is just a copy of the reference. self._current_workspaces[ubatch_id] = None del current_workspace self._current_workspaces[ubatch_id] = torch.empty( (required_bytes,), dtype=torch.uint8, device=self._device ) if envs.VLLM_DEBUG_WORKSPACE: logger.info( "[WORKSPACE DEBUG] Resized workspace from '%s': %.2f MB -> " "%.2f MB (%d ubatches, total memory %.2f MB)", get_caller_info(), current_size / _MB, required_bytes / _MB, self._num_ubatches, required_bytes * self._num_ubatches / _MB, ) current_workspace = self._current_workspaces[dbo_current_ubatch_id()] return current_workspace def is_workspace_manager_initialized() -> bool: """Check if workspace manager has been initialized. Returns: True if workspace manager is initialized, False otherwise. """ return _manager is not None def current_workspace_manager() -> "WorkspaceManager": """Get the current workspace manager instance. Raises: AssertionError: If workspace manager has not been initialized. """ assert _manager is not None, ( "WorkspaceManager not initialized. Call init_workspace_manager() " "with a device before using workspace functions." ) return _manager def init_workspace_manager( device: torch.device, num_ubatches: int | None = None ) -> None: """Initialize the workspace manager with a device. Must be called before using any workspace functions. Typically called from GPUModelRunner.__init__. Args: device: The device to allocate workspace on. num_ubatches: Number of micro-batches. Defaults to 1. """ global _manager if _manager is not None: logger.warning( "WorkspaceManager already initialized on device %s, " "reinitializing on device %s", _manager._device, device, ) _manager = WorkspaceManager(device, num_ubatches) def lock_workspace() -> None: """Lock the workspace to prevent further growth. After calling this function, any attempt to allocate a workspace larger than the current size will raise an AssertionError. This ensures that workspace size is fixed during execution and prevents unexpected memory allocations in the hot path. Example: # During initialization init_workspace_manager(device) reserve_workspace(shape1, dtype1) reserve_workspace(shape2, dtype2) # Lock after warmup/profiling lock_workspace() # Now all get_workspace calls must fit in pre-allocated size """ current_workspace_manager().lock() def reset_workspace_manager() -> None: """Reset the workspace manager to uninitialized state. This is primarily intended for testing purposes to allow tests to reinitialize the workspace manager cleanly. """ global _manager _manager = None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu_worker.py
vllm/v1/worker/gpu_worker.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """A GPU worker class.""" import gc import os from contextlib import AbstractContextManager, nullcontext from types import NoneType from typing import TYPE_CHECKING, Any, cast import numpy as np import torch import torch.distributed import torch.nn as nn import vllm.envs as envs from vllm.config import CUDAGraphMode, VllmConfig from vllm.config.compilation import CompilationMode from vllm.distributed import ( ensure_model_parallel_initialized, init_distributed_environment, set_custom_all_reduce, ) from vllm.distributed.ec_transfer import ensure_ec_transfer_initialized from vllm.distributed.kv_transfer import ( ensure_kv_transfer_initialized, get_kv_transfer_group, has_kv_transfer_group, ) from vllm.distributed.parallel_state import ( get_pcp_group, get_pp_group, get_tp_group, ) from vllm.logger import init_logger from vllm.lora.request import LoRARequest from vllm.model_executor import set_random_seed from vllm.model_executor.models.interfaces import is_mixture_of_experts from vllm.model_executor.warmup.kernel_warmup import kernel_warmup from vllm.platforms import current_platform from vllm.profiler.wrapper import CudaProfilerWrapper, TorchProfilerWrapper from vllm.sequence import IntermediateTensors from vllm.tasks import SupportedTask from vllm.utils.mem_constants import GiB_bytes from vllm.utils.mem_utils import MemorySnapshot, memory_profiling from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput from vllm.v1.engine import ReconfigureDistributedRequest, ReconfigureRankType from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheSpec from vllm.v1.outputs import ( AsyncModelRunnerOutput, DraftTokenIds, ModelRunnerOutput, ) from vllm.v1.utils import report_usage_stats from vllm.v1.worker.utils import is_residual_scattered_for_sp from vllm.v1.worker.worker_base import WorkerBase from vllm.v1.worker.workspace import init_workspace_manager from .utils import request_memory logger = init_logger(__name__) if TYPE_CHECKING: from vllm.model_executor.model_loader.tensorizer import TensorizerConfig from vllm.v1.worker.gpu_model_runner import GPUModelRunner class Worker(WorkerBase): def __init__( self, vllm_config: VllmConfig, local_rank: int, rank: int, distributed_init_method: str, is_driver_worker: bool = False, ): super().__init__( vllm_config=vllm_config, local_rank=local_rank, rank=rank, distributed_init_method=distributed_init_method, is_driver_worker=is_driver_worker, ) # configure float32 matmul precision according to vLLM env. precision = envs.VLLM_FLOAT32_MATMUL_PRECISION torch.backends.cuda.matmul.fp32_precision = precision if self.model_config.trust_remote_code: # note: lazy import to avoid importing torch before initializing from vllm.utils.import_utils import init_cached_hf_modules init_cached_hf_modules() # Buffers saved before sleep self._sleep_saved_buffers: dict[str, torch.Tensor] = {} # Torch/CUDA profiler. Enabled and configured through profiler_config. self.profiler: Any | None = None profiler_config = vllm_config.profiler_config if profiler_config.profiler == "torch": worker_name = f"{vllm_config.instance_id}-rank-{self.rank}" self.profiler = TorchProfilerWrapper( profiler_config, worker_name=worker_name, local_rank=self.local_rank, activities=["CPU", "CUDA"], ) elif profiler_config.profiler == "cuda": self.profiler = CudaProfilerWrapper(profiler_config) else: self.profiler = None self.use_v2_model_runner = envs.VLLM_USE_V2_MODEL_RUNNER def sleep(self, level: int = 1) -> None: from vllm.device_allocator.cumem import CuMemAllocator free_bytes_before_sleep = torch.cuda.mem_get_info()[0] # Save the buffers before level 2 sleep if level == 2: model = self.model_runner.model self._sleep_saved_buffers = { name: buffer.cpu().clone() for name, buffer in model.named_buffers() } allocator = CuMemAllocator.get_instance() allocator.sleep(offload_tags=("weights",) if level == 1 else tuple()) free_bytes_after_sleep, total = torch.cuda.mem_get_info() freed_bytes = free_bytes_after_sleep - free_bytes_before_sleep used_bytes = total - free_bytes_after_sleep assert freed_bytes >= 0, "Memory usage increased after sleeping." logger.info( "Sleep mode freed %.2f GiB memory, %.2f GiB memory is still in use.", freed_bytes / GiB_bytes, used_bytes / GiB_bytes, ) def wake_up(self, tags: list[str] | None = None) -> None: from vllm.device_allocator.cumem import CuMemAllocator allocator = CuMemAllocator.get_instance() allocator.wake_up(tags) # Restore the buffers after level 2 sleep if len(self._sleep_saved_buffers): model = self.model_runner.model for name, buffer in model.named_buffers(): if name in self._sleep_saved_buffers: buffer.data.copy_(self._sleep_saved_buffers[name].data) self._sleep_saved_buffers = {} # If the KV cache has just been woken up, # the internal state of cache_engine must be reset, # especially the FP8 scaling factor. if ( (tags is None or "kv_cache" in tags) and self.cache_config.cache_dtype.startswith("fp8") and hasattr(self.model_runner, "init_fp8_kv_scales") ): self.model_runner.init_fp8_kv_scales() def _maybe_get_memory_pool_context(self, tag: str) -> AbstractContextManager: if self.vllm_config.model_config.enable_sleep_mode: from vllm.device_allocator.cumem import CuMemAllocator allocator = CuMemAllocator.get_instance() if tag == "weights": assert allocator.get_current_usage() == 0, ( "Sleep mode can only be used for one instance per process." ) return allocator.use_memory_pool(tag=tag) else: return nullcontext() def initialize_cache(self, num_gpu_blocks: int, num_cpu_blocks: int) -> None: self.cache_config.num_gpu_blocks = num_gpu_blocks self.cache_config.num_cpu_blocks = num_cpu_blocks def init_device(self): if self.device_config.device_type == "cuda": # This env var set by Ray causes exceptions with graph building. os.environ.pop("NCCL_ASYNC_ERROR_HANDLING", None) parallel_config = self.parallel_config if ( parallel_config.distributed_executor_backend not in ("ray", "external_launcher") and parallel_config.data_parallel_backend != "ray" and parallel_config.nnodes_within_dp == 1 ): # Use local DP rank if available, otherwise use global DP rank. dp_local_rank = self.parallel_config.data_parallel_rank_local if dp_local_rank is None: dp_local_rank = self.parallel_config.data_parallel_index tp_pp_world_size = ( self.parallel_config.pipeline_parallel_size * self.parallel_config.tensor_parallel_size ) # DP_LOCAL_RANK * TP_PP_WORLD_SIZE + TP_LOCAL_RANK self.local_rank += dp_local_rank * tp_pp_world_size assert self.local_rank < torch.cuda.device_count(), ( f"DP adjusted local rank {self.local_rank} is out of bounds. " ) visible_device_count = ( torch.cuda.device_count() if torch.cuda.is_available() else 0 ) assert self.parallel_config.local_world_size <= visible_device_count, ( f"local_world_size ({self.parallel_config.local_world_size}) must " f"be less than or equal to the number of visible devices " f"({visible_device_count})." ) self.device = torch.device(f"cuda:{self.local_rank}") current_platform.set_device(self.device) current_platform.check_if_supports_dtype(self.model_config.dtype) # Initialize the distributed environment BEFORE taking # memory snapshot # This ensures NCCL buffers are allocated before we measure # available memory init_worker_distributed_environment( self.vllm_config, self.rank, self.distributed_init_method, self.local_rank, current_platform.dist_backend, ) # Set random seed. set_random_seed(self.model_config.seed) # Now take memory snapshot after NCCL is initialized gc.collect() torch.cuda.empty_cache() # take current memory snapshot self.init_snapshot = init_snapshot = MemorySnapshot(device=self.device) self.requested_memory = request_memory(init_snapshot, self.cache_config) else: raise RuntimeError(f"Not support device type: {self.device_config.device}") # Initialize workspace manager num_ubatches = 2 if self.vllm_config.parallel_config.enable_dbo else 1 init_workspace_manager(self.device, num_ubatches) # Construct the model runner if self.use_v2_model_runner: from vllm.v1.worker.gpu.model_runner import ( GPUModelRunner as GPUModelRunnerV2, ) # HACK(woosuk): This is a temporary fix to avoid type errors. self.model_runner: GPUModelRunner = GPUModelRunnerV2( # type: ignore self.vllm_config, self.device ) else: from vllm.v1.worker.gpu_model_runner import ( GPUModelRunner as GPUModelRunnerV1, ) self.model_runner = GPUModelRunnerV1(self.vllm_config, self.device) if self.rank == 0: # If usage stat is enabled, collect relevant info. report_usage_stats(self.vllm_config) # FIXME(youkaichao & ywang96): Use TorchDispatchMode instead of memory pool # to hijack tensor allocation. def load_model(self) -> None: eep_scale_up = os.environ.get("VLLM_ELASTIC_EP_SCALE_UP_LAUNCH") == "1" with self._maybe_get_memory_pool_context(tag="weights"): self.model_runner.load_model(eep_scale_up=eep_scale_up) def update_config(self, overrides: dict[str, Any]) -> None: self.model_runner.update_config(overrides) def reload_weights(self) -> None: self.model_runner.reload_weights() @torch.inference_mode() def determine_available_memory(self) -> int: """Profiles the peak memory usage of the model to determine how much memory can be used for KV cache without OOMs. The engine will first conduct a profiling of the existing memory usage. Then, it calculates the free memory that can be used for KV cache in bytes. Tip: You may limit the usage of GPU memory by adjusting the `gpu_memory_utilization` parameter. """ GiB = lambda b: b / GiB_bytes if kv_cache_memory_bytes := self.cache_config.kv_cache_memory_bytes: # still need a profile run which compiles the model for # max_num_batched_tokens self.model_runner.profile_run() msg = ( f"Initial free memory {GiB(self.init_snapshot.free_memory):.2f} " f"GiB, reserved {GiB(kv_cache_memory_bytes):.2f} GiB memory for " "KV Cache as specified by kv_cache_memory_bytes config and " "skipped memory profiling. This does not respect the " "gpu_memory_utilization config. Only use kv_cache_memory_bytes " "config when you want manual control of KV cache memory " "size. If OOM'ed, check the difference of initial free " "memory between the current run and the previous run " "where kv_cache_memory_bytes is suggested and update it " "correspondingly." ) logger.info(msg) return kv_cache_memory_bytes torch.cuda.empty_cache() torch.cuda.reset_peak_memory_stats() # Execute a forward pass with dummy inputs to profile the memory usage # of the model. with memory_profiling( self.init_snapshot, weights_memory=int(self.model_runner.model_memory_usage), ) as profile_result: self.model_runner.profile_run() self.non_torch_memory = profile_result.non_torch_increase self.peak_activation_memory = profile_result.torch_peak_increase free_gpu_memory = profile_result.after_profile.free_memory # NOTE(woosuk): Here we assume that the other processes using the same # GPU did not change their memory usage during the profiling. assert self.init_snapshot.free_memory > free_gpu_memory, ( "Error in memory profiling. " f"Initial free memory {GiB(self.init_snapshot.free_memory)} GiB, " f"current free memory {GiB(free_gpu_memory)} GiB. " "This happens when other processes sharing the same container " "release GPU memory while vLLM is profiling during initialization. " "To fix this, ensure consistent GPU memory allocation or " "isolate vLLM in its own container." ) self.available_kv_cache_memory_bytes = ( self.requested_memory - profile_result.non_kv_cache_memory ) unrequested_memory = self.init_snapshot.free_memory - self.requested_memory logger.debug( "Initial free memory: %.2f GiB; Requested memory: %.2f (util), %.2f GiB", GiB(self.init_snapshot.free_memory), self.cache_config.gpu_memory_utilization, GiB(self.requested_memory), ) logger.debug( "Free memory after profiling: %.2f GiB (total), " "%.2f GiB (within requested)", GiB(free_gpu_memory), GiB(free_gpu_memory - unrequested_memory), ) logger.debug(profile_result) logger.info_once( "Available KV cache memory: %.2f GiB", GiB(self.available_kv_cache_memory_bytes), scope="local", ) gc.collect() return int(self.available_kv_cache_memory_bytes) def get_kv_connector_handshake_metadata(self) -> dict | None: """Get KV connector metadata from this worker if available.""" if not has_kv_transfer_group(): return None connector = get_kv_transfer_group() # Return None for connectors that don't need to exchange handshake # metadata across workers. if (metadata := connector.get_handshake_metadata()) is None: return None tp_rank = get_tp_group().rank_in_group return {tp_rank: metadata} def get_kv_cache_spec(self) -> dict[str, KVCacheSpec]: return self.model_runner.get_kv_cache_spec() def update_max_model_len(self, max_model_len: int) -> None: """Update max_model_len after auto-fit to GPU memory. This is called when max_model_len=-1 is used and the engine automatically determines the maximum context length that fits in GPU memory. Workers need to update their cached max_model_len to match the engine's decision. """ self.model_config.max_model_len = max_model_len if self.model_runner is not None: self.model_runner.max_model_len = max_model_len logger.debug("Updated max_model_len to %d", max_model_len) def initialize_from_config(self, kv_cache_config: KVCacheConfig) -> None: """Allocate GPU KV cache with the specified kv_cache_config.""" # Init kv cache connector here, because it requires # `kv_cache_config`. # NOTE(Kuntai): This need to be done before `initialize_kv_cache`, # because `initialize_kv_cache` will inject kv cache groups not # related to kv cache connector (e.g. kv cache sharing layers). ensure_kv_transfer_initialized(self.vllm_config, kv_cache_config) if self.vllm_config.model_config.enable_sleep_mode: from vllm.device_allocator.cumem import CuMemAllocator allocator = CuMemAllocator.get_instance() with allocator.use_memory_pool(tag="kv_cache"): self.model_runner.initialize_kv_cache(kv_cache_config) else: self.model_runner.initialize_kv_cache(kv_cache_config) def compile_or_warm_up_model(self) -> None: warmup_sizes = [] if self.vllm_config.compilation_config.mode == CompilationMode.VLLM_COMPILE: # warm up sizes that are not in cudagraph capture sizes, # but users still want to compile for better performance, # e.g. for the max-num-batched token size in chunked prefill. compile_sizes = self.vllm_config.compilation_config.compile_sizes warmup_sizes = compile_sizes.copy() if compile_sizes is not None else [] cg_capture_sizes: list[int] = [] if self.vllm_config.compilation_config.cudagraph_mode != CUDAGraphMode.NONE: cg_sizes = self.vllm_config.compilation_config.cudagraph_capture_sizes cg_capture_sizes = [] if cg_sizes is None else cg_sizes warmup_sizes = [x for x in warmup_sizes if x not in cg_capture_sizes] compile_ranges = self.vllm_config.compilation_config.get_compile_ranges() # For each compile_range, if none of the batch sizes # in warmup_sizes or cudagraph_capture_sizes are in the range, # add the end of the range to ensure compilation/warmup. all_sizes = set(cg_capture_sizes) all_sizes.update([x for x in warmup_sizes if isinstance(x, int)]) for compile_range in compile_ranges: if not any(x in compile_range for x in all_sizes): warmup_sizes.append(compile_range.end) # We skip EPLB here since we don't want to record dummy metrics for size in sorted(warmup_sizes, reverse=True): logger.info("Compile and warming up model for size %d", size) self.model_runner._dummy_run(size, skip_eplb=True, remove_lora=False) self.model_runner.maybe_remove_all_loras(self.model_runner.lora_config) # Warmup and tune the kernels used during model execution before # cuda graph capture. kernel_warmup(self) cuda_graph_memory_bytes = 0 if not self.model_config.enforce_eager: cuda_graph_memory_bytes = self.model_runner.capture_model() if self.cache_config.kv_cache_memory_bytes is None and hasattr( self, "peak_activation_memory" ): # Suggests optimal kv cache memory size if we rely on # memory_profiling to guess the kv cache memory size which # provides peak_activation_memory and a few other memory # consumption. `memory_profiling` does not consider # CUDAGraph memory size and may not utilize all gpu memory. # Users may want fine-grained control to specify kv cache # memory size. GiB = lambda b: round(b / GiB_bytes, 2) # empirically observed that the memory profiling may # slightly underestimate the memory consumption. # So leave a small buffer (=150MiB) to avoid OOM. redundancy_buffer_memory = 150 * (1 << 20) non_kv_cache_memory = ( self.model_runner.model_memory_usage + self.peak_activation_memory + self.non_torch_memory + cuda_graph_memory_bytes ) kv_cache_memory_bytes_to_gpu_limit = ( self.init_snapshot.free_memory - non_kv_cache_memory - redundancy_buffer_memory ) kv_cache_memory_bytes_to_requested_limit = ( int(self.requested_memory) - non_kv_cache_memory - redundancy_buffer_memory ) msg = ( f"Free memory on device " f"({GiB(self.init_snapshot.free_memory)}/" f"{GiB(self.init_snapshot.total_memory)} GiB) on startup. " f"Desired GPU memory utilization is " f"({self.cache_config.gpu_memory_utilization}, " f"{GiB(self.requested_memory)} GiB). " f"Actual usage is {GiB(self.model_runner.model_memory_usage)} " f"GiB for weight, {GiB(self.peak_activation_memory)} GiB " f"for peak activation, {GiB(self.non_torch_memory)} GiB " f"for non-torch memory, and {GiB(cuda_graph_memory_bytes)} " f"GiB for CUDAGraph memory. Replace gpu_memory_utilization " f"config with `--kv-cache-memory=" f"{kv_cache_memory_bytes_to_requested_limit}` " f"({GiB(kv_cache_memory_bytes_to_requested_limit)} GiB) to fit " f"into requested memory, or `--kv-cache-memory=" f"{kv_cache_memory_bytes_to_gpu_limit}` " f"({GiB(kv_cache_memory_bytes_to_gpu_limit)} GiB) to fully " f"utilize gpu memory. Current kv cache memory in use is " f"{GiB(self.available_kv_cache_memory_bytes)} GiB." ) logger.debug(msg) # Warm up sampler and preallocate memory buffer for logits and other # sampling related tensors of max possible shape to avoid memory # fragmentation issue. # NOTE: This is called after `capture_model` on purpose to prevent # memory buffers from being cleared by `torch.cuda.empty_cache`. if get_pp_group().is_last_rank: max_num_reqs = min( self.scheduler_config.max_num_seqs, self.scheduler_config.max_num_batched_tokens, ) # We skip EPLB here since we don't want to record dummy metrics hidden_states, last_hidden_states = self.model_runner._dummy_run( num_tokens=max_num_reqs, skip_eplb=True, cudagraph_runtime_mode=CUDAGraphMode.NONE, ) if self.model_runner.is_pooling_model: self.model_runner._dummy_pooler_run(hidden_states) else: self.model_runner._dummy_sampler_run(hidden_states=last_hidden_states) # Reset the seed to ensure that the random state is not affected by # the model initialization and profiling. set_random_seed(self.model_config.seed) def reset_mm_cache(self) -> None: self.model_runner.reset_mm_cache() def get_model(self) -> nn.Module: return self.model_runner.get_model() def get_supported_tasks(self) -> tuple[SupportedTask, ...]: return self.model_runner.get_supported_tasks() def annotate_profile(self, scheduler_output): # add trace annotation so that we can easily distinguish # new/cached request numbers in each iteration if not self.profiler: return nullcontext() self.profiler.step() num_new = len(scheduler_output.scheduled_new_reqs) num_cached = len(scheduler_output.scheduled_cached_reqs.req_ids) return self.profiler.annotate_context_manager( f"execute_new_{num_new}_cached_{num_cached}" ) @torch.inference_mode() def sample_tokens( self, grammar_output: "GrammarOutput | None" ) -> ModelRunnerOutput | AsyncModelRunnerOutput: return self.model_runner.sample_tokens(grammar_output) @torch.inference_mode() def execute_model( self, scheduler_output: "SchedulerOutput" ) -> ModelRunnerOutput | AsyncModelRunnerOutput | None: intermediate_tensors = None forward_pass = scheduler_output.total_num_scheduled_tokens > 0 num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens all_gather_tensors = {} compilation_config = self.vllm_config.compilation_config parallel_config = self.vllm_config.parallel_config if ( parallel_config.pipeline_parallel_size > 1 and compilation_config.pass_config.enable_sp and forward_pass ): # currently only supported by V1 GPUModelRunner assert not self.use_v2_model_runner num_scheduled_tokens_np = np.array( list(scheduler_output.num_scheduled_tokens.values()), dtype=np.int32, ) # TODO(lucas): This is pretty gross; ideally we should only ever call # `_determine_batch_execution_and_padding` once (will get called again # in `execute_model`) but this requires a larger refactor of PP. _, batch_desc, _, _, _ = ( self.model_runner._determine_batch_execution_and_padding( num_tokens=num_scheduled_tokens, num_reqs=len(num_scheduled_tokens_np), num_scheduled_tokens_np=num_scheduled_tokens_np, max_num_scheduled_tokens=num_scheduled_tokens_np.max(), use_cascade_attn=False, # TODO(lucas): Handle cascade attention ) ) all_gather_tensors = { "residual": not is_residual_scattered_for_sp( self.vllm_config, batch_desc.num_tokens ) } if forward_pass and not get_pp_group().is_first_rank: tensor_dict = get_pp_group().recv_tensor_dict( all_gather_group=get_tp_group(), all_gather_tensors=all_gather_tensors, ) assert tensor_dict is not None intermediate_tensors = IntermediateTensors(tensor_dict) with self.annotate_profile(scheduler_output): output = self.model_runner.execute_model( scheduler_output, intermediate_tensors ) if isinstance( output, ModelRunnerOutput | AsyncModelRunnerOutput | NoneType ): return output assert isinstance(output, IntermediateTensors) parallel_config = self.vllm_config.parallel_config assert ( parallel_config.distributed_executor_backend != "external_launcher" and not get_pp_group().is_last_rank ) get_pp_group().send_tensor_dict( output.tensors, all_gather_group=get_tp_group(), all_gather_tensors=all_gather_tensors, ) return None def take_draft_token_ids(self) -> DraftTokenIds | None: return self.model_runner.take_draft_token_ids() def profile(self, is_start: bool = True): if self.profiler is None: raise RuntimeError( "Profiling is not enabled. Please set --profiler-config to enable " "profiling. Example: " "'--profiler-config.profiler=torch --profiler-config.torch_profiler_dir" "=YOUR_DIR_PATH_TO_DUMP_TRACE'" ) if is_start: self.profiler.start() else: self.profiler.stop() def execute_dummy_batch(self) -> None: if self.use_v2_model_runner: self.model_runner.execute_model( SchedulerOutput.make_empty(), dummy_run=True ) else: self.model_runner._dummy_run(1, uniform_decode=True) def add_lora(self, lora_request: LoRARequest) -> bool: return self.model_runner.add_lora(lora_request) def remove_lora(self, lora_id: int) -> bool: return self.model_runner.remove_lora(lora_id) def list_loras(self) -> set[int]: return self.model_runner.list_loras() def pin_lora(self, lora_id: int) -> bool: return self.model_runner.pin_lora(lora_id) def check_health(self) -> None: # worker will always be healthy as long as it's running. return def _eplb_before_scale_down(self, old_ep_size: int, new_ep_size: int) -> None: from vllm.distributed.parallel_state import get_ep_group if get_ep_group().rank == 0: logger.info( "[Elastic EP] Starting expert resharding before scaling down..." ) rank_mapping = { old_ep_rank: old_ep_rank if old_ep_rank < new_ep_size else -1 for old_ep_rank in range(old_ep_size) } assert self.model_runner.eplb_state is not None self.model_runner.eplb_state.rearrange( execute_shuffle=True, global_expert_loads=None, rank_mapping=rank_mapping, ) torch.cuda.synchronize() if get_ep_group().rank == 0: logger.info("[Elastic EP] Expert resharding completed!") def _eplb_after_scale_up( self, old_ep_size: int, new_ep_size: int, global_expert_loads: list[torch.Tensor] | None, ) -> None: from vllm.distributed.parallel_state import get_ep_group if get_ep_group().rank == 0: logger.info("[Elastic EP] Starting expert resharding after scaling up...") rank_mapping = {old_ep_rank: old_ep_rank for old_ep_rank in range(old_ep_size)} assert self.model_runner.eplb_state is not None self.model_runner.eplb_state.rearrange( execute_shuffle=True, global_expert_loads=global_expert_loads, rank_mapping=rank_mapping, ) if get_ep_group().rank == 0: logger.info("[Elastic EP] Expert resharding completed!") def _reconfigure_parallel_config( self, reconfig_request: ReconfigureDistributedRequest ) -> None: """ Update parallel config with provided reconfig_request """ parallel_config = self.vllm_config.parallel_config parallel_config.data_parallel_size = reconfig_request.new_data_parallel_size if ( reconfig_request.new_data_parallel_rank != ReconfigureRankType.KEEP_CURRENT_RANK ): parallel_config.data_parallel_rank = reconfig_request.new_data_parallel_rank if ( reconfig_request.new_data_parallel_rank_local != ReconfigureRankType.KEEP_CURRENT_RANK ): parallel_config.data_parallel_rank_local = ( reconfig_request.new_data_parallel_rank_local ) parallel_config.data_parallel_master_ip = ( reconfig_request.new_data_parallel_master_ip ) parallel_config.data_parallel_master_port = ( reconfig_request.new_data_parallel_master_port ) def _reconfigure_moe( self, old_ep_size: int, new_ep_size: int ) -> list[torch.Tensor] | None: """ Reconfigure MoE modules with provided reconfig_request Return the global expert load if new_ep_size > old_ep_size, otherwise None """ from vllm.distributed.parallel_state import ( get_dp_group, get_ep_group, prepare_communication_buffer_for_model, ) from vllm.model_executor.layers.fused_moe.layer import ( FusedMoE, FusedMoEParallelConfig, ) parallel_config = self.vllm_config.parallel_config def get_moe_modules(model: torch.nn.Module) -> list[FusedMoE]: return [ module for module in model.modules() if ( module.__class__.__name__ == "FusedMoE" or module.__class__.__name__ == "SharedFusedMoE" ) ] def update_moe_modules(moe_modules: list[FusedMoE], num_local_experts: int): assert all(
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/__init__.py
vllm/v1/worker/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/worker_base.py
vllm/v1/worker/worker_base.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os from collections.abc import Callable from typing import TYPE_CHECKING, Any, TypeVar import torch import torch.nn as nn from vllm.config import VllmConfig, set_current_vllm_config from vllm.logger import init_logger from vllm.lora.request import LoRARequest from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.cache import worker_receiver_cache_from_config from vllm.utils.import_utils import resolve_obj_by_qualname from vllm.utils.system_utils import update_environment_variables from vllm.v1.kv_cache_interface import KVCacheSpec from vllm.v1.serial_utils import run_method if TYPE_CHECKING: from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput from vllm.v1.outputs import AsyncModelRunnerOutput, ModelRunnerOutput else: SchedulerOutput = object GrammarOutput = object AsyncModelRunnerOutput = object ModelRunnerOutput = object logger = init_logger(__name__) _R = TypeVar("_R") class WorkerBase: """Worker interface that allows vLLM to cleanly separate implementations for different hardware. Also abstracts control plane communication, e.g., to communicate request metadata to other workers. """ def __init__( self, vllm_config: VllmConfig, local_rank: int, rank: int, distributed_init_method: str, is_driver_worker: bool = False, ) -> None: """ Initialize common worker components. Args: vllm_config: Complete vLLM configuration local_rank: Local device index rank: Global rank in distributed setup distributed_init_method: Distributed initialization method is_driver_worker: Whether this worker handles driver responsibilities """ self.vllm_config = vllm_config self.model_config = vllm_config.model_config self.cache_config = vllm_config.cache_config self.lora_config = vllm_config.lora_config self.load_config = vllm_config.load_config self.parallel_config = vllm_config.parallel_config self.scheduler_config = vllm_config.scheduler_config self.device_config = vllm_config.device_config self.speculative_config = vllm_config.speculative_config self.observability_config = vllm_config.observability_config self.kv_transfer_config = vllm_config.kv_transfer_config self.compilation_config = vllm_config.compilation_config from vllm.platforms import current_platform self.current_platform = current_platform self.parallel_config.rank = rank self.local_rank = local_rank self.rank = rank self.distributed_init_method = distributed_init_method self.is_driver_worker = is_driver_worker # Device and model state self.device: torch.device | None = None self.model_runner: nn.Module | None = None def get_kv_cache_spec(self) -> dict[str, KVCacheSpec]: """Get specifications for KV cache implementation.""" raise NotImplementedError def compile_or_warm_up_model(self) -> None: """Prepare model for execution through compilation/warmup.""" raise NotImplementedError def check_health(self) -> None: """Basic health check (override for device-specific checks).""" return def init_device(self) -> None: """Initialize device state, such as loading the model or other on-device memory allocations. """ raise NotImplementedError def initialize_cache(self, num_gpu_blocks: int, num_cpu_blocks: int) -> None: """Initialize the KV cache with the given size in blocks.""" raise NotImplementedError def reset_mm_cache(self) -> None: reset_fn = getattr(self.model_runner, "reset_mm_cache", None) if callable(reset_fn): reset_fn() def get_model(self) -> nn.Module: raise NotImplementedError def apply_model(self, fn: Callable[[nn.Module], _R]) -> _R: """Apply a function on the model inside this worker.""" return fn(self.get_model()) def load_model(self) -> None: """Load model onto target device.""" raise NotImplementedError def execute_model( self, scheduler_output: SchedulerOutput ) -> ModelRunnerOutput | AsyncModelRunnerOutput | None: """If this method returns None, sample_tokens should be called immediately after to obtain the ModelRunnerOutput. Note that this design may be changed in future if/when structured outputs parallelism is re-architected. """ raise NotImplementedError def sample_tokens( self, grammar_output: GrammarOutput ) -> ModelRunnerOutput | AsyncModelRunnerOutput: """Should be called immediately after execute_model iff it returned None.""" raise NotImplementedError def get_cache_block_size_bytes(self) -> int: """Return the size of a single cache block, in bytes. Used in speculative decoding. """ raise NotImplementedError def add_lora(self, lora_request: LoRARequest) -> bool: raise NotImplementedError def remove_lora(self, lora_id: int) -> bool: raise NotImplementedError def pin_lora(self, lora_id: int) -> bool: raise NotImplementedError def list_loras(self) -> set[int]: raise NotImplementedError @property def vocab_size(self) -> int: """Get vocabulary size from model configuration.""" return self.model_config.get_vocab_size() def shutdown(self) -> None: """Clean up resources held by the worker.""" return class WorkerWrapperBase: """ This class represents one process in an executor/engine. It is responsible for lazily initializing the worker and handling the worker's lifecycle. We first instantiate the WorkerWrapper, which remembers the worker module and class name. Then, when we call `update_environment_variables`, and the real initialization happens in `init_worker`. """ def __init__( self, vllm_config: VllmConfig, rpc_rank: int = 0, global_rank: int | None = None, ) -> None: """ Initialize the worker wrapper with the given vllm_config and rpc_rank. Note: rpc_rank is the rank of the worker in the executor. In most cases, it is also the rank of the worker in the distributed group. However, when multiple executors work together, they can be different. e.g. in the case of SPMD-style offline inference with TP=2, users can launch 2 engines/executors, each with only 1 worker. All workers have rpc_rank=0, but they have different ranks in the TP group. """ self.rpc_rank = rpc_rank self.global_rank = self.rpc_rank if global_rank is None else global_rank self.worker: WorkerBase | None = None # do not store this `vllm_config`, `init_worker` will set the final # one. # TODO: investigate if we can remove this field in `WorkerWrapperBase`, # `init_cached_hf_modules` should be unnecessary now. self.vllm_config: VllmConfig | None = None # `model_config` can be None in tests model_config = vllm_config.model_config if model_config and model_config.trust_remote_code: # note: lazy import to avoid importing torch before initializing from vllm.utils.import_utils import init_cached_hf_modules init_cached_hf_modules() def shutdown(self) -> None: if self.worker is not None: self.worker.shutdown() def adjust_rank(self, rank_mapping: dict[int, int]) -> None: """ Adjust the rpc_rank based on the given mapping. It is only used during the initialization of the executor, to adjust the rpc_rank of workers after we create all workers. """ if self.rpc_rank in rank_mapping: self.rpc_rank = rank_mapping[self.rpc_rank] def update_environment_variables( self, envs_list: list[dict[str, str]], ) -> None: envs = envs_list[self.rpc_rank] key = "CUDA_VISIBLE_DEVICES" if key in envs and key in os.environ: # overwriting CUDA_VISIBLE_DEVICES is desired behavior # suppress the warning in `update_environment_variables` del os.environ[key] update_environment_variables(envs) def init_worker(self, all_kwargs: list[dict[str, Any]]) -> None: """ Here we inject some common logic before initializing the worker. Arguments are passed to the worker class constructor. """ kwargs = all_kwargs[self.rpc_rank] self.vllm_config = kwargs.get("vllm_config") assert self.vllm_config is not None, ( "vllm_config is required to initialize the worker" ) self.vllm_config.enable_trace_function_call_for_thread() from vllm.plugins import load_general_plugins load_general_plugins() if isinstance(self.vllm_config.parallel_config.worker_cls, str): worker_class = resolve_obj_by_qualname( self.vllm_config.parallel_config.worker_cls ) else: raise ValueError( "passing worker_cls is no longer supported. Please pass keep the class in a separate module and pass the qualified name of the class as a string." # noqa: E501 ) if self.vllm_config.parallel_config.worker_extension_cls: worker_extension_cls = resolve_obj_by_qualname( self.vllm_config.parallel_config.worker_extension_cls ) extended_calls = [] if worker_extension_cls not in worker_class.__bases__: # check any conflicts between worker and worker_extension_cls for attr in dir(worker_extension_cls): if attr.startswith("__"): continue assert not hasattr(worker_class, attr), ( f"Worker class {worker_class} already has an attribute" f" {attr}, which conflicts with the worker" f" extension class {worker_extension_cls}." ) if callable(getattr(worker_extension_cls, attr)): extended_calls.append(attr) # dynamically inherit the worker extension class worker_class.__bases__ = worker_class.__bases__ + ( worker_extension_cls, ) logger.info( "Injected %s into %s for extended collective_rpc calls %s", worker_extension_cls, worker_class, extended_calls, ) shared_worker_lock = kwargs.pop("shared_worker_lock", None) if shared_worker_lock is None: msg = ( "Missing `shared_worker_lock` argument from executor. " "This argument is needed for mm_processor_cache_type='shm'." ) mm_config = self.vllm_config.model_config.multimodal_config if mm_config and mm_config.mm_processor_cache_type == "shm": raise ValueError(msg) else: logger.warning_once(msg) self.mm_receiver_cache = None else: self.mm_receiver_cache = worker_receiver_cache_from_config( self.vllm_config, MULTIMODAL_REGISTRY, shared_worker_lock, ) with set_current_vllm_config(self.vllm_config): # To make vLLM config available during worker initialization self.worker = worker_class(**kwargs) assert self.worker is not None def initialize_from_config(self, kv_cache_configs: list[Any]) -> None: kv_cache_config = kv_cache_configs[self.global_rank] assert self.vllm_config is not None with set_current_vllm_config(self.vllm_config): self.worker.initialize_from_config(kv_cache_config) # type: ignore def init_device(self): assert self.vllm_config is not None with set_current_vllm_config(self.vllm_config): # To make vLLM config available during device initialization self.worker.init_device() # type: ignore def execute_method(self, method: str | bytes, *args, **kwargs): try: # method resolution order: # if a method is defined in this class, it will be called directly. # otherwise, since we define `__getattr__` and redirect attribute # query to `self.worker`, the method will be called on the worker. return run_method(self, method, args, kwargs) except Exception as e: # if the driver worker also execute methods, # exceptions in the rest worker may cause deadlock in rpc like ray # see https://github.com/vllm-project/vllm/issues/3455 # print the error and inform the user to solve the error msg = ( f"Error executing method {method!r}. " "This might cause deadlock in distributed execution." ) logger.exception(msg) raise e def __getattr__(self, attr: str): return getattr(self.worker, attr) def _apply_mm_cache(self, scheduler_output: SchedulerOutput) -> None: mm_cache = self.mm_receiver_cache if mm_cache is None: return for req_data in scheduler_output.scheduled_new_reqs: req_data.mm_features = mm_cache.get_and_update_features( req_data.mm_features ) def execute_model( self, scheduler_output: SchedulerOutput, *args, **kwargs, ) -> ModelRunnerOutput | AsyncModelRunnerOutput | None: self._apply_mm_cache(scheduler_output) assert self.worker is not None return self.worker.execute_model(scheduler_output, *args, **kwargs) def reset_mm_cache(self) -> None: mm_receiver_cache = self.mm_receiver_cache if mm_receiver_cache is not None: mm_receiver_cache.clear_cache() assert self.worker is not None self.worker.reset_mm_cache()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/dp_utils.py
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, should_dp_pad: 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(5, 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] = 1 if should_dp_pad else 0 tensor[4][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[4, :].min().item()) def _synchronize_dp_ranks( num_tokens_unpadded: int, num_tokens_padded: int, should_attempt_ubatching: bool, should_attempt_dp_padding: 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 should_attempt_dp_padding is True, all ranks will be padded out so that the 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, should_dp_pad=should_attempt_dp_padding, orig_num_tokens_per_ubatch=num_tokens_unpadded, padded_num_tokens_per_ubatch=num_tokens_padded, cudagraph_mode=cudagraph_mode, parallel_config=parallel_config, ) should_dp_pad = bool(torch.all(tensor[3] == 1).item()) # DP ranks should all have the same value for should_attempt_dp_padding. assert should_attempt_dp_padding == should_dp_pad # Check conditions for microbatching should_ubatch = _post_process_ubatch(tensor, parallel_config.num_ubatches) if should_ubatch and not should_dp_pad: logger.debug_once( "Microbatching has been triggered and requires DP padding. " "Enabling DP padding even though it has been explicitly " "disabled.", scope="global", ) should_dp_pad = True # 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, ) # Synchronize cudagraph_mode across ranks (take min) synced_cudagraph_mode = _post_process_cudagraph_mode(tensor) return should_ubatch, num_tokens_after_padding, synced_cudagraph_mode def coordinate_batch_across_dp( num_tokens_unpadded: int, allow_microbatching: bool, allow_dp_padding: 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 allow_dp_padding: If all DP ranks should be padded up to the same value 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) 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 allow_dp_padding is True. 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, allow_dp_padding, cudagraph_mode, parallel_config, ) ) return (should_ubatch, num_tokens_after_padding, synced_cudagraph_mode)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/cp_utils.py
vllm/v1/worker/cp_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import TYPE_CHECKING, Any, cast from vllm.config import VllmConfig, get_layers_from_vllm_config if TYPE_CHECKING: from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase else: AttentionLayerBase = object def check_attention_cp_compatibility(vllm_config: VllmConfig) -> None: pcp_size = vllm_config.parallel_config.prefill_context_parallel_size dcp_size = vllm_config.parallel_config.decode_context_parallel_size interleave_size = vllm_config.parallel_config.cp_kv_cache_interleave_size if pcp_size * dcp_size > 1: layer_type = cast(type[Any], AttentionLayerBase) layers = get_layers_from_vllm_config(vllm_config, layer_type) for layer in layers.values(): layer_impl = getattr(layer, "impl", None) if layer_impl is None: continue if vllm_config.speculative_config is not None and interleave_size > 1: assert layer_impl.supports_mtp_with_cp_non_trivial_interleave_size, ( "MTP with cp_kv_cache_interleave_size > 1 is not " f"supported in {layer_impl.__class__.__name__}." ) if dcp_size > 1: assert layer_impl.need_to_return_lse_for_decode, ( "DCP requires attention impls to return" " the softmax lse for decode, but the impl " f"{layer_impl.__class__.__name__} " "does not return the softmax lse for decode." ) if pcp_size > 1: assert layer_impl.supports_pcp, ( "PCP requires attention impls' support, " f"but the impl {layer_impl.__class__.__name__} " "does not support PCP." )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/input_batch.py
vllm/v1/worker/gpu/input_batch.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import Any import numpy as np import torch from vllm.triton_utils import tl, triton from vllm.utils import random_uuid from vllm.utils.math_utils import cdiv from vllm.v1.utils import CpuGpuBuffer class InputBuffers: def __init__( self, max_num_reqs: int, max_num_tokens: int, inputs_embeds_size: int, vocab_size: int, dtype: torch.dtype, device: torch.device, pin_memory: bool, ): self.max_num_reqs = max_num_reqs self.max_num_tokens = max_num_tokens self.device = device self.pin_memory = pin_memory self.idx_mapping = self._make_buffer(max_num_reqs, dtype=torch.int32) self.input_ids = torch.zeros(max_num_tokens, dtype=torch.int32, device=device) self.positions = torch.zeros(max_num_tokens, dtype=torch.int64, device=device) self.query_start_loc = self._make_buffer(max_num_reqs + 1, dtype=torch.int32) self.seq_lens = torch.zeros(max_num_reqs, dtype=torch.int32, device=device) self.cu_num_logits = self._make_buffer(max_num_reqs + 1, dtype=torch.int32) # Structured outputs. self.bitmask_indices = self._make_buffer(max_num_reqs, dtype=torch.int32) self.grammar_bitmask = self._make_buffer( max_num_reqs, cdiv(vocab_size, 32), dtype=torch.int32 ) def _make_buffer(self, *args, dtype: torch.dtype) -> CpuGpuBuffer: return CpuGpuBuffer( *args, dtype=dtype, pin_memory=self.pin_memory, device=self.device ) @dataclass class InputBatch: # batch_idx -> req_id req_ids: list[str] num_reqs: int # batch_idx -> req_state_idx idx_mapping: torch.Tensor idx_mapping_np: np.ndarray # [num_reqs] # batch_idx -> num_scheduled_tokens num_scheduled_tokens: np.ndarray # sum(num_scheduled_tokens) num_tokens: int num_tokens_after_padding: int num_draft_tokens: int # [num_reqs + 1] query_start_loc: torch.Tensor query_start_loc_np: np.ndarray # [num_reqs] seq_lens: torch.Tensor seq_lens_np: np.ndarray # [num_tokens_after_padding] input_ids: torch.Tensor # [num_tokens_after_padding] positions: torch.Tensor # layer_name -> Metadata attn_metadata: dict[str, Any] # [total_num_logits] logits_indices: torch.Tensor # [num_reqs + 1] cu_num_logits: torch.Tensor @classmethod def make_dummy( cls, num_reqs: int, num_tokens: int, input_buffers: InputBuffers, device: torch.device, ) -> "InputBatch": assert 0 < num_reqs <= num_tokens req_ids = [f"req_{i}_{random_uuid()}" for i in range(num_reqs)] idx_mapping_np = np.arange(num_reqs, dtype=np.int32) idx_mapping = torch.arange(num_reqs, dtype=torch.int32, device=device) num_scheduled_tokens = np.full(num_reqs, num_tokens // num_reqs, dtype=np.int32) num_scheduled_tokens[-1] += num_tokens % num_reqs assert int(num_scheduled_tokens.sum()) == num_tokens input_buffers.query_start_loc.np[0] = 0 input_buffers.query_start_loc.np[1 : num_reqs + 1] = np.cumsum( num_scheduled_tokens ) input_buffers.query_start_loc.np[num_reqs + 1 :] = num_tokens query_start_loc_np = input_buffers.query_start_loc.np[: num_reqs + 1] query_start_loc = input_buffers.query_start_loc.copy_to_gpu()[: num_reqs + 1] # seq_len equals to query_len seq_lens_np = np.full(num_reqs, num_tokens // num_reqs, dtype=np.int32) seq_lens_np[-1] += num_tokens % num_reqs input_buffers.seq_lens[:num_reqs] = num_tokens // num_reqs input_buffers.seq_lens[num_reqs - 1] += num_tokens % num_reqs input_buffers.seq_lens[num_reqs:] = 0 seq_lens = input_buffers.seq_lens[:num_reqs] input_ids = input_buffers.input_ids[:num_tokens] positions = input_buffers.positions[:num_tokens] # attn_metadata = defaultdict(lambda: None) logits_indices = query_start_loc[1:] - 1 cu_num_logits = torch.arange(num_reqs + 1, device=device, dtype=torch.int32) return cls( req_ids=req_ids, num_reqs=num_reqs, idx_mapping=idx_mapping, idx_mapping_np=idx_mapping_np, num_scheduled_tokens=num_scheduled_tokens, num_tokens=num_tokens, num_tokens_after_padding=num_tokens, num_draft_tokens=0, query_start_loc=query_start_loc, query_start_loc_np=query_start_loc_np, seq_lens=seq_lens, seq_lens_np=seq_lens_np, input_ids=input_ids, positions=positions, attn_metadata=None, # type: ignore logits_indices=logits_indices, cu_num_logits=cu_num_logits, ) @triton.jit def _prepare_prefill_inputs_kernel( input_ids_ptr, next_prefill_tokens_ptr, idx_mapping_ptr, query_start_loc_ptr, prefill_token_ids_ptr, prefill_token_ids_stride, prefill_lens_ptr, num_computed_tokens_ptr, BLOCK_SIZE: tl.constexpr, ): batch_idx = tl.program_id(0) req_state_idx = tl.load(idx_mapping_ptr + batch_idx) prefill_len = tl.load(prefill_lens_ptr + req_state_idx) num_computed = tl.load(num_computed_tokens_ptr + req_state_idx) if num_computed >= prefill_len: # Not prefill. return query_start = tl.load(query_start_loc_ptr + batch_idx) query_end = tl.load(query_start_loc_ptr + batch_idx + 1) query_len = query_end - query_start prefill_ptr = prefill_token_ids_ptr + req_state_idx * prefill_token_ids_stride for i in range(0, query_len, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < query_len tokens = tl.load(prefill_ptr + num_computed + block, mask=mask) tl.store(input_ids_ptr + query_start + block, tokens, mask=mask) next_pos = num_computed + query_len if next_pos < prefill_len: next_token = tl.load(prefill_ptr + next_pos) tl.store(next_prefill_tokens_ptr + req_state_idx, next_token) def prepare_prefill_inputs( input_ids: torch.Tensor, next_prefill_tokens: torch.Tensor, idx_mapping: torch.Tensor, query_start_loc: torch.Tensor, prefill_token_ids: torch.Tensor, prefill_len: torch.Tensor, num_computed_tokens: torch.Tensor, ) -> None: num_reqs = idx_mapping.shape[0] _prepare_prefill_inputs_kernel[(num_reqs,)]( input_ids, next_prefill_tokens, idx_mapping, query_start_loc, prefill_token_ids, prefill_token_ids.stride(0), prefill_len, num_computed_tokens, BLOCK_SIZE=1024, ) @triton.jit def _prepare_pos_seq_lens_kernel( pos_ptr, seq_lens_ptr, idx_mapping_ptr, query_start_loc_ptr, num_computed_tokens_ptr, max_num_reqs, BLOCK_SIZE: tl.constexpr, ): req_id = tl.program_id(0) num_reqs = tl.num_programs(0) - 1 if req_id == num_reqs: # Pad unused seq_lens as 0 for full CUDA graphs. for i in tl.range(num_reqs, max_num_reqs, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < max_num_reqs tl.store(seq_lens_ptr + block, 0, mask=mask) return req_state_idx = tl.load(idx_mapping_ptr + req_id) num_computed_tokens = tl.load(num_computed_tokens_ptr + req_state_idx) start = tl.load(query_start_loc_ptr + req_id) end = tl.load(query_start_loc_ptr + req_id + 1) query_len = end - start seq_len = num_computed_tokens + query_len tl.store(seq_lens_ptr + req_id, seq_len) for i in tl.range(0, query_len, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < query_len pos = num_computed_tokens + block tl.store(pos_ptr + start + block, pos, mask=mask) def prepare_pos_seq_lens( idx_mapping: torch.Tensor, query_start_loc: torch.Tensor, num_computed_tokens: torch.Tensor, pos: torch.Tensor, seq_lens: torch.Tensor, ) -> None: num_reqs = idx_mapping.shape[0] # NOTE(woosuk): We do +1 because the last thread block is used # to pad unused seq_lens as 0 for full CUDA graphs. _prepare_pos_seq_lens_kernel[(num_reqs + 1,)]( pos, seq_lens, idx_mapping, query_start_loc, num_computed_tokens, seq_lens.shape[0], BLOCK_SIZE=1024, ) @triton.jit def _combine_sampled_and_draft_tokens_kernel( input_ids_ptr, idx_mapping_ptr, last_sampled_tokens_ptr, query_start_loc_ptr, seq_lens_ptr, prefill_len_ptr, draft_tokens_ptr, draft_tokens_stride, cu_num_logits_ptr, logits_indices_ptr, BLOCK_SIZE: tl.constexpr, ): batch_idx = tl.program_id(0) req_state_idx = tl.load(idx_mapping_ptr + batch_idx) # Get the number of logits and draft tokens. cu_num_logits_start = tl.load(cu_num_logits_ptr + batch_idx) cu_num_logits_end = tl.load(cu_num_logits_ptr + batch_idx + 1) num_logits = cu_num_logits_end - cu_num_logits_start num_draft_tokens = num_logits - 1 # Compute the logits indices. block = tl.arange(0, BLOCK_SIZE) query_end = tl.load(query_start_loc_ptr + batch_idx + 1) logits_start = query_end - num_logits tl.store( logits_indices_ptr + cu_num_logits_start + block, logits_start + block, mask=block < num_logits, ) seq_len = tl.load(seq_lens_ptr + batch_idx) prefill_len = tl.load(prefill_len_ptr + req_state_idx) if seq_len <= prefill_len: # Handling prefill tokens. No sampled or draft tokens. return # Write the last sampled token ID to input_ids. last_token_id = tl.load(last_sampled_tokens_ptr + req_state_idx) tl.store(input_ids_ptr + query_end - num_logits, last_token_id) # Write the draft tokens (if any) to input_ids. if num_draft_tokens > 0: mask = block < num_draft_tokens draft_tokens = tl.load( draft_tokens_ptr + req_state_idx * draft_tokens_stride + block, mask=mask, ) tl.store( input_ids_ptr + query_end - num_draft_tokens + block, draft_tokens, mask=mask, ) def combine_sampled_and_draft_tokens( input_ids: torch.Tensor, idx_mapping: torch.Tensor, last_sampled_tokens: torch.Tensor, query_start_loc: torch.Tensor, seq_lens: torch.Tensor, prefill_len: torch.Tensor, draft_tokens: torch.Tensor, cu_num_logits: torch.Tensor, num_logits: int, ) -> torch.Tensor: num_reqs = seq_lens.shape[0] num_speculative_steps = draft_tokens.shape[-1] logits_indices = torch.empty( num_logits, dtype=torch.int64, device=input_ids.device, ) _combine_sampled_and_draft_tokens_kernel[(num_reqs,)]( input_ids, idx_mapping, last_sampled_tokens, query_start_loc, seq_lens, prefill_len, draft_tokens, draft_tokens.stride(0), cu_num_logits, logits_indices, # NOTE(woosuk): Add 1 to ensure the block can cover the last sampled token # in addition to all draft tokens. BLOCK_SIZE=triton.next_power_of_2(num_speculative_steps + 1), ) return logits_indices @triton.jit def _get_num_sampled_and_rejected_kernel( num_sampled_ptr, num_rejected_ptr, seq_lens_ptr, cu_num_logits_ptr, idx_mapping_ptr, prefill_len_ptr, ): batch_idx = tl.program_id(0) req_state_idx = tl.load(idx_mapping_ptr + batch_idx) seq_len = tl.load(seq_lens_ptr + batch_idx) prefill_len = tl.load(prefill_len_ptr + req_state_idx) is_chunked_prefilling = seq_len < prefill_len num_sampled = tl.load(num_sampled_ptr + batch_idx) num_sampled = tl.where(is_chunked_prefilling, 0, num_sampled) tl.store(num_sampled_ptr + batch_idx, num_sampled) logits_start = tl.load(cu_num_logits_ptr + batch_idx) logits_end = tl.load(cu_num_logits_ptr + batch_idx + 1) num_logits = logits_end - logits_start num_rejected = num_logits - num_sampled num_rejected = tl.where(is_chunked_prefilling, 0, num_rejected) tl.store(num_rejected_ptr + batch_idx, num_rejected) def get_num_sampled_and_rejected( num_sampled: torch.Tensor, seq_lens: torch.Tensor, cu_num_logits: torch.Tensor, idx_mapping: torch.Tensor, prefill_len: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: num_reqs = idx_mapping.shape[0] num_rejected = torch.empty_like(num_sampled) _get_num_sampled_and_rejected_kernel[(num_reqs,)]( num_sampled, num_rejected, seq_lens, cu_num_logits, idx_mapping, prefill_len, ) return num_sampled, num_rejected @triton.jit def _post_update_kernel( idx_mapping_ptr, num_computed_tokens_ptr, last_sampled_tokens_ptr, output_bin_counts_ptr, output_bin_counts_stride, sampled_tokens_ptr, sampled_tokens_stride, num_sampled_ptr, num_rejected_ptr, query_start_loc_ptr, ): req_id = tl.program_id(0) req_state_idx = tl.load(idx_mapping_ptr + req_id) num_sampled = tl.load(num_sampled_ptr + req_id) if num_sampled > 0: token_id = tl.load( sampled_tokens_ptr + req_id * sampled_tokens_stride + num_sampled - 1 ) tl.store(last_sampled_tokens_ptr + req_state_idx, token_id) for i in range(num_sampled): token_id = tl.load(sampled_tokens_ptr + req_id * sampled_tokens_stride + i) token_ptr = ( output_bin_counts_ptr + req_state_idx * output_bin_counts_stride + token_id ) count = tl.load(token_ptr) count += 1 tl.store(token_ptr, count) query_start = tl.load(query_start_loc_ptr + req_id) query_end = tl.load(query_start_loc_ptr + req_id + 1) query_len = query_end - query_start num_rejected = tl.load(num_rejected_ptr + req_id) num_computed = tl.load(num_computed_tokens_ptr + req_state_idx) num_computed += query_len - num_rejected tl.store(num_computed_tokens_ptr + req_state_idx, num_computed) def post_update( # [num_reqs] idx_mapping: torch.Tensor, # [max_num_reqs] num_computed_tokens: torch.Tensor, # [max_num_reqs] last_sampled_tokens: torch.Tensor, # [max_num_reqs, vocab_size] output_bin_counts: torch.Tensor, # [num_reqs, num_speculative_steps + 1] sampled_tokens: torch.Tensor, # [num_reqs] num_sampled: torch.Tensor, # [num_reqs] num_rejected: torch.Tensor, # [num_reqs + 1] query_start_loc: torch.Tensor, ) -> None: num_reqs = idx_mapping.shape[0] _post_update_kernel[(num_reqs,)]( idx_mapping, num_computed_tokens, last_sampled_tokens, output_bin_counts, output_bin_counts.stride(0), sampled_tokens, sampled_tokens.stride(0), num_sampled, num_rejected, query_start_loc, num_warps=1, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/async_utils.py
vllm/v1/worker/gpu/async_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from contextlib import contextmanager import numpy as np import torch from vllm.v1.outputs import ( AsyncModelRunnerOutput, LogprobsTensors, ModelRunnerOutput, ) from vllm.v1.worker.gpu.sample.output import SamplerOutput class AsyncOutput(AsyncModelRunnerOutput): def __init__( self, model_runner_output: ModelRunnerOutput, sampler_output: SamplerOutput, num_sampled_tokens: torch.Tensor, copy_stream: torch.cuda.Stream, copy_event: torch.cuda.Event, ): # NOTE(woosuk): We must retain references to the GPU tensors, # as the copy operations are performed on a different CUDA stream than # the one where the tensors were created. self.model_runner_output = model_runner_output self.sampler_output = sampler_output self.num_sampled_tokens = num_sampled_tokens self.copy_stream = copy_stream self.copy_event = copy_event default_stream = torch.cuda.current_stream() with torch.cuda.stream(self.copy_stream): self.copy_stream.wait_stream(default_stream) self.sampled_token_ids = async_copy_to_np(sampler_output.sampled_token_ids) if sampler_output.logprobs_tensors is not None: self.logprobs_tensors: LogprobsTensors | None = ( sampler_output.logprobs_tensors.to_cpu_nonblocking() ) else: self.logprobs_tensors = None if sampler_output.num_nans is not None: self.num_nans = async_copy_to_np(sampler_output.num_nans) else: self.num_nans = None self.num_sampled_tokens_np = async_copy_to_np(num_sampled_tokens) self.prompt_logprobs_dict: dict[str, LogprobsTensors | None] = {} if self.model_runner_output.prompt_logprobs_dict: for k, v in self.model_runner_output.prompt_logprobs_dict.items(): if v is not None: self.prompt_logprobs_dict[k] = v.to_cpu_nonblocking() else: self.prompt_logprobs_dict[k] = None self.copy_event.record(self.copy_stream) def get_output(self) -> ModelRunnerOutput: self.copy_event.synchronize() # NOTE(woosuk): The following code is to ensure compatibility with # the existing model runner. # Going forward, we should keep the data structures as NumPy arrays # rather than Python lists. sampled_token_ids: list[list[int]] = self.sampled_token_ids.tolist() num_reqs = len(sampled_token_ids) num_sampled_tokens = self.num_sampled_tokens_np.tolist() for i in range(num_reqs): del sampled_token_ids[i][num_sampled_tokens[i] :] self.model_runner_output.sampled_token_ids = sampled_token_ids if self.num_nans is not None: num_nans = self.num_nans.tolist() self.model_runner_output.num_nans_in_logits = { req_id: num_nans[i] for i, req_id in enumerate(self.model_runner_output.req_ids) } if self.logprobs_tensors is not None: self.model_runner_output.logprobs = self.logprobs_tensors.tolists() self.model_runner_output.prompt_logprobs_dict = self.prompt_logprobs_dict return self.model_runner_output @contextmanager def async_barrier(event: torch.cuda.Event | None): if event is not None: event.synchronize() try: yield finally: if event is not None: event.record() def async_copy_to_np(x: torch.Tensor) -> np.ndarray: return x.to("cpu", non_blocking=True).numpy()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/model_runner.py
vllm/v1/worker/gpu/model_runner.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import gc import time from copy import deepcopy from typing import Any import numpy as np import torch import torch.nn as nn from vllm.config import VllmConfig from vllm.config.compilation import CUDAGraphMode from vllm.forward_context import set_forward_context from vllm.logger import init_logger from vllm.model_executor.model_loader import get_model_loader from vllm.utils.mem_constants import GiB_bytes from vllm.utils.mem_utils import DeviceMemoryProfiler from vllm.utils.platform_utils import is_pin_memory_available from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.outputs import ( EMPTY_MODEL_RUNNER_OUTPUT, LogprobsTensors, ModelRunnerOutput, ) from vllm.v1.worker.gpu.async_utils import AsyncOutput, async_barrier from vllm.v1.worker.gpu.attn_utils import ( build_attn_metadata, get_kv_cache_spec, init_attn_backend, init_kv_cache, ) from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1.worker.gpu.cudagraph_utils import CudaGraphManager from vllm.v1.worker.gpu.dp_utils import ( get_batch_metadata_across_dp, make_num_tokens_across_dp, ) from vllm.v1.worker.gpu.input_batch import ( InputBatch, InputBuffers, combine_sampled_and_draft_tokens, get_num_sampled_and_rejected, post_update, prepare_pos_seq_lens, prepare_prefill_inputs, ) from vllm.v1.worker.gpu.sample.logprob import compute_prompt_logprobs from vllm.v1.worker.gpu.sample.metadata import ( SamplingMetadata, expand_sampling_metadata, ) from vllm.v1.worker.gpu.sample.output import SamplerOutput from vllm.v1.worker.gpu.sample.sampler import Sampler from vllm.v1.worker.gpu.spec_decode import init_speculator from vllm.v1.worker.gpu.spec_decode.rejection_sample import rejection_sample from vllm.v1.worker.gpu.states import RequestState from vllm.v1.worker.gpu.structured_outputs import apply_grammar_bitmask from vllm.v1.worker.kv_connector_model_runner_mixin import KVConnectorModelRunnerMixin from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin logger = init_logger(__name__) class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin): def __init__( self, vllm_config: VllmConfig, device: torch.device, ): self.vllm_config = vllm_config self.model_config = vllm_config.model_config self.cache_config = vllm_config.cache_config self.compilation_config = vllm_config.compilation_config self.lora_config = vllm_config.lora_config self.load_config = vllm_config.load_config self.parallel_config = vllm_config.parallel_config self.scheduler_config = vllm_config.scheduler_config self.speculative_config = vllm_config.speculative_config self.observability_config = vllm_config.observability_config self.device = device self.pin_memory = is_pin_memory_available() self.dtype = self.model_config.dtype self.kv_cache_dtype = self.dtype if self.cache_config.cache_dtype != "auto": # Quantized KV cache. self.kv_cache_dtype = STR_DTYPE_TO_TORCH_DTYPE[ self.cache_config.cache_dtype ] self.is_pooling_model = False self.vocab_size = self.model_config.get_vocab_size() self.max_model_len = self.model_config.max_model_len self.max_num_tokens = self.scheduler_config.max_num_batched_tokens self.max_num_reqs = self.scheduler_config.max_num_seqs self.inputs_embeds_size = self.model_config.get_inputs_embeds_size() self.use_async_scheduling = self.scheduler_config.async_scheduling self.output_copy_stream = torch.cuda.Stream(self.device) self.output_copy_event = torch.cuda.Event() if self.use_async_scheduling: self.input_prep_event = torch.cuda.Event() self.structured_outputs_event = torch.cuda.Event() else: self.input_prep_event = None self.structured_outputs_event = None if self.speculative_config is not None: self.do_spec_decode = True self.num_speculative_steps = self.speculative_config.num_speculative_tokens self.speculator = init_speculator(self.vllm_config, self.device) else: self.do_spec_decode = False self.num_speculative_steps = 0 self.speculator = None self.req_states = RequestState( max_num_reqs=self.max_num_reqs, max_model_len=self.max_model_len, max_num_batched_tokens=self.max_num_tokens, num_speculative_steps=self.num_speculative_steps, vocab_size=self.vocab_size, device=self.device, pin_memory=self.pin_memory, ) self.input_buffers = InputBuffers( max_num_reqs=self.max_num_reqs, max_num_tokens=self.max_num_tokens, inputs_embeds_size=self.inputs_embeds_size, vocab_size=self.vocab_size, dtype=self.dtype, device=self.device, pin_memory=self.pin_memory, ) self.sampler = Sampler(logprobs_mode=self.model_config.logprobs_mode) # CUDA graphs. self.cudagraph_manager = CudaGraphManager(self.vllm_config, self.device) def get_supported_tasks(self) -> tuple[str]: return ("generate",) def load_model(self, *args, **kwargs) -> None: time_before_load = time.perf_counter() with DeviceMemoryProfiler() as m: model_loader = get_model_loader(self.vllm_config.load_config) logger.info("Loading model from scratch...") self.model = model_loader.load_model( vllm_config=self.vllm_config, model_config=self.vllm_config.model_config, ) if self.lora_config: self.model = self.load_lora_model( self.model, self.vllm_config, self.device, ) if self.do_spec_decode: self.speculator.load_model(self.model) time_after_load = time.perf_counter() self.model_memory_usage = m.consumed_memory logger.info( "Model loading took %.4f GiB and %.6f seconds", m.consumed_memory / GiB_bytes, time_after_load - time_before_load, ) def get_model(self) -> nn.Module: return self.model def get_kv_cache_spec(self): return get_kv_cache_spec(self.vllm_config) def initialize_kv_cache(self, kv_cache_config: KVCacheConfig) -> None: kv_cache_config = deepcopy(kv_cache_config) self.kv_cache_config = kv_cache_config block_sizes = [ kv_cache_group.kv_cache_spec.block_size for kv_cache_group in kv_cache_config.kv_cache_groups ] self.block_tables = BlockTables( block_sizes=block_sizes, max_num_reqs=self.max_num_reqs, max_num_batched_tokens=self.max_num_tokens, max_model_len=self.max_model_len, device=self.device, pin_memory=self.pin_memory, ) self.attn_backends, self.attn_metadata_builders = init_attn_backend( self.kv_cache_config, self.vllm_config, self.device, ) if self.do_spec_decode: # HACK(woosuk) self.speculator.set_attn( self.kv_cache_config, self.attn_metadata_builders, self.block_tables, ) # TODO(woosuk): Support other backends. if not all(b.get_name() == "FLASH_ATTN" for b in self.attn_backends.values()): raise NotImplementedError("Only FLASH_ATTN backend is supported currently.") self.kv_caches: list[torch.Tensor] = [] init_kv_cache( self.kv_caches, self.compilation_config.static_forward_context, self.kv_cache_config, self.attn_backends, self.device, ) # Attention groups are not supported. self.attn_groups = [] # type: ignore def prepare_dummy_attn_metadata(self, input_batch: InputBatch) -> None: block_tables = self.block_tables.get_dummy_block_tables(input_batch.num_reqs) slot_mappings = self.block_tables.get_dummy_slot_mappings( input_batch.num_tokens ) num_computed_tokens = torch.zeros( input_batch.num_reqs, dtype=torch.int32, device=self.device ) query_start_loc = self.input_buffers.query_start_loc query_start_loc_gpu = query_start_loc.gpu[: input_batch.num_reqs + 1] query_start_loc_cpu = query_start_loc.cpu[: input_batch.num_reqs + 1] attn_metadata = build_attn_metadata( attn_metadata_builders=self.attn_metadata_builders, num_reqs=input_batch.num_reqs, num_tokens=input_batch.num_tokens, query_start_loc_gpu=query_start_loc_gpu, query_start_loc_cpu=query_start_loc_cpu, seq_lens=self.input_buffers.seq_lens, seq_lens_np=input_batch.seq_lens_np, num_computed_tokens_cpu=num_computed_tokens, block_tables=block_tables, slot_mappings=slot_mappings, kv_cache_config=self.kv_cache_config, ) input_batch.attn_metadata = attn_metadata @torch.inference_mode() def _dummy_run( self, num_tokens: int, *args, skip_attn: bool = True, **kwargs, ) -> tuple[torch.Tensor, torch.Tensor]: num_reqs = min(num_tokens, self.max_num_reqs) input_batch = InputBatch.make_dummy( num_reqs=num_reqs, num_tokens=num_tokens, input_buffers=self.input_buffers, device=self.device, ) if not skip_attn: self.prepare_dummy_attn_metadata(input_batch) dp_size = self.parallel_config.data_parallel_size num_tokens_across_dp = make_num_tokens_across_dp(dp_size, num_tokens) num_sampled_tokens = np.ones(input_batch.num_reqs, dtype=np.int32) with ( self.maybe_dummy_run_with_lora( self.lora_config, input_batch.num_scheduled_tokens, num_sampled_tokens, ), set_forward_context( input_batch.attn_metadata, self.vllm_config, num_tokens=num_tokens, num_tokens_across_dp=num_tokens_across_dp, ), ): hidden_states = self.model( input_ids=input_batch.input_ids, positions=input_batch.positions, ) sample_hidden_states = hidden_states[input_batch.logits_indices] return hidden_states, sample_hidden_states @torch.inference_mode() def _dummy_sampler_run( self, hidden_states: torch.Tensor, ) -> None: num_reqs = hidden_states.shape[0] sampling_metadata = SamplingMetadata.make_dummy( num_reqs=num_reqs, device=self.device, ) logits = self.model.compute_logits(hidden_states) self.sampler(logits, sampling_metadata) @torch.inference_mode() def profile_run(self) -> None: hidden_states, sample_hidden_states = self._dummy_run( self.max_num_tokens, skip_attn=True, ) self._dummy_sampler_run(sample_hidden_states) if self.do_spec_decode: num_tokens_across_dp = make_num_tokens_across_dp( self.parallel_config.data_parallel_size, self.max_num_tokens ) self.speculator.run_model( self.max_num_tokens, attn_metadata=None, num_tokens_across_dp=num_tokens_across_dp, ) torch.cuda.synchronize() del hidden_states, sample_hidden_states gc.collect() def reset_mm_cache(self) -> None: pass def _get_num_input_tokens(self, num_scheduled_tokens: int) -> int: # SP is not supported yet. return num_scheduled_tokens @torch.inference_mode() def capture_model(self) -> int: if not self.cudagraph_manager.needs_capture(): logger.warning( "Skipping CUDA graph capture. To turn on CUDA graph capture, " "ensure `cudagraph_mode` was not manually set to `NONE`" ) return 0 start_time = time.perf_counter() gc.collect() torch.cuda.empty_cache() start_free_gpu_memory = torch.cuda.mem_get_info()[0] with self.maybe_setup_dummy_loras(self.lora_config): self.cudagraph_manager.capture( model=self.model, input_buffers=self.input_buffers, block_tables=self.block_tables, attn_metadata_builders=self.attn_metadata_builders, kv_cache_config=self.kv_cache_config, ) if self.do_spec_decode: self.speculator.capture_model() end_time = time.perf_counter() end_free_gpu_memory = torch.cuda.mem_get_info()[0] elapsed_time = end_time - start_time cuda_graph_size = start_free_gpu_memory - end_free_gpu_memory # This usually takes 5~20 seconds. logger.info( "Graph capturing finished in %.0f secs, took %.2f GiB", elapsed_time, cuda_graph_size / (1 << 30), ) return cuda_graph_size def warmup_for_prefill(self) -> None: # For FlashInfer, we would like to execute a dummy prefill run # to trigger JIT compilation. if all("FLASHINFER" in b.get_name() for b in self.attn_backends.values()): self._dummy_run(self.max_num_tokens, skip_attn=False) torch.cuda.synchronize() def update_states(self, scheduler_output: SchedulerOutput) -> None: if scheduler_output.preempted_req_ids is not None: for req_id in scheduler_output.preempted_req_ids: self.req_states.remove_request(req_id) for req_id in scheduler_output.finished_req_ids: self.req_states.remove_request(req_id) # TODO(woosuk): Change SchedulerOutput. req_indices: list[int] = [] cu_num_new_blocks = tuple( [0] for _ in range(self.block_tables.num_kv_cache_groups) ) new_block_ids: tuple[list[int], ...] = tuple( [] for _ in range(self.block_tables.num_kv_cache_groups) ) overwrite: list[bool] = [] # Add new requests. for new_req_data in scheduler_output.scheduled_new_reqs: assert new_req_data.prompt_token_ids is not None assert new_req_data.prefill_token_ids is not None assert new_req_data.sampling_params is not None req_id = new_req_data.req_id self.req_states.add_request( req_id=req_id, prompt_len=len(new_req_data.prompt_token_ids), prefill_token_ids=new_req_data.prefill_token_ids, num_computed_tokens=new_req_data.num_computed_tokens, sampling_params=new_req_data.sampling_params, lora_request=new_req_data.lora_request, ) req_index = self.req_states.req_id_to_index[req_id] req_indices.append(req_index) for i, block_ids in enumerate(new_req_data.block_ids): x = cu_num_new_blocks[i][-1] cu_num_new_blocks[i].append(x + len(block_ids)) new_block_ids[i].extend(block_ids) overwrite.append(True) if scheduler_output.scheduled_new_reqs: self.req_states.prefill_len.copy_to_gpu() # Add new blocks for the existing requests. cached_reqs = scheduler_output.scheduled_cached_reqs for i, req_id in enumerate(cached_reqs.req_ids): req_index = self.req_states.req_id_to_index[req_id] req_new_block_ids = cached_reqs.new_block_ids[i] if req_new_block_ids is not None: req_indices.append(req_index) for group_id, block_ids in enumerate(req_new_block_ids): x = cu_num_new_blocks[group_id][-1] cu_num_new_blocks[group_id].append(x + len(block_ids)) new_block_ids[group_id].extend(block_ids) overwrite.append(False) if req_indices: self.block_tables.append_block_ids( req_indices=req_indices, cu_num_new_blocks=cu_num_new_blocks, new_block_ids=new_block_ids, overwrite=overwrite, ) def prepare_inputs( self, scheduler_output: SchedulerOutput, num_tokens_after_padding: int, ) -> InputBatch: num_tokens = scheduler_output.total_num_scheduled_tokens assert num_tokens > 0 num_reqs = len(scheduler_output.num_scheduled_tokens) # Decode first, then prefill. # batch_idx -> req_id req_ids = sorted( scheduler_output.num_scheduled_tokens.keys(), key=lambda k: scheduler_output.num_scheduled_tokens[k], ) num_scheduled_tokens = np.array( [scheduler_output.num_scheduled_tokens[i] for i in req_ids], dtype=np.int32 ) idx_mapping_list = [ self.req_states.req_id_to_index[req_id] for req_id in req_ids ] idx_mapping = self.input_buffers.idx_mapping idx_mapping.np[:num_reqs] = idx_mapping_list idx_mapping_np = idx_mapping.np[:num_reqs] idx_mapping = idx_mapping.copy_to_gpu(num_reqs) # Get the number of draft tokens for each request. if not scheduler_output.scheduled_spec_decode_tokens: # No draft token scheduled (common case). total_num_draft_tokens = 0 total_num_logits = num_reqs cu_num_logits = torch.arange( num_reqs + 1, device=self.device, dtype=torch.int32 ) else: draft_tokens = scheduler_output.scheduled_spec_decode_tokens num_draft_tokens = np.array( [ len(draft_tokens[req_id]) if req_id in draft_tokens else 0 for req_id in req_ids ], dtype=np.int32, ) total_num_draft_tokens = int(num_draft_tokens.sum()) total_num_logits = num_reqs + total_num_draft_tokens np.cumsum( num_draft_tokens + 1, out=self.input_buffers.cu_num_logits.np[1 : num_reqs + 1], ) cu_num_logits = self.input_buffers.cu_num_logits.copy_to_gpu(num_reqs + 1) # Block tables: num_kv_cache_groups x [num_reqs, max_num_blocks] block_tables = self.block_tables.gather_block_tables(idx_mapping) # Get query_start_loc. np.cumsum( num_scheduled_tokens, out=self.input_buffers.query_start_loc.np[1 : num_reqs + 1], ) # Pad for full CUDA graph mode. # Some attention backends like FA3 require query_start_loc to be non-decreasing. self.input_buffers.query_start_loc.np[num_reqs + 1 :] = num_tokens self.input_buffers.query_start_loc.copy_to_gpu() query_start_loc_gpu = self.input_buffers.query_start_loc.gpu[: num_reqs + 1] query_start_loc_cpu = self.input_buffers.query_start_loc.cpu[: num_reqs + 1] query_start_loc_np = self.input_buffers.query_start_loc.np[: num_reqs + 1] # Get prefill tokens. prepare_prefill_inputs( self.input_buffers.input_ids, self.req_states.next_prefill_tokens, idx_mapping, query_start_loc_gpu, self.req_states.prefill_token_ids.gpu, self.req_states.prefill_len.gpu, self.req_states.num_computed_tokens, ) # Prepare positions and seq_lens. prepare_pos_seq_lens( idx_mapping, query_start_loc_gpu, self.req_states.num_computed_tokens, self.input_buffers.positions, self.input_buffers.seq_lens, ) seq_lens = self.input_buffers.seq_lens[:num_reqs] # Some input token ids are directly read from the last sampled tokens # and draft tokens. Also, get the logits indices to sample tokens from. logits_indices = combine_sampled_and_draft_tokens( self.input_buffers.input_ids, idx_mapping, self.req_states.last_sampled_tokens, query_start_loc_gpu, seq_lens, self.req_states.prefill_len.gpu, self.req_states.draft_tokens, cu_num_logits, total_num_logits, ) # Compute slot mappings: [num_kv_cache_groups, num_tokens] slot_mappings = self.block_tables.compute_slot_mappings( query_start_loc_gpu, self.input_buffers.positions[:num_tokens] ) # Get num_computed_tokens. # HACK(woosuk): Here, we use num_computed_tokens on GPU instead of # num_computed_tokens_cpu. This works for most cases. num_computed_tokens = self.req_states.num_computed_tokens[idx_mapping] # HACK(woosuk): Only GPU has the exact seq_lens because at this point # CPU does not know how many draft tokens are accepted/rejected in the # previous step. Therefore, we use max_model_len to be safe. # NOTE(woosuk): This only works for FA3 backend. seq_lens_np = np.full(num_reqs, self.max_model_len, dtype=np.int32) # Layer name -> attention metadata. attn_metadata = build_attn_metadata( attn_metadata_builders=self.attn_metadata_builders, num_reqs=num_reqs, num_tokens=num_tokens, query_start_loc_gpu=query_start_loc_gpu, query_start_loc_cpu=query_start_loc_cpu, seq_lens=self.input_buffers.seq_lens, seq_lens_np=seq_lens_np, num_computed_tokens_cpu=num_computed_tokens, block_tables=block_tables, slot_mappings=slot_mappings, kv_cache_config=self.kv_cache_config, ) input_ids = self.input_buffers.input_ids[:num_tokens_after_padding] positions = self.input_buffers.positions[:num_tokens_after_padding] return InputBatch( req_ids=req_ids, num_reqs=num_reqs, idx_mapping=idx_mapping, idx_mapping_np=idx_mapping_np, num_scheduled_tokens=num_scheduled_tokens, num_tokens=num_tokens, num_tokens_after_padding=num_tokens_after_padding, num_draft_tokens=total_num_draft_tokens, query_start_loc=query_start_loc_gpu, query_start_loc_np=query_start_loc_np, seq_lens=seq_lens, seq_lens_np=seq_lens_np, input_ids=input_ids, positions=positions, attn_metadata=attn_metadata, logits_indices=logits_indices, cu_num_logits=cu_num_logits, ) def sample( self, hidden_states: torch.Tensor, input_batch: InputBatch, sampling_metadata: SamplingMetadata, grammar_output: GrammarOutput | None, ) -> tuple[SamplerOutput, torch.Tensor, torch.Tensor]: sample_hidden_states = hidden_states[input_batch.logits_indices] logits = self.model.compute_logits(sample_hidden_states) if grammar_output is not None: # Apply grammar bitmask to the logits in-place. # TODO(woosuk): Make compatible with spec decoding. assert input_batch.num_draft_tokens == 0 with async_barrier(self.structured_outputs_event): apply_grammar_bitmask( logits, input_batch.req_ids, grammar_output.structured_output_request_ids, grammar_output.grammar_bitmask, self.input_buffers, ) # Sample tokens and compute logprobs (if needed). sampler_output = self.sampler(logits, sampling_metadata) if input_batch.num_draft_tokens == 0: # No draft tokens (common case). num_sampled = torch.ones( input_batch.num_reqs, dtype=torch.int32, device=self.device ) else: # Rejection sampling for spec decoding. input_ids = input_batch.input_ids[input_batch.logits_indices] sampled_tokens, num_sampled = rejection_sample( sampler_output.sampled_token_ids, input_ids, input_batch.cu_num_logits, self.num_speculative_steps, ) sampler_output.sampled_token_ids = sampled_tokens # Get the number of sampled and rejected tokens. # For chunked prefills, num_sampled and num_rejected are both 0. num_sampled, num_rejected = get_num_sampled_and_rejected( num_sampled, input_batch.seq_lens, input_batch.cu_num_logits, input_batch.idx_mapping, self.req_states.prefill_len.gpu, ) return sampler_output, num_sampled, num_rejected def compute_prompt_logprobs( self, hidden_states: torch.Tensor, input_batch: InputBatch, ) -> dict[str, LogprobsTensors]: idx_mapping_np = input_batch.idx_mapping_np needs_prompt_logprobs = self.req_states.needs_prompt_logprobs[idx_mapping_np] if not np.any(needs_prompt_logprobs): # No request asks for prompt logprobs. return {} prompt_lens = self.req_states.prompt_len[idx_mapping_np] # NOTE(woosuk): -1 because the last prompt token's hidden state is not # needed for prompt logprobs. computed_prefill = self.req_states.num_computed_prefill_tokens[idx_mapping_np] includes_prompt = computed_prefill < prompt_lens - 1 # NOTE(woosuk): If the request was resumed after preemption, its prompt # logprobs must have been computed before preemption. Skip. resumed_after_prompt = ( prompt_lens < self.req_states.prefill_len.np[idx_mapping_np] ) needs_prompt_logprobs &= includes_prompt & ~resumed_after_prompt if not np.any(needs_prompt_logprobs): return {} # Just to be safe, clone the input ids. n = input_batch.num_tokens # Shift the input ids by one. token_ids = torch.empty_like(input_batch.input_ids[:n]) token_ids[: n - 1] = input_batch.input_ids[1:n] # To avoid out-of-bound access, set the last token id to 0. token_ids[n - 1] = 0 # Handle chunked prompts. pos_after_step = computed_prefill + input_batch.num_scheduled_tokens is_prompt_chunked = pos_after_step < prompt_lens prefill_token_ids = self.req_states.prefill_token_ids.np query_start_loc = self.input_buffers.query_start_loc.np for i, req_id in enumerate(input_batch.req_ids): if not needs_prompt_logprobs[i]: continue if not is_prompt_chunked[i]: continue # The prompt is chunked. Get the next prompt token. req_idx = input_batch.idx_mapping_np[i] next_prompt_token = int(prefill_token_ids[req_idx, pos_after_step[i]]) idx = int(query_start_loc[i + 1] - 1) # Set the next prompt token. # NOTE(woosuk): This triggers a GPU operation. token_ids[idx] = next_prompt_token # NOTE(woosuk): We mask out logprobs for negative tokens. prompt_logprobs, prompt_ranks = compute_prompt_logprobs( token_ids, hidden_states[:n], self.model.compute_logits, ) prompt_token_ids = token_ids.unsqueeze(-1) prompt_logprobs_dict: dict[str, LogprobsTensors] = {} for i, req_id in enumerate(input_batch.req_ids): if not needs_prompt_logprobs[i]: continue start_idx = query_start_loc[i] end_idx = query_start_loc[i + 1] assert start_idx < end_idx, ( f"start_idx ({start_idx}) >= end_idx ({end_idx})" ) logprobs = LogprobsTensors( logprob_token_ids=prompt_token_ids[start_idx:end_idx], logprobs=prompt_logprobs[start_idx:end_idx], selected_token_ranks=prompt_ranks[start_idx:end_idx], ) req_extra_data = self.req_states.extra_data[req_id] prompt_logprobs_list = req_extra_data.in_progress_prompt_logprobs if is_prompt_chunked[i]: # Prompt is chunked. Do not return the logprobs yet. prompt_logprobs_list.append(logprobs) continue if prompt_logprobs_list: # Merge the in-progress logprobs. prompt_logprobs_list.append(logprobs) logprobs = LogprobsTensors( logprob_token_ids=torch.cat( [x.logprob_token_ids for x in prompt_logprobs_list] ), logprobs=torch.cat([x.logprobs for x in prompt_logprobs_list]), selected_token_ranks=torch.cat( [x.selected_token_ranks for x in prompt_logprobs_list] ), ) prompt_logprobs_list.clear() prompt_logprobs_dict[req_id] = logprobs return prompt_logprobs_dict def postprocess( self, input_batch: InputBatch, sampled_tokens: torch.Tensor, num_sampled: torch.Tensor, num_rejected: torch.Tensor, ) -> None: # Update the number of computed tokens. post_update( input_batch.idx_mapping, self.req_states.num_computed_tokens, self.req_states.last_sampled_tokens, self.req_states.output_bin_counts, sampled_tokens, num_sampled, num_rejected, input_batch.query_start_loc, ) # Update the number of computed prefill tokens. idx_mapping_np = input_batch.idx_mapping_np computed_prefill = self.req_states.num_computed_prefill_tokens # TODO(woosuk): Simplify this. computed_prefill[idx_mapping_np] = np.minimum( computed_prefill[idx_mapping_np] + input_batch.num_scheduled_tokens, self.req_states.prefill_len.np[idx_mapping_np], ) @torch.inference_mode() def propose_draft( self, input_batch: InputBatch, sampling_metadata: SamplingMetadata, last_hidden_states: torch.Tensor, aux_hidden_states: list[torch.Tensor] | None, num_sampled: torch.Tensor, num_rejected: torch.Tensor, ) -> torch.Tensor: assert self.speculator is not None last_sampled_tokens = self.req_states.last_sampled_tokens[ input_batch.idx_mapping ] next_prefill_tokens = self.req_states.next_prefill_tokens[ input_batch.idx_mapping ] draft_tokens = self.speculator.propose( input_batch, sampling_metadata, last_hidden_states, aux_hidden_states, num_sampled, num_rejected, last_sampled_tokens, next_prefill_tokens, ) return draft_tokens def get_cudagraph_and_dp_padding( self, scheduler_output: SchedulerOutput, ) -> tuple[CUDAGraphMode, int, torch.Tensor | None]: total_num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens dp_size = self.parallel_config.data_parallel_size if dp_size == 1: # No DP. Only consider CUDA graphs. if total_num_scheduled_tokens == 0: # Special case: no tokens to run. return CUDAGraphMode.NONE, 0, None cudagraph_size = self.cudagraph_manager.get_cudagraph_size( scheduler_output, total_num_scheduled_tokens ) if cudagraph_size is not None: # Use full CUDA graph.
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/states.py
vllm/v1/worker/gpu/states.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass, field import numpy as np import torch from vllm.lora.request import LoRARequest from vllm.sampling_params import SamplingParams from vllm.utils.math_utils import cdiv from vllm.utils.platform_utils import is_uva_available from vllm.utils.torch_utils import get_cuda_view_from_cpu_tensor from vllm.v1.outputs import LogprobsTensors from vllm.v1.utils import CpuGpuBuffer from vllm.v1.worker.gpu.sample.metadata import SamplingMetadata from vllm.v1.worker.gpu.sample.penalties import bincount _NP_INT64_MIN = np.iinfo(np.int64).min _NP_INT64_MAX = np.iinfo(np.int64).max NO_LORA_ID = 0 class RequestState: def __init__( self, max_num_reqs: int, max_model_len: int, max_num_batched_tokens: int, num_speculative_steps: int, vocab_size: int, device: torch.device, pin_memory: bool, ): self.max_num_reqs = max_num_reqs self.max_model_len = max_model_len self.max_num_batched_tokens = max_num_batched_tokens self.num_speculative_steps = num_speculative_steps self.vocab_size = vocab_size self.device = device self.pin_memory = pin_memory self.req_id_to_index: dict[str, int] = {} self.index_to_req_id: dict[int, str] = {} self.free_indices = list(range(max_num_reqs)) self.extra_data: dict[str, ExtraData] = {} self.prompt_len = np.zeros(self.max_num_reqs, dtype=np.int32) # NOTE(woosuk): This tensor can be extremely large (e.g., several GBs) # depending on the configured max_num_reqs and max_model_len. self.prefill_token_ids = UvaBuffer( self.max_num_reqs, self.max_model_len, dtype=torch.int32 ) # NOTE(woosuk): We don't use UVA for prefill_len because its GPU view # can be used outside of update_states and prepare_inputs. # Without async barrier, using UVA can cause race conditions. self.prefill_len = self._make_buffer(self.max_num_reqs, dtype=torch.int32) # Number of computed tokens. self.num_computed_prefill_tokens = np.zeros(self.max_num_reqs, dtype=np.int32) self.num_computed_tokens = torch.zeros( self.max_num_reqs, dtype=torch.int32, device=device ) # Last sampled tokens. self.last_sampled_tokens = torch.zeros( self.max_num_reqs, 1, dtype=torch.int64, device=device, ) # Draft tokens. self.draft_tokens = torch.zeros( self.max_num_reqs, self.num_speculative_steps, dtype=torch.int64, device=device, ) self.next_prefill_tokens = torch.zeros( self.max_num_reqs, dtype=torch.int32, device=device ) # LoRA. self.lora_ids = np.zeros(self.max_num_reqs, dtype=np.int32) self.lora_ids.fill(NO_LORA_ID) # Sampling parameters. self.temperature = self._make_param(self.max_num_reqs, torch.float32) self.top_p = self._make_param(self.max_num_reqs, torch.float32) self.top_k = self._make_param(self.max_num_reqs, torch.int32) self.min_p = self._make_param(self.max_num_reqs, torch.float32) self.repetition_penalty = self._make_param(self.max_num_reqs, torch.float32) self.frequency_penalty = self._make_param(self.max_num_reqs, torch.float32) self.presence_penalty = self._make_param(self.max_num_reqs, torch.float32) self.seeds = self._make_param(self.max_num_reqs, torch.int64) self.num_logprobs = np.empty(self.max_num_reqs, dtype=np.int32) # -1 means no logprobs are requested. self.num_logprobs.fill(-1) self.needs_prompt_logprobs = np.zeros(self.max_num_reqs, dtype=bool) # Statistics for penalties. self.prompt_bin_mask = torch.zeros( self.max_num_reqs, cdiv(self.vocab_size, 32), dtype=torch.int32, device=self.device, ) # TODO(woosuk): This tensor is rarely used but can be extremely large. # Optimize the memory usage. self.output_bin_counts = torch.zeros( self.max_num_reqs, self.vocab_size, dtype=torch.int32, device=self.device ) def _make_param(self, size: int, dtype: torch.dtype) -> "Param": return Param(size, dtype=dtype, device=self.device, pin_memory=self.pin_memory) def _make_buffer(self, size: int, dtype: torch.dtype) -> CpuGpuBuffer: return CpuGpuBuffer( size, dtype=dtype, device=self.device, pin_memory=self.pin_memory ) @property def num_reqs(self) -> int: return len(self.req_id_to_index) def add_request( self, req_id: str, prompt_len: int, prefill_token_ids: list[int], num_computed_tokens: int, sampling_params: SamplingParams, lora_request: LoRARequest | None, ) -> None: assert len(self.free_indices) > 0, "No free indices" req_idx = self.free_indices.pop() self.req_id_to_index[req_id] = req_idx self.index_to_req_id[req_idx] = req_id self.extra_data[req_id] = ExtraData(lora_request) self.prompt_len[req_idx] = prompt_len prefill_len = len(prefill_token_ids) assert prefill_len >= prompt_len, ( f"prefill_len {prefill_len} < prompt_len {prompt_len}" ) self.prefill_len.np[req_idx] = prefill_len self.prefill_token_ids.np[req_idx, :prefill_len] = prefill_token_ids self.num_computed_prefill_tokens[req_idx] = num_computed_tokens # FIXME(woosuk): This triggers a GPU operation whenever adding a new request. # Optimize this. self.num_computed_tokens[req_idx] = num_computed_tokens if lora_request is not None: self.lora_ids[req_idx] = lora_request.lora_int_id else: self.lora_ids[req_idx] = NO_LORA_ID self.temperature.np[req_idx] = sampling_params.temperature self.top_p.np[req_idx] = sampling_params.top_p if 0 < sampling_params.top_k < self.vocab_size: top_k = sampling_params.top_k else: top_k = self.vocab_size self.top_k.np[req_idx] = top_k self.min_p.np[req_idx] = sampling_params.min_p self.repetition_penalty.np[req_idx] = sampling_params.repetition_penalty self.frequency_penalty.np[req_idx] = sampling_params.frequency_penalty self.presence_penalty.np[req_idx] = sampling_params.presence_penalty if use_penalty(sampling_params): bincount( self.prefill_token_ids.gpu[req_idx], prefill_len, prompt_len, self.prompt_bin_mask[req_idx], self.output_bin_counts[req_idx], ) if sampling_params.seed is not None: seed = sampling_params.seed else: seed = np.random.randint(_NP_INT64_MIN, _NP_INT64_MAX) self.seeds.np[req_idx] = seed if sampling_params.logprobs is not None: num_logprobs = sampling_params.logprobs else: num_logprobs = -1 self.num_logprobs[req_idx] = num_logprobs # For now, only support prompt logprobs for the prompt tokens. needs_prompt_logprobs = sampling_params.prompt_logprobs is not None self.needs_prompt_logprobs[req_idx] = needs_prompt_logprobs def remove_request(self, req_id: str) -> None: self.extra_data.pop(req_id, None) req_idx = self.req_id_to_index.pop(req_id, None) if req_idx is None: # Request not found. return self.index_to_req_id.pop(req_idx, None) self.free_indices.append(req_idx) def make_sampling_metadata( self, idx_mapping: torch.Tensor, idx_mapping_np: np.ndarray, pos: torch.Tensor, ) -> SamplingMetadata: temperature = self.temperature.np[idx_mapping_np] temperature = self.temperature.copy_np_to_gpu(temperature) top_p = self.top_p.np[idx_mapping_np] no_top_p = np.all(top_p == 1.0) top_p = self.top_p.copy_np_to_gpu(top_p) if not no_top_p else None top_k = self.top_k.np[idx_mapping_np] no_top_k = np.all(top_k == self.vocab_size) top_k = self.top_k.copy_np_to_gpu(top_k) if not no_top_k else None min_p = self.min_p.np[idx_mapping_np] no_min_p = np.all(min_p == 0.0) min_p = self.min_p.copy_np_to_gpu(min_p) if not no_min_p else None rep_penalty = self.repetition_penalty.np[idx_mapping_np] rep_penalty = self.repetition_penalty.copy_np_to_gpu(rep_penalty) freq_penalty = self.frequency_penalty.np[idx_mapping_np] freq_penalty = self.frequency_penalty.copy_np_to_gpu(freq_penalty) pres_penalty = self.presence_penalty.np[idx_mapping_np] pres_penalty = self.presence_penalty.copy_np_to_gpu(pres_penalty) seeds = self.seeds.np[idx_mapping_np] seeds = self.seeds.copy_np_to_gpu(seeds) num_logprobs = self.num_logprobs[idx_mapping_np] max_num_logprobs: int | None = int(np.max(num_logprobs)) if max_num_logprobs == -1: max_num_logprobs = None return SamplingMetadata( temperature=temperature, top_p=top_p, top_k=top_k, min_p=min_p, repetition_penalty=rep_penalty, frequency_penalty=freq_penalty, presence_penalty=pres_penalty, seeds=seeds, pos=pos, max_num_logprobs=max_num_logprobs, idx_mapping=idx_mapping, prompt_bin_mask=self.prompt_bin_mask, output_bin_counts=self.output_bin_counts, ) def make_lora_inputs( self, req_ids: list[str], idx_mapping: np.ndarray, num_scheduled_tokens: np.ndarray, ) -> tuple[tuple[int, ...], tuple[int, ...], set[LoRARequest]]: lora_ids = self.lora_ids[idx_mapping] prompt_lora_mapping = tuple(lora_ids) token_lora_mapping = tuple(lora_ids.repeat(num_scheduled_tokens)) active_lora_requests: set[LoRARequest] = set() for req_id in req_ids: lora_request = self.extra_data[req_id].lora_request if lora_request is not None: active_lora_requests.add(lora_request) return prompt_lora_mapping, token_lora_mapping, active_lora_requests class Param: def __init__( self, size: int, dtype: torch.dtype, device: torch.device, pin_memory: bool, ): self.buffer = CpuGpuBuffer( size, dtype=dtype, device=device, pin_memory=pin_memory, ) self.np = np.zeros_like(self.buffer.np) def copy_np_to_gpu(self, x: np.ndarray) -> torch.Tensor: n = x.shape[0] self.buffer.np[:n] = x return self.buffer.copy_to_gpu(n) @dataclass class ExtraData: lora_request: LoRARequest | None in_progress_prompt_logprobs: list[LogprobsTensors] = field(default_factory=list) class UvaBuffer: def __init__(self, *size: int | torch.SymInt, dtype: torch.dtype): assert is_uva_available() self.cpu = torch.zeros(*size, dtype=dtype, device="cpu", pin_memory=True) self.np = self.cpu.numpy() self.gpu = get_cuda_view_from_cpu_tensor(self.cpu) def use_penalty(sampling_params: SamplingParams) -> bool: return ( sampling_params.repetition_penalty != 1.0 or sampling_params.frequency_penalty != 0.0 or sampling_params.presence_penalty != 0.0 )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/attn_utils.py
vllm/v1/worker/gpu/attn_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from typing import Any, cast import numpy as np import torch from vllm.attention.backends.abstract import AttentionBackend from vllm.config import VllmConfig, get_layers_from_vllm_config from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase from vllm.v1.attention.backends.utils import ( AttentionMetadataBuilder, CommonAttentionMetadata, ) from vllm.v1.kv_cache_interface import ( AttentionSpec, KVCacheConfig, KVCacheSpec, ) from vllm.v1.worker.utils import bind_kv_cache def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]: kv_cache_spec: dict[str, KVCacheSpec] = {} layer_type = cast(type[Any], AttentionLayerBase) attn_layers = get_layers_from_vllm_config(vllm_config, layer_type) for layer_name, attn_module in attn_layers.items(): # Skip modules that don't need KV cache (eg encoder-only attention) if spec := attn_module.get_kv_cache_spec(vllm_config): kv_cache_spec[layer_name] = spec return kv_cache_spec def init_attn_backend( kv_cache_config: KVCacheConfig, vllm_config: VllmConfig, device: torch.device, ): attn_backends: dict[str, type[AttentionBackend]] = {} attn_metadata_builders: list[AttentionMetadataBuilder] = [] flashinfer_workspace: torch.Tensor | None = None for kv_cache_group_spec in kv_cache_config.kv_cache_groups: layer_names = kv_cache_group_spec.layer_names any_layer_name = next(iter(layer_names)) layer_type = cast(type[Any], AttentionLayerBase) attn_layers = get_layers_from_vllm_config(vllm_config, layer_type, layer_names) attn_backend = attn_layers[any_layer_name].get_attn_backend() for layer_name in layer_names: attn_backends[layer_name] = attn_backend attn_metadata_builder = attn_backend.get_builder_cls()( kv_cache_group_spec.kv_cache_spec, layer_names, vllm_config, device, ) attn_metadata_builders.append(attn_metadata_builder) # type: ignore if "FLASHINFER" in attn_backend.get_name(): if flashinfer_workspace is None: flashinfer_workspace = attn_metadata_builder._get_workspace_buffer() else: attn_metadata_builder.set_workspace_buffer(flashinfer_workspace) return attn_backends, attn_metadata_builders def _allocate_kv_cache( kv_cache_config: KVCacheConfig, device: torch.device, ): kv_cache_raw_tensors: dict[str, torch.Tensor] = {} for kv_cache_tensor in kv_cache_config.kv_cache_tensors: tensor = torch.zeros(kv_cache_tensor.size, dtype=torch.int8, device=device) for layer_name in kv_cache_tensor.shared_by: kv_cache_raw_tensors[layer_name] = tensor layer_names = set() for group in kv_cache_config.kv_cache_groups: for layer_name in group.layer_names: layer_names.add(layer_name) assert layer_names == set(kv_cache_raw_tensors.keys()), ( "Some layers are not correctly initialized" ) return kv_cache_raw_tensors def _reshape_kv_cache( kv_cache_config: KVCacheConfig, kv_cache_raw_tensors: dict[str, torch.Tensor], attn_backends: dict[str, AttentionBackend], ) -> dict[str, torch.Tensor]: kv_caches: dict[str, torch.Tensor] = {} for kv_cache_group_spec in kv_cache_config.kv_cache_groups: kv_cache_spec = kv_cache_group_spec.kv_cache_spec assert isinstance(kv_cache_spec, AttentionSpec) for layer_name in kv_cache_group_spec.layer_names: raw_tensor = kv_cache_raw_tensors[layer_name] assert raw_tensor.numel() % kv_cache_spec.page_size_bytes == 0 num_blocks = raw_tensor.numel() // kv_cache_spec.page_size_bytes attn_backend = attn_backends[layer_name] kv_cache_shape = attn_backend.get_kv_cache_shape( num_blocks, kv_cache_spec.block_size, kv_cache_spec.num_kv_heads, kv_cache_spec.head_size, ) # FIXME(woosuk): Add kv_cache_stride_order to all attention backends. try: kv_cache_stride_order = attn_backend.get_kv_cache_stride_order() assert len(kv_cache_stride_order) == len(kv_cache_shape) except (AttributeError, NotImplementedError): kv_cache_stride_order = tuple(range(len(kv_cache_shape))) kv_cache_shape = tuple(kv_cache_shape[i] for i in kv_cache_stride_order) inv_order = [ kv_cache_stride_order.index(i) for i in range(len(kv_cache_stride_order)) ] dtype = kv_cache_spec.dtype raw_tensor = raw_tensor.view(dtype) raw_tensor = raw_tensor.view(kv_cache_shape) kv_caches[layer_name] = raw_tensor.permute(*inv_order) return kv_caches def init_kv_cache( runner_kv_caches: list[torch.Tensor], forward_context: dict[str, Any], kv_cache_config: KVCacheConfig, attn_backends: dict[str, AttentionBackend], device: torch.device, ) -> None: kv_cache_raw_tensors = _allocate_kv_cache(kv_cache_config, device) kv_caches = _reshape_kv_cache(kv_cache_config, kv_cache_raw_tensors, attn_backends) bind_kv_cache(kv_caches, forward_context, runner_kv_caches) def build_attn_metadata( attn_metadata_builders: list[AttentionMetadataBuilder], num_reqs: int, num_tokens: int, query_start_loc_gpu: torch.Tensor, query_start_loc_cpu: torch.Tensor, seq_lens: torch.Tensor, seq_lens_np: np.ndarray, num_computed_tokens_cpu: torch.Tensor | None, block_tables: Sequence[torch.Tensor], slot_mappings: torch.Tensor, kv_cache_config: KVCacheConfig, ) -> dict[str, Any]: max_query_len = int(query_start_loc_cpu.max()) seq_lens = seq_lens[:num_reqs] seq_lens_cpu = torch.from_numpy(seq_lens_np) max_seq_len = int(seq_lens_np.max()) attn_metadata: dict[str, Any] = {} kv_cache_groups = kv_cache_config.kv_cache_groups for i, kv_cache_spec in enumerate(kv_cache_groups): block_table = block_tables[i] slot_mapping = slot_mappings[i] common_attn_metadata = CommonAttentionMetadata( query_start_loc=query_start_loc_gpu, query_start_loc_cpu=query_start_loc_cpu, seq_lens=seq_lens, _seq_lens_cpu=seq_lens_cpu, max_seq_len=max_seq_len, _num_computed_tokens_cpu=num_computed_tokens_cpu, num_reqs=num_reqs, num_actual_tokens=num_tokens, max_query_len=max_query_len, block_table_tensor=block_table, slot_mapping=slot_mapping, causal=True, ) attn_metadata_builder = attn_metadata_builders[i] metadata = attn_metadata_builder.build( common_prefix_len=0, common_attn_metadata=common_attn_metadata, ) for layer_name in kv_cache_spec.layer_names: attn_metadata[layer_name] = metadata return attn_metadata
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/cudagraph_utils.py
vllm/v1/worker/gpu/cudagraph_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Callable, Iterable from typing import Any import numpy as np import torch import torch.nn as nn from tqdm import tqdm from vllm.config import VllmConfig from vllm.config.compilation import CUDAGraphMode from vllm.distributed.parallel_state import graph_capture, is_global_first_rank from vllm.forward_context import set_forward_context from vllm.v1.attention.backends.utils import AttentionMetadataBuilder from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.attn_utils import build_attn_metadata from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1.worker.gpu.dp_utils import make_num_tokens_across_dp from vllm.v1.worker.gpu.input_batch import InputBuffers class CudaGraphManager: def __init__( self, vllm_config: VllmConfig, device: torch.device, ): self.vllm_config = vllm_config self.scheduler_config = vllm_config.scheduler_config self.device = device self.max_model_len = vllm_config.model_config.max_model_len self.max_num_reqs = self.scheduler_config.max_num_seqs self.max_num_tokens = self.scheduler_config.max_num_batched_tokens self.dp_size = vllm_config.parallel_config.data_parallel_size self.compilation_config = vllm_config.compilation_config assert self.compilation_config is not None self.cudagraph_mode: CUDAGraphMode if self.compilation_config.cudagraph_mode is None: self.cudagraph_mode = CUDAGraphMode.NONE else: self.cudagraph_mode = self.compilation_config.cudagraph_mode self.cudagraph_sizes = get_cudagraph_sizes( self.compilation_config.cudagraph_capture_sizes, self.max_num_reqs, self.max_num_tokens, self.cudagraph_mode, ) self.graphs: dict[int, torch.cuda.CUDAGraph] = {} self.pool = torch.cuda.graph_pool_handle() self.hidden_states: torch.Tensor | None = None def needs_capture(self) -> bool: return len(self.cudagraph_sizes) > 0 def get_cudagraph_size( self, scheduler_output: SchedulerOutput, num_tokens_after_padding: int, ) -> int | None: return get_cudagraph_size( num_tokens_after_padding, scheduler_output.num_scheduled_tokens.values(), self.cudagraph_sizes, self.cudagraph_mode, ) def capture_graph( self, num_tokens: int, model: nn.Module, input_buffers: InputBuffers, block_tables: BlockTables, attn_metadata_builders: list[AttentionMetadataBuilder], kv_cache_config: KVCacheConfig, ) -> None: num_reqs = min(num_tokens, self.max_num_reqs) input_ids = input_buffers.input_ids[:num_tokens] positions = input_buffers.positions[:num_tokens] attn_metadata = prepare_inputs_to_capture( num_reqs, num_tokens, input_buffers, block_tables, attn_metadata_builders, self.max_model_len, kv_cache_config, ) num_tokens_across_dp = make_num_tokens_across_dp(self.dp_size, num_tokens) # Warm up. with set_forward_context( attn_metadata, self.vllm_config, num_tokens=num_tokens, cudagraph_runtime_mode=CUDAGraphMode.NONE, num_tokens_across_dp=num_tokens_across_dp, ): hidden_states = model( input_ids=input_ids, positions=positions, ) if self.hidden_states is None: self.hidden_states = torch.empty_like(hidden_states) # Capture the graph. assert num_tokens not in self.graphs graph = torch.cuda.CUDAGraph() with ( set_forward_context( attn_metadata, self.vllm_config, num_tokens=num_tokens, cudagraph_runtime_mode=CUDAGraphMode.NONE, num_tokens_across_dp=num_tokens_across_dp, ), torch.cuda.graph(graph, self.pool), ): hidden_states = model( input_ids=input_ids, positions=positions, ) self.hidden_states[:num_tokens] = hidden_states self.graphs[num_tokens] = graph @torch.inference_mode() def capture( self, model: nn.Module, input_buffers: InputBuffers, block_tables: BlockTables, attn_metadata_builders: list[AttentionMetadataBuilder], kv_cache_config: KVCacheConfig, ) -> None: capture_graphs( self.cudagraph_sizes, self.device, self.capture_graph, model=model, input_buffers=input_buffers, block_tables=block_tables, attn_metadata_builders=attn_metadata_builders, kv_cache_config=kv_cache_config, ) def run(self, num_tokens: int) -> torch.Tensor: assert num_tokens in self.graphs self.graphs[num_tokens].replay() assert self.hidden_states is not None return self.hidden_states[:num_tokens] def get_cudagraph_sizes( capture_sizes: list[int] | None, max_num_reqs: int, max_num_tokens: int, cudagraph_mode: CUDAGraphMode, ) -> dict[int, int]: if not cudagraph_mode.has_full_cudagraphs(): return {} if not capture_sizes: return {} capture_sizes = sorted(capture_sizes) # Limit the capture sizes to the max number of requests or tokens. upper_bound = ( max_num_reqs if cudagraph_mode == CUDAGraphMode.FULL_DECODE_ONLY else max_num_tokens ) capture_sizes = [x for x in capture_sizes if x <= upper_bound] if not capture_sizes: return {} cudagraph_sizes: dict[int, int] = {} for i in range(1, capture_sizes[-1] + 1): for x in capture_sizes: if i <= x: cudagraph_sizes[i] = x break return cudagraph_sizes def get_cudagraph_size( num_tokens_after_dp_padding: int, num_tokens_per_request: Iterable[int], cudagraph_sizes: dict[int, int], cudagraph_mode: CUDAGraphMode, ) -> int | None: size = cudagraph_sizes.get(num_tokens_after_dp_padding) if size is None: # No CUDA graph for this size. return None if cudagraph_mode == CUDAGraphMode.FULL_DECODE_ONLY: all_decode = all(x == 1 for x in num_tokens_per_request) if not all_decode: # Prefill is included. return None return size def capture_graphs( cudagraph_sizes: dict[int, int], device: torch.device, capture_fn: Callable, **capture_kwargs, ) -> None: # Capture larger graphs first. sizes_to_capture = sorted(set(cudagraph_sizes.values()), reverse=True) if is_global_first_rank(): sizes_to_capture = tqdm(sizes_to_capture, desc="Capturing CUDA graphs") with graph_capture(device=device): for size in sizes_to_capture: capture_fn(size, **capture_kwargs) def prepare_inputs_to_capture( num_reqs: int, num_tokens: int, input_buffers: InputBuffers, block_tables: BlockTables, attn_metadata_builders: list[AttentionMetadataBuilder], max_model_len: int, kv_cache_config: KVCacheConfig, ) -> dict[str, Any]: num_tokens_per_req = num_tokens // num_reqs query_start_loc = input_buffers.query_start_loc query_start_loc.np[: num_reqs + 1] = np.arange(num_reqs + 1) * num_tokens_per_req query_start_loc.np[num_reqs:] = num_tokens query_start_loc.copy_to_gpu() seq_lens_np = np.full(num_reqs, max_model_len, dtype=np.int32) # HACK(woosuk): For faster warmup, we set seq_lens (GPU) to num_tokens # rather than max_model_len. This introduces a discrepancy between # seq_lens (on GPU) and seq_lens_np (on CPU), which may cause issues for # certain attention backends. input_buffers.seq_lens[:num_reqs] = num_tokens input_buffers.seq_lens[num_reqs:] = 0 input_block_tables = [x[:num_reqs] for x in block_tables.input_block_tables] slot_mappings = block_tables.slot_mappings[:, :num_tokens] attn_metadata = build_attn_metadata( attn_metadata_builders=attn_metadata_builders, num_reqs=num_reqs, num_tokens=num_tokens, query_start_loc_gpu=query_start_loc.gpu[: num_reqs + 1], query_start_loc_cpu=query_start_loc.cpu[: num_reqs + 1], seq_lens=input_buffers.seq_lens, seq_lens_np=seq_lens_np, num_computed_tokens_cpu=None, # FIXME block_tables=input_block_tables, slot_mappings=slot_mappings, kv_cache_config=kv_cache_config, ) return attn_metadata
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/block_table.py
vllm/v1/worker/gpu/block_table.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Iterable import torch from vllm.attention.backends.utils import PAD_SLOT_ID from vllm.triton_utils import tl, triton from vllm.utils.math_utils import cdiv from vllm.v1.utils import CpuGpuBuffer class BlockTables: def __init__( self, block_sizes: list[int], max_num_reqs: int, max_num_batched_tokens: int, max_model_len: int, device: torch.device, pin_memory: bool, ): self.block_sizes = block_sizes self.max_num_reqs = max_num_reqs self.max_num_batched_tokens = max_num_batched_tokens self.max_model_len = max_model_len self.device = device self.pin_memory = pin_memory self.num_kv_cache_groups = len(self.block_sizes) # num_kv_cache_groups x [max_num_reqs, max_num_blocks] self.block_tables: list[torch.Tensor] = [] for i in range(self.num_kv_cache_groups): block_size = self.block_sizes[i] max_num_blocks = cdiv(self.max_model_len, block_size) block_table = torch.zeros( self.max_num_reqs, max_num_blocks, dtype=torch.int32, device=self.device, ) self.block_tables.append(block_table) self.block_table_ptrs = self._make_ptr_tensor(self.block_tables) # Block tables used for model's forward pass. # num_kv_cache_groups x [max_num_reqs, max_num_blocks] self.input_block_tables: list[torch.Tensor] = [ torch.zeros_like(block_table) for block_table in self.block_tables ] self.input_block_table_ptrs = self._make_ptr_tensor(self.input_block_tables) self.block_table_strides = torch.tensor( [b.stride(0) for b in self.block_tables], dtype=torch.int64, device=self.device, ) self.block_sizes_tensor = torch.tensor( self.block_sizes, dtype=torch.int32, device=self.device ) self.num_blocks = torch.zeros( self.num_kv_cache_groups, self.max_num_reqs, dtype=torch.int32, device=self.device, ) self.slot_mappings = torch.zeros( self.num_kv_cache_groups, self.max_num_batched_tokens, dtype=torch.int64, device=self.device, ) # Misc buffers. self.req_indices = self._make_buffer(self.max_num_reqs, dtype=torch.int32) self.overwrite = self._make_buffer(self.max_num_reqs, dtype=torch.bool) self.cu_num_new_blocks = self._make_buffer( self.num_kv_cache_groups, self.max_num_reqs + 1, dtype=torch.int32 ) def _make_buffer(self, *args, dtype: torch.dtype) -> CpuGpuBuffer: return CpuGpuBuffer( *args, dtype=dtype, pin_memory=self.pin_memory, device=self.device ) def _make_ptr_tensor(self, x: Iterable[torch.Tensor]) -> torch.Tensor: # NOTE(woosuk): Use uint64 instead of int64 to cover all possible addresses. ptrs_tensor_cpu = torch.tensor( [t.data_ptr() for t in x], dtype=torch.uint64, device="cpu", pin_memory=self.pin_memory, ) return ptrs_tensor_cpu.to(self.device, non_blocking=True) def append_block_ids( self, # [num_reqs] req_indices: list[int], # [num_kv_cache_groups, num_reqs + 1] cu_num_new_blocks: tuple[list[int], ...], # [num_kv_cache_groups, num_new_blocks] new_block_ids: tuple[list[int], ...], # [num_reqs] overwrite: list[bool], ) -> None: num_reqs = len(req_indices) self.req_indices.np[:num_reqs] = req_indices self.overwrite.np[:num_reqs] = overwrite for i in range(self.num_kv_cache_groups): self.cu_num_new_blocks.np[i, : num_reqs + 1] = cu_num_new_blocks[i] # NOTE(woosuk): Here, we cannot use a fixed-size buffer because there's # no clear upper bound to the number of new blocks in a single step. # NOTE(woosuk): The buffer has to be cached, because otherwise we cannot # guarantee that the buffer is not freed before the copy is completed. self.new_block_ids_cpu = torch.empty( self.num_kv_cache_groups, max(len(x) for x in new_block_ids), dtype=torch.int32, device="cpu", pin_memory=self.pin_memory, ) new_block_ids_np = self.new_block_ids_cpu.numpy() for i in range(self.num_kv_cache_groups): new_block_ids_np[i, : len(new_block_ids[i])] = new_block_ids[i] new_block_ids_gpu = self.new_block_ids_cpu.to(self.device, non_blocking=True) _append_block_ids_kernel[(self.num_kv_cache_groups, num_reqs)]( self.req_indices.copy_to_gpu(num_reqs), self.cu_num_new_blocks.copy_to_gpu(), self.cu_num_new_blocks.gpu.stride(0), new_block_ids_gpu, new_block_ids_gpu.stride(0), self.overwrite.copy_to_gpu(num_reqs), self.block_table_strides, self.block_table_ptrs, self.num_blocks, self.num_blocks.stride(0), BLOCK_SIZE=1024, # type: ignore ) def gather_block_tables( self, idx_mapping: torch.Tensor, ) -> tuple[torch.Tensor, ...]: num_reqs = idx_mapping.shape[0] _gather_block_tables_kernel[(self.num_kv_cache_groups, num_reqs)]( idx_mapping, self.block_table_ptrs, self.input_block_table_ptrs, self.block_table_strides, self.num_blocks, self.num_blocks.stride(0), BLOCK_SIZE=1024, # type: ignore ) return tuple(block_table[:num_reqs] for block_table in self.input_block_tables) def get_dummy_block_tables(self, num_reqs: int) -> tuple[torch.Tensor, ...]: return tuple(block_table[:num_reqs] for block_table in self.input_block_tables) def compute_slot_mappings( self, query_start_loc: torch.Tensor, positions: torch.Tensor, ) -> torch.Tensor: num_reqs = query_start_loc.shape[0] - 1 num_tokens = positions.shape[0] num_groups = self.num_kv_cache_groups _compute_slot_mappings_kernel[(num_groups, num_reqs + 1)]( num_tokens, self.max_num_batched_tokens, query_start_loc, positions, self.input_block_table_ptrs, self.block_table_strides, self.block_sizes_tensor, self.slot_mappings, self.slot_mappings.stride(0), PAD_ID=PAD_SLOT_ID, BLOCK_SIZE=1024, # type: ignore ) return self.slot_mappings[:, :num_tokens] def get_dummy_slot_mappings(self, num_tokens: int) -> torch.Tensor: self.slot_mappings.fill_(PAD_SLOT_ID) return self.slot_mappings[:, :num_tokens] @triton.jit def _append_block_ids_kernel( # Inputs req_indices, # [num_reqs] cu_num_new_blocks_ptr, # [num_kv_cache_groups, num_reqs + 1] cu_num_new_blocks_stride, new_block_ids_ptr, # [num_kv_cache_groups, num_new_blocks] new_block_ids_stride, overwrite, # [num_reqs] block_table_strides, # [num_kv_cache_groups] # Outputs block_table_ptrs, # [num_kv_cache_groups] num_blocks_ptr, # [num_kv_cache_groups, max_num_reqs] num_blocks_stride, # Constants BLOCK_SIZE: tl.constexpr, ): group_id = tl.program_id(0) batch_idx = tl.program_id(1) req_idx = tl.load(req_indices + batch_idx) do_overwrite = tl.load(overwrite + batch_idx) group_new_blocks_ptr = cu_num_new_blocks_ptr + group_id * cu_num_new_blocks_stride start_idx = tl.load(group_new_blocks_ptr + batch_idx) end_idx = tl.load(group_new_blocks_ptr + batch_idx + 1) num_new_blocks = end_idx - start_idx group_num_blocks_ptr = num_blocks_ptr + group_id * num_blocks_stride dst_start_idx = tl.load(group_num_blocks_ptr + req_idx) if not do_overwrite else 0 dst_end_idx = dst_start_idx + num_new_blocks tl.store(group_num_blocks_ptr + req_idx, dst_end_idx) # Destination block_table_ptr = _load_ptr(block_table_ptrs + group_id, tl.int32) block_table_stride = tl.load(block_table_strides + group_id) row_ptr = block_table_ptr + req_idx * block_table_stride group_new_block_ids_ptr = new_block_ids_ptr + group_id * new_block_ids_stride for i in range(0, num_new_blocks, BLOCK_SIZE): offset = i + tl.arange(0, BLOCK_SIZE) block_ids = tl.load( group_new_block_ids_ptr + start_idx + offset, mask=offset < num_new_blocks ) tl.store( row_ptr + dst_start_idx + offset, block_ids, mask=offset < num_new_blocks ) @triton.jit def _gather_block_tables_kernel( batch_idx_to_req_idx, # [batch_size] src_block_table_ptrs, # [num_kv_cache_groups] dst_block_table_ptrs, # [num_kv_cache_groups] block_table_strides, # [num_kv_cache_groups] num_blocks_ptr, # [num_kv_cache_groups, max_num_reqs] num_blocks_stride, BLOCK_SIZE: tl.constexpr, ): # kv cache group id group_id = tl.program_id(0) batch_idx = tl.program_id(1) req_idx = tl.load(batch_idx_to_req_idx + batch_idx) group_num_blocks_ptr = num_blocks_ptr + group_id * num_blocks_stride num_blocks = tl.load(group_num_blocks_ptr + req_idx) stride = tl.load(block_table_strides + group_id) src_block_table_ptr = _load_ptr(src_block_table_ptrs + group_id, tl.int32) src_row_ptr = src_block_table_ptr + req_idx * stride dst_block_table_ptr = _load_ptr(dst_block_table_ptrs + group_id, tl.int32) dst_row_ptr = dst_block_table_ptr + batch_idx * stride for i in tl.range(0, num_blocks, BLOCK_SIZE): offset = i + tl.arange(0, BLOCK_SIZE) block_ids = tl.load(src_row_ptr + offset, mask=offset < num_blocks) tl.store(dst_row_ptr + offset, block_ids, mask=offset < num_blocks) @triton.jit def _compute_slot_mappings_kernel( num_tokens, max_num_tokens, cu_num_tokens, # [num_reqs + 1] pos, # [num_tokens] block_table_ptrs, # [num_kv_cache_groups] block_table_strides, # [num_kv_cache_groups] page_sizes, # [num_kv_cache_groups] slot_mappings_ptr, # [num_kv_cache_groups, max_num_tokens] slot_mappings_stride, PAD_ID: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): # kv cache group id group_id = tl.program_id(0) req_idx = tl.program_id(1) slot_mapping_ptr = slot_mappings_ptr + group_id * slot_mappings_stride if req_idx == tl.num_programs(1) - 1: # Pad remaining slots to -1. This is needed for CUDA graphs. for i in range(num_tokens, max_num_tokens, BLOCK_SIZE): offset = i + tl.arange(0, BLOCK_SIZE) tl.store(slot_mapping_ptr + offset, PAD_ID, mask=offset < max_num_tokens) return block_table_ptr = _load_ptr(block_table_ptrs + group_id, tl.int32) block_table_stride = tl.load(block_table_strides + group_id) page_size = tl.load(page_sizes + group_id) start_idx = tl.load(cu_num_tokens + req_idx) end_idx = tl.load(cu_num_tokens + req_idx + 1) for i in range(start_idx, end_idx, BLOCK_SIZE): offset = i + tl.arange(0, BLOCK_SIZE) positions = tl.load(pos + offset, mask=offset < end_idx, other=0) block_indices = positions // page_size block_numbers = tl.load( block_table_ptr + req_idx * block_table_stride + block_indices ) slot_ids = block_numbers * page_size + positions % page_size tl.store(slot_mapping_ptr + offset, slot_ids, mask=offset < end_idx) @triton.jit def _load_ptr(ptr_to_ptr, elem_dtype): ptr = tl.load(ptr_to_ptr) ptr = tl.cast(ptr, tl.pointer_type(elem_dtype)) return tl.multiple_of(ptr, 16)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/structured_outputs.py
vllm/v1/worker/gpu/structured_outputs.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import numpy as np import torch from vllm.triton_utils import tl, triton from vllm.v1.worker.gpu.input_batch import InputBuffers def apply_grammar_bitmask( logits: torch.Tensor, req_ids: list[str], grammar_req_ids: list[str], grammar_bitmask: np.ndarray, input_buffers: InputBuffers, ) -> None: input_buffers.grammar_bitmask.np[: grammar_bitmask.shape[0]] = grammar_bitmask input_buffers.grammar_bitmask.copy_to_gpu(grammar_bitmask.shape[0]) batch_size = logits.shape[0] grammar_req_id_to_idx = {req_id: i for i, req_id in enumerate(grammar_req_ids)} # logits -> bitmask mapping mapping = [grammar_req_id_to_idx.get(req_id, -1) for req_id in req_ids] input_buffers.bitmask_indices.np[:batch_size] = mapping input_buffers.bitmask_indices.copy_to_gpu(batch_size) vocab_size = logits.shape[-1] BLOCK_SIZE = 8192 grid = (batch_size, triton.cdiv(vocab_size, BLOCK_SIZE)) _apply_grammar_bitmask_kernel[grid]( logits, logits.stride(0), input_buffers.grammar_bitmask.gpu, input_buffers.grammar_bitmask.gpu.stride(0), input_buffers.bitmask_indices.gpu, vocab_size, BLOCK_SIZE=BLOCK_SIZE, ) # Adapted from # https://github.com/mlc-ai/xgrammar/blob/main/python/xgrammar/kernels/apply_token_bitmask_inplace_triton.py @triton.jit def _apply_grammar_bitmask_kernel( logits_ptr, logits_stride, bitmask_ptr, bitmask_stride, bitmask_indices_ptr, vocab_size, BLOCK_SIZE: tl.constexpr, ): logits_idx = tl.program_id(0) bitmask_idx = tl.load(bitmask_indices_ptr + logits_idx) if bitmask_idx == -1: # No bitmask to apply. return # Load the bitmask. block_id = tl.program_id(1) bitmask_offset = (block_id * BLOCK_SIZE) // 32 + tl.arange(0, BLOCK_SIZE // 32) packed_bitmask = tl.load( bitmask_ptr + bitmask_idx * bitmask_stride + bitmask_offset, mask=bitmask_offset < bitmask_stride, ) # Unpack the bitmask. bitmask = ((packed_bitmask[:, None] >> (tl.arange(0, 32)[None, :])) & 1) == 0 bitmask = bitmask.reshape(BLOCK_SIZE) # Apply the bitmask to the logits. block_offset = block_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) tl.store( logits_ptr + logits_idx * logits_stride + block_offset, -float("inf"), mask=bitmask & (block_offset < vocab_size), )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/__init__.py
vllm/v1/worker/gpu/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/dp_utils.py
vllm/v1/worker/gpu/dp_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch import torch.distributed as dist from vllm.distributed.parallel_state import get_dp_group def get_batch_metadata_across_dp( num_tokens: int, cudagraph_size: int, dp_size: int, dp_rank: int, ) -> tuple[torch.Tensor, torch.Tensor]: assert dp_size > 1 # Use CPU group to avoid CPU-GPU synchronization. group = get_dp_group().cpu_group tensor = torch.zeros(2, dp_size, dtype=torch.int32, device="cpu") tensor[0][dp_rank] = num_tokens tensor[1][dp_rank] = cudagraph_size dist.all_reduce(tensor, group=group) return tensor[0], tensor[1] def make_num_tokens_across_dp( dp_size: int, num_tokens: int, ) -> torch.Tensor | None: if dp_size == 1: return None return torch.full((dp_size,), num_tokens, dtype=torch.int32, device="cpu")
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/metrics/logits.py
vllm/v1/worker/gpu/metrics/logits.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from torch._inductor.runtime.triton_helpers import libdevice from vllm.triton_utils import tl, triton @triton.jit def _num_nans_kernel( logits_ptr, logits_stride, num_nans_ptr, vocab_size, BLOCK_SIZE: tl.constexpr, ): req_idx = tl.program_id(0) num_nans = 0 for i in range(0, vocab_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < vocab_size logits = tl.load( logits_ptr + req_idx * logits_stride + block, mask=mask, other=0 ) logits = logits.to(tl.float32) is_nan = libdevice.isnan(logits).to(tl.int1) num_nans += tl.sum(is_nan).to(tl.int32) tl.store(num_nans_ptr + req_idx, num_nans) def get_num_nans(logits: torch.Tensor) -> torch.Tensor: num_reqs, vocab_size = logits.shape BLOCK_SIZE = 8192 num_nans = torch.empty(num_reqs, dtype=torch.int32, device=logits.device) _num_nans_kernel[(num_reqs,)]( logits, logits.stride(0), num_nans, vocab_size, BLOCK_SIZE=BLOCK_SIZE, ) return num_nans
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/metrics/__init__.py
vllm/v1/worker/gpu/metrics/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/spec_decode/eagle_cudagraph.py
vllm/v1/worker/gpu/spec_decode/eagle_cudagraph.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Callable import torch from vllm.config import VllmConfig from vllm.config.compilation import CUDAGraphMode from vllm.v1.attention.backends.utils import AttentionMetadataBuilder from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1.worker.gpu.cudagraph_utils import ( capture_graphs, get_cudagraph_sizes, prepare_inputs_to_capture, ) from vllm.v1.worker.gpu.dp_utils import make_num_tokens_across_dp from vllm.v1.worker.gpu.input_batch import InputBuffers class EagleCudaGraphManager: def __init__( self, vllm_config: VllmConfig, device: torch.device, ): self.vllm_config = vllm_config self.scheduler_config = vllm_config.scheduler_config self.device = device self.max_model_len = vllm_config.model_config.max_model_len self.max_num_reqs = self.scheduler_config.max_num_seqs self.max_num_tokens = self.scheduler_config.max_num_batched_tokens self.dp_size = vllm_config.parallel_config.data_parallel_size self.compilation_config = vllm_config.compilation_config assert self.compilation_config is not None cudagraph_mode: CUDAGraphMode if self.compilation_config.cudagraph_mode is None: cudagraph_mode = CUDAGraphMode.NONE else: cudagraph_mode = self.compilation_config.cudagraph_mode if cudagraph_mode == CUDAGraphMode.FULL: # NOTE(woosuk): For Eagle, we only use CUDA graphs for decode. cudagraph_mode = CUDAGraphMode.FULL_DECODE_ONLY self.cudagraph_mode = cudagraph_mode self.cudagraph_sizes = get_cudagraph_sizes( self.compilation_config.cudagraph_capture_sizes, self.max_num_reqs, self.max_num_tokens, self.cudagraph_mode, ) self.graphs: dict[int, torch.cuda.CUDAGraph] = {} self.pool = torch.cuda.graph_pool_handle() def get_cudagraph_size(self, num_tokens: int) -> int | None: return self.cudagraph_sizes.get(num_tokens) def capture_graph( self, num_tokens: int, generate_fn: Callable, input_buffers: InputBuffers, block_tables: BlockTables, attn_metadata_builders: list[AttentionMetadataBuilder], kv_cache_config: KVCacheConfig, ) -> None: num_reqs = min(num_tokens, self.max_num_reqs) attn_metadata = prepare_inputs_to_capture( num_reqs, num_tokens, input_buffers, block_tables, attn_metadata_builders, self.max_model_len, kv_cache_config, ) num_tokens_across_dp = make_num_tokens_across_dp(self.dp_size, num_tokens) # Warm up. generate_fn(num_tokens, attn_metadata, num_tokens_across_dp) # Capture the graph. assert num_tokens not in self.graphs graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph, self.pool): generate_fn(num_tokens, attn_metadata, num_tokens_across_dp) self.graphs[num_tokens] = graph @torch.inference_mode() def capture( self, generate_fn: Callable, input_buffers: InputBuffers, block_tables: BlockTables, attn_metadata_builders: list[AttentionMetadataBuilder], kv_cache_config: KVCacheConfig, ) -> None: capture_graphs( self.cudagraph_sizes, self.device, self.capture_graph, generate_fn=generate_fn, input_buffers=input_buffers, block_tables=block_tables, attn_metadata_builders=attn_metadata_builders, kv_cache_config=kv_cache_config, ) def run(self, num_tokens: int) -> None: assert num_tokens in self.graphs self.graphs[num_tokens].replay()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/spec_decode/eagle.py
vllm/v1/worker/gpu/spec_decode/eagle.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any import numpy as np import torch import torch.nn as nn from vllm.config import VllmConfig from vllm.config.compilation import CUDAGraphMode from vllm.forward_context import set_forward_context from vllm.logger import init_logger from vllm.model_executor.model_loader import get_model from vllm.triton_utils import tl, triton from vllm.utils.platform_utils import is_pin_memory_available from vllm.v1.attention.backends.utils import AttentionMetadataBuilder from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.attn_utils import build_attn_metadata from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample from vllm.v1.worker.gpu.sample.metadata import SamplingMetadata from vllm.v1.worker.gpu.spec_decode.eagle_cudagraph import EagleCudaGraphManager logger = init_logger(__name__) class EagleSpeculator: def __init__(self, vllm_config: VllmConfig, device: torch.device): self.vllm_config = vllm_config self.device = device self.speculative_config = vllm_config.speculative_config assert self.speculative_config is not None self.method = self.speculative_config.method self.num_speculative_steps = self.speculative_config.num_speculative_tokens self.draft_model_config = self.speculative_config.draft_model_config self.scheduler_config = vllm_config.scheduler_config self.max_num_reqs = self.scheduler_config.max_num_seqs self.max_num_tokens = self.scheduler_config.max_num_batched_tokens self.max_model_len = vllm_config.model_config.max_model_len # We need to get the hidden size from the draft model config because # the draft model's hidden size can be different from the target model's # hidden size (e.g., Llama 3.3 70B). self.hidden_size = self.draft_model_config.get_hidden_size() self.inputs_embeds_size = self.draft_model_config.get_inputs_embeds_size() self.vocab_size = self.draft_model_config.get_vocab_size() self.pin_memory = is_pin_memory_available() self.dtype = vllm_config.model_config.dtype self.input_buffers = InputBuffers( max_num_reqs=self.max_num_reqs, max_num_tokens=self.max_num_tokens, inputs_embeds_size=self.inputs_embeds_size, vocab_size=self.vocab_size, dtype=self.dtype, device=device, pin_memory=self.pin_memory, ) self.hidden_states = torch.zeros( self.max_num_tokens, self.hidden_size, dtype=self.dtype, device=device, ) self.temperature = torch.zeros( self.max_num_reqs, dtype=torch.float32, device=device, ) self.seeds = torch.zeros( self.max_num_reqs, dtype=torch.int64, device=device, ) self.draft_tokens = torch.zeros( self.max_num_reqs, self.num_speculative_steps, dtype=torch.int64, device=device, ) self.cudagraph_manager = EagleCudaGraphManager(vllm_config, device) def load_model(self, target_model: nn.Module) -> None: from vllm.compilation.backends import set_model_tag with set_model_tag("eagle_head"): self.model = get_model( vllm_config=self.vllm_config, model_config=self.draft_model_config ) share_lm_head = True if share_lm_head and hasattr(target_model, "lm_head"): if hasattr(self.model, "lm_head"): del self.model.lm_head self.model.lm_head = target_model.lm_head def set_attn( self, kv_cache_config: KVCacheConfig, attn_metadata_builders: list[AttentionMetadataBuilder], block_tables: BlockTables, ) -> None: self.kv_cache_config = kv_cache_config self.attn_metadata_builders = attn_metadata_builders self.block_tables = block_tables @torch.inference_mode() def run_model( self, num_tokens: int, attn_metadata: dict[str, Any], num_tokens_across_dp: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: with set_forward_context( attn_metadata, self.vllm_config, num_tokens=num_tokens, cudagraph_runtime_mode=CUDAGraphMode.NONE, num_tokens_across_dp=num_tokens_across_dp, ): ret_hidden_states = self.model( input_ids=self.input_buffers.input_ids[:num_tokens], positions=self.input_buffers.positions[:num_tokens], hidden_states=self.hidden_states[:num_tokens], ) if self.method == "mtp": last_hidden_states = ret_hidden_states hidden_states = ret_hidden_states else: last_hidden_states, hidden_states = ret_hidden_states return last_hidden_states, hidden_states def generate_draft( self, num_reqs: int, attn_metadata: dict[str, Any], num_tokens_across_dp: torch.Tensor | None, ) -> None: pos = self.input_buffers.positions[:num_reqs] query_start_loc = self.input_buffers.query_start_loc.gpu[: num_reqs + 1] for step in range(1, self.num_speculative_steps): # Run the eagle model. last_hidden_states, hidden_states = self.run_model( num_reqs, attn_metadata, num_tokens_across_dp ) logits = self.model.compute_logits(last_hidden_states) # NOTE(woosuk): We must add 1 to the positions to match the Gumbel noise # used for draft and target sampling. draft_tokens = gumbel_sample( logits, self.temperature[:num_reqs], self.seeds[:num_reqs], pos + 1, apply_temperature=True, ) self.draft_tokens[:num_reqs, step] = draft_tokens if step < self.num_speculative_steps - 1: # Update the inputs for the next step. update_eagle_inputs( draft_tokens, hidden_states, self.input_buffers, self.hidden_states, self.max_model_len, ) self.block_tables.compute_slot_mappings(query_start_loc, pos) def capture_model(self) -> None: if self.num_speculative_steps == 1: return logger.info("Capturing model for Eagle speculator...") self.cudagraph_manager.capture( self.generate_draft, self.input_buffers, self.block_tables, self.attn_metadata_builders, self.kv_cache_config, ) @torch.inference_mode() def propose( self, input_batch: InputBatch, sampling_metadata: SamplingMetadata, # [num_tokens, hidden_size] last_hidden_states: torch.Tensor, # num_layers x [num_tokens, hidden_size] aux_hidden_states: list[torch.Tensor] | None, # [num_reqs] num_sampled: torch.Tensor, # [num_reqs] num_rejected: torch.Tensor, # [num_reqs] last_sampled: torch.Tensor, # [num_reqs] next_prefill_tokens: torch.Tensor, ) -> torch.Tensor: # NOTE(woosuk): To avoid CPU-GPU synchronization without CPU knowing the # number of rejected tokens, we maintain the size of eagle's input_ids and # hidden_states the same as the target model's. This means, we pad each # request's query length to include any rejected positions. By doing so, # we can also reuse the attention metadata (e.g., query_start_loc, # seq_lens) of the target model. if aux_hidden_states: assert self.method == "eagle3" hidden_states = self.model.combine_hidden_states( torch.cat(aux_hidden_states, dim=-1) ) else: hidden_states = last_hidden_states num_tokens = input_batch.num_tokens_after_padding self.hidden_states[:num_tokens] = hidden_states # Get the input ids and last token indices for the speculator. last_token_indices = prepare_eagle_inputs( self.input_buffers, input_batch, num_sampled, num_rejected, last_sampled, next_prefill_tokens, ) # Prefill: Run the eagle speculator with eager mode. # TODO(woosuk): Support CUDA graph for prefill. last_hidden_states, hidden_states = self.run_model( num_tokens, input_batch.attn_metadata, num_tokens_across_dp=None, # FIXME ) sample_hidden_states = last_hidden_states[last_token_indices] logits = self.model.compute_logits(sample_hidden_states) num_reqs = input_batch.num_reqs cu_num_logits = input_batch.cu_num_logits[:num_reqs] # NOTE(woosuk): For draft sampling, we only consider the temperature # and ignore the other sampling parameters such as top_k and top_p, # for simplicity and performance. # While this may slightly degrade the acceptance rate, it does not # affect the output distribution after rejection sampling. temperature = self.temperature[:num_reqs] seeds = self.seeds[:num_reqs] pos = self.input_buffers.positions[:num_reqs] # Gather the values and copy them to the pre-allocated buffers. torch.gather(sampling_metadata.temperature, 0, cu_num_logits, out=temperature) torch.gather(sampling_metadata.seeds, 0, cu_num_logits, out=seeds) torch.gather(input_batch.positions, 0, last_token_indices, out=pos) # NOTE(woosuk): We must add 1 to the positions to match the Gumbel noise # used for draft and target sampling. draft_tokens = gumbel_sample( logits, temperature, seeds, pos + 1, apply_temperature=True ) if self.num_speculative_steps == 1: # Early exit. return draft_tokens.view(-1, 1) # Save the draft tokens for the first step. self.draft_tokens[:num_reqs, 0] = draft_tokens # Prepare the inputs for the decode steps. prepare_eagle_decode( draft_tokens, hidden_states, last_token_indices, input_batch.seq_lens, num_rejected, self.input_buffers, self.hidden_states, self.max_model_len, self.max_num_reqs, ) query_start_loc = self.input_buffers.query_start_loc query_start_loc_gpu = query_start_loc.gpu[: num_reqs + 1] slot_mappings = self.block_tables.compute_slot_mappings( query_start_loc_gpu, pos ) cudagraph_size = self.cudagraph_manager.get_cudagraph_size(num_reqs) if cudagraph_size is not None: # Run CUDA graph. self.cudagraph_manager.run(cudagraph_size) return self.draft_tokens[:num_reqs] # Run eager mode. query_start_loc.np[: num_reqs + 1] = np.arange(num_reqs + 1) query_start_loc_cpu = query_start_loc.cpu[: num_reqs + 1] # HACK(woosuk) seq_lens_np = np.full(num_reqs, self.max_model_len, dtype=np.int32) block_tables = [x[:num_reqs] for x in self.block_tables.input_block_tables] # FIXME(woosuk): This is UNSAFE!! attn_metadata = build_attn_metadata( attn_metadata_builders=self.attn_metadata_builders, num_reqs=num_reqs, num_tokens=num_reqs, query_start_loc_gpu=query_start_loc_gpu, query_start_loc_cpu=query_start_loc_cpu, seq_lens=self.input_buffers.seq_lens[:num_reqs], seq_lens_np=seq_lens_np, num_computed_tokens_cpu=None, # FIXME block_tables=block_tables, slot_mappings=slot_mappings, kv_cache_config=self.kv_cache_config, ) self.generate_draft(num_reqs, attn_metadata, num_tokens_across_dp=None) # FIXME return self.draft_tokens[:num_reqs] @triton.jit def _prepare_eagle_inputs_kernel( last_token_indices_ptr, eagle_input_ids_ptr, eagle_positions_ptr, target_input_ids_ptr, target_positions_ptr, last_sampled_ptr, next_prefill_tokens_ptr, num_sampled_ptr, num_rejected_ptr, query_start_loc_ptr, BLOCK_SIZE: tl.constexpr, ): batch_idx = tl.program_id(0) query_start = tl.load(query_start_loc_ptr + batch_idx) query_end = tl.load(query_start_loc_ptr + batch_idx + 1) query_len = query_end - query_start # Get the true query length and next token after accounting for rejected tokens. num_rejected = tl.load(num_rejected_ptr + batch_idx) query_len -= num_rejected num_sampled = tl.load(num_sampled_ptr + batch_idx) if num_sampled > 0: next_token = tl.load(last_sampled_ptr + batch_idx).to(tl.int32) else: # Chunked prefilling. # Get the next prefill token. next_token = tl.load(next_prefill_tokens_ptr + batch_idx) # Shift target_input_ids by one. for i in range(1, query_len, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < query_len input_ids = tl.load(target_input_ids_ptr + query_start + block, mask=mask) tl.store(eagle_input_ids_ptr + query_start + block - 1, input_ids, mask=mask) last_token_index = query_start + query_len - 1 tl.store(last_token_indices_ptr + batch_idx, last_token_index) tl.store(eagle_input_ids_ptr + last_token_index, next_token) # Copy positions. for i in range(0, query_len, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < query_len target_pos = tl.load(target_positions_ptr + query_start + block, mask=mask) tl.store(eagle_positions_ptr + query_start + block, target_pos, mask=mask) def prepare_eagle_inputs( input_buffers: InputBuffers, input_batch: InputBatch, # [num_reqs] num_sampled: torch.Tensor, # [num_reqs] num_rejected: torch.Tensor, # [num_reqs] last_sampled: torch.Tensor, # [num_reqs] next_prefill_tokens: torch.Tensor, ) -> torch.Tensor: num_reqs = input_batch.num_reqs last_token_indices = torch.empty( num_reqs, dtype=torch.int64, device=num_sampled.device, ) _prepare_eagle_inputs_kernel[(num_reqs,)]( last_token_indices, input_buffers.input_ids, input_buffers.positions, input_batch.input_ids, input_batch.positions, last_sampled, next_prefill_tokens, num_sampled, num_rejected, input_batch.query_start_loc, BLOCK_SIZE=1024, ) return last_token_indices @triton.jit def _prepare_eagle_docode_kernel( draft_tokens_ptr, output_hidden_states_ptr, output_hidden_states_stride, last_token_indices_ptr, target_seq_lens_ptr, num_rejected_ptr, input_ids_ptr, positions_ptr, input_hidden_states_ptr, input_hidden_states_stride, query_start_loc_ptr, seq_lens_ptr, hidden_size, max_model_len, max_num_reqs, BLOCK_SIZE: tl.constexpr, ): req_idx = tl.program_id(0) num_reqs = tl.num_programs(0) - 1 if req_idx == num_reqs: # Compute query_start_loc. Pad it with the last query_start_loc # for CUDA graphs. for i in range(0, max_num_reqs + 1, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) q = tl.where(block < num_reqs, block, num_reqs) mask = block < max_num_reqs + 1 tl.store(query_start_loc_ptr + block, q, mask=mask) # Pad seq_lens for CUDA graphs. for i in range(req_idx, max_num_reqs, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < max_num_reqs tl.store(seq_lens_ptr + block, 0, mask=mask) return # draft token -> input id. draft_token = tl.load(draft_tokens_ptr + req_idx) tl.store(input_ids_ptr + req_idx, draft_token) # output hidden states -> input hidden states. src_idx = tl.load(last_token_indices_ptr + req_idx) for i in range(0, hidden_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < hidden_size output_hidden_states = tl.load( output_hidden_states_ptr + src_idx * output_hidden_states_stride + block, mask=mask, ) tl.store( input_hidden_states_ptr + req_idx * input_hidden_states_stride + block, output_hidden_states, mask=mask, ) # Compute position and seq_lens. # NOTE(woosuk): To prevent out-of-range access, we clamp these values # if they reach the max model length. position = tl.load(positions_ptr + req_idx) position = tl.minimum(position + 1, max_model_len - 1) tl.store(positions_ptr + req_idx, position) target_seq_len = tl.load(target_seq_lens_ptr + req_idx) num_rejected = tl.load(num_rejected_ptr + req_idx) seq_len = target_seq_len - num_rejected seq_len = tl.minimum(seq_len + 1, max_model_len) tl.store(seq_lens_ptr + req_idx, seq_len) def prepare_eagle_decode( draft_tokens: torch.Tensor, output_hidden_states: torch.Tensor, last_token_indices: torch.Tensor, target_seq_lens: torch.Tensor, num_rejected: torch.Tensor, input_buffers: InputBuffers, input_hidden_states: torch.Tensor, max_model_len: int, max_num_reqs: int, ): num_reqs = draft_tokens.shape[0] hidden_size = output_hidden_states.shape[-1] _prepare_eagle_docode_kernel[(num_reqs + 1,)]( draft_tokens, output_hidden_states, output_hidden_states.stride(0), last_token_indices, target_seq_lens, num_rejected, input_buffers.input_ids, input_buffers.positions, input_hidden_states, input_hidden_states.stride(0), input_buffers.query_start_loc.gpu, input_buffers.seq_lens, hidden_size, max_model_len, max_num_reqs, BLOCK_SIZE=1024, ) @triton.jit def _update_eagle_inputs_kernel( input_ids_ptr, positions_ptr, input_hidden_states_ptr, input_hidden_states_stride, seq_lens_ptr, max_model_len, draft_tokens_ptr, output_hidden_states_ptr, output_hidden_states_stride, hidden_size, BLOCK_SIZE: tl.constexpr, ): req_idx = tl.program_id(0) # Draft token -> Input ID. draft_token = tl.load(draft_tokens_ptr + req_idx) tl.store(input_ids_ptr + req_idx, draft_token) # Output hidden states -> Input hidden states. for i in range(0, hidden_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < hidden_size output_hidden_states = tl.load( output_hidden_states_ptr + req_idx * output_hidden_states_stride + block, mask=mask, ) tl.store( input_hidden_states_ptr + req_idx * input_hidden_states_stride + block, output_hidden_states, mask=mask, ) # Increment position and seq_lens. # NOTE(woosuk): To prevent out-of-range access, we clamp these values # if they reach the max model length. position = tl.load(positions_ptr + req_idx) position = tl.minimum(position + 1, max_model_len - 1) tl.store(positions_ptr + req_idx, position) seq_len = tl.load(seq_lens_ptr + req_idx) seq_len = tl.minimum(seq_len + 1, max_model_len) tl.store(seq_lens_ptr + req_idx, seq_len) def update_eagle_inputs( draft_tokens: torch.Tensor, output_hidden_states: torch.Tensor, input_buffers: InputBuffers, hidden_states: torch.Tensor, max_model_len: int, ): num_reqs, hidden_size = output_hidden_states.shape _update_eagle_inputs_kernel[(num_reqs,)]( input_buffers.input_ids, input_buffers.positions, hidden_states, hidden_states.stride(0), input_buffers.seq_lens, max_model_len, draft_tokens, output_hidden_states, output_hidden_states.stride(0), hidden_size, BLOCK_SIZE=1024, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/spec_decode/__init__.py
vllm/v1/worker/gpu/spec_decode/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm.config import VllmConfig def init_speculator( vllm_config: VllmConfig, device: torch.device, ): speculative_config = vllm_config.speculative_config assert speculative_config is not None if speculative_config.use_eagle(): from vllm.v1.worker.gpu.spec_decode.eagle import EagleSpeculator return EagleSpeculator(vllm_config, device) raise NotImplementedError(f"{speculative_config.method} is not supported yet.")
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/spec_decode/rejection_sample.py
vllm/v1/worker/gpu/spec_decode/rejection_sample.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm.triton_utils import tl, triton @triton.jit def _rejection_sample_kernel( sampled_ptr, # [num_reqs, num_speculative_steps + 1] sampled_stride, num_sampled_ptr, # [num_reqs] target_sampled_ptr, # [num_draft_tokens + num_reqs] input_ids_ptr, # [num_draft_tokens + num_reqs] cu_num_logits_ptr, # [num_reqs + 1] ): req_idx = tl.program_id(0) start_idx = tl.load(cu_num_logits_ptr + req_idx) end_idx = tl.load(cu_num_logits_ptr + req_idx + 1) num_tokens = end_idx - start_idx num_sampled = 0 rejected = False for i in range(num_tokens - 1): if not rejected: target_sampled = tl.load(target_sampled_ptr + start_idx + i) draft_sampled = tl.load(input_ids_ptr + start_idx + i + 1) tl.store(sampled_ptr + req_idx * sampled_stride + i, target_sampled) num_sampled += 1 if target_sampled != draft_sampled: rejected = True if not rejected: target_sampled = tl.load(target_sampled_ptr + start_idx + num_tokens - 1) tl.store( sampled_ptr + req_idx * sampled_stride + num_tokens - 1, target_sampled ) num_sampled += 1 tl.store(num_sampled_ptr + req_idx, num_sampled) def rejection_sample( # [num_draft_tokens + num_reqs] target_sampled: torch.Tensor, # [num_draft_tokens + num_reqs] input_ids: torch.Tensor, # [num_reqs + 1] cu_num_logits: torch.Tensor, num_speculative_steps: int, ) -> tuple[torch.Tensor, torch.Tensor]: num_reqs = cu_num_logits.shape[0] - 1 sampled = torch.empty( num_reqs, num_speculative_steps + 1, dtype=target_sampled.dtype, device=target_sampled.device, ) num_sampled = torch.empty( num_reqs, dtype=torch.int32, device=target_sampled.device, ) _rejection_sample_kernel[(num_reqs,)]( sampled, sampled.stride(0), num_sampled, target_sampled, input_ids, cu_num_logits, num_warps=1, ) return sampled, num_sampled
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/sampler.py
vllm/v1/worker/gpu/sample/sampler.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch import vllm.envs as envs from vllm.config.model import LogprobsMode from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p from vllm.v1.worker.gpu.metrics.logits import get_num_nans from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample from vllm.v1.worker.gpu.sample.logprob import compute_topk_logprobs from vllm.v1.worker.gpu.sample.metadata import SamplingMetadata from vllm.v1.worker.gpu.sample.min_p import apply_min_p from vllm.v1.worker.gpu.sample.output import SamplerOutput from vllm.v1.worker.gpu.sample.penalties import apply_penalties_and_temperature class Sampler: def __init__( self, logprobs_mode: LogprobsMode = "raw_logprobs", ): if logprobs_mode not in ["processed_logprobs", "raw_logprobs"]: raise NotImplementedError(f"Unsupported logprobs_mode: {logprobs_mode}") self.logprobs_mode = logprobs_mode self.compute_nans = envs.VLLM_COMPUTE_NANS_IN_LOGITS # False by default. def __call__( self, logits: torch.Tensor, sampling_metadata: SamplingMetadata, ) -> SamplerOutput: # NOTE(woosuk): We intentionally compute num_nans before sampling to make clear # that num_nans is computed before applying penalties and temperature. num_nans = get_num_nans(logits) if self.compute_nans else None sampled, processed_logits = self.sample(logits, sampling_metadata) if sampling_metadata.max_num_logprobs is not None: logits = ( processed_logits if self.logprobs_mode == "processed_logprobs" else logits ) logprobs_tensors = compute_topk_logprobs( logits, sampling_metadata.max_num_logprobs, sampled, ) else: logprobs_tensors = None # These are GPU tensors. sampler_output = SamplerOutput( # The sampled tokens are expanded to 2D tensor with shape # [num_requests, 1], where each row represents one generated # token per request. sampled_token_ids=sampled.view(-1, 1), logprobs_tensors=logprobs_tensors, num_nans=num_nans, ) return sampler_output def sample( self, logits: torch.Tensor, sampling_metadata: SamplingMetadata, ) -> tuple[torch.Tensor, torch.Tensor]: # Copy logits to a new FP32 tensor. logits = torch.empty_like(logits, dtype=torch.float32).copy_(logits) # Apply penalties and temperature in place. apply_penalties_and_temperature(logits, sampling_metadata) # Apply min_p in place. if sampling_metadata.min_p is not None: apply_min_p(logits, sampling_metadata.min_p) # Apply top_k and/or top_p. This might return a new tensor. logits = apply_top_k_top_p( logits, sampling_metadata.top_k, sampling_metadata.top_p ) sampled = gumbel_sample( logits, sampling_metadata.temperature, sampling_metadata.seeds, sampling_metadata.pos, apply_temperature=False, ) return sampled, logits
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/output.py
vllm/v1/worker/gpu/sample/output.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass import torch from vllm.v1.outputs import LogprobsTensors @dataclass class SamplerOutput: sampled_token_ids: torch.Tensor logprobs_tensors: LogprobsTensors | None num_nans: torch.Tensor | None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/gumbel.py
vllm/v1/worker/gpu/sample/gumbel.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm.triton_utils import tl, triton @triton.jit def _gumbel_sample_kernel( local_argmax_ptr, local_argmax_stride, local_max_ptr, local_max_stride, logits_ptr, logits_stride, seeds_ptr, pos_ptr, temp_ptr, vocab_size, BLOCK_SIZE: tl.constexpr, APPLY_TEMPERATURE: tl.constexpr, ): req_idx = tl.program_id(0) block_idx = tl.program_id(1) block = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = block < vocab_size logits = tl.load( logits_ptr + req_idx * logits_stride + block, mask=mask, other=float("-inf"), ) logits = logits.to(tl.float32) temp = tl.load(temp_ptr + req_idx).to(tl.float32) if temp != 0.0: # Calculate the seed for gumbel noise. seed = tl.load(seeds_ptr + req_idx) pos = tl.load(pos_ptr + req_idx) gumbel_seed = tl.randint(seed, pos) # Generate gumbel noise. r = tl.rand(gumbel_seed, block).to(tl.float64) gumbel_noise = -tl.log(-tl.log(r + 1e-20) + 1e-20) gumbel_noise = gumbel_noise.to(tl.float32) # Apply temperature. if APPLY_TEMPERATURE: # NOTE(woosuk): Match the behavior of _penalties_and_temperature_kernel. # E.g., if the kernel uses tl.div_rn, we should use tl.div_rn here too. logits = logits / temp # Apply gumbel noise. logits = tl.where(mask, logits + gumbel_noise, float("-inf")) idx = tl.argmax(logits, axis=0) token_id = block_idx * BLOCK_SIZE + idx value = tl.max(logits, axis=0) tl.store(local_argmax_ptr + req_idx * local_argmax_stride + block_idx, token_id) tl.store(local_max_ptr + req_idx * local_max_stride + block_idx, value) def gumbel_sample( logits: torch.Tensor, # [num_reqs, vocab_size] temperature: torch.Tensor, # [num_reqs] seed: torch.Tensor, # [num_reqs] pos: torch.Tensor, # [num_reqs] apply_temperature: bool, ) -> torch.Tensor: num_reqs, vocab_size = logits.shape BLOCK_SIZE = 1024 num_blocks = triton.cdiv(vocab_size, BLOCK_SIZE) local_argmax = torch.empty( num_reqs, num_blocks, dtype=torch.int64, device=logits.device, ) local_max = torch.empty( num_reqs, num_blocks, dtype=torch.float32, device=logits.device, ) _gumbel_sample_kernel[(num_reqs, num_blocks)]( local_argmax, local_argmax.stride(0), local_max, local_max.stride(0), logits, logits.stride(0), seed, pos, temperature, vocab_size, BLOCK_SIZE=BLOCK_SIZE, APPLY_TEMPERATURE=apply_temperature, ) # NOTE(woosuk): Use int64 for later indexing. max_block_idx = local_max.argmax(dim=-1, keepdim=True) sampled = local_argmax.gather(dim=-1, index=max_block_idx).view(-1) return sampled
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/penalties.py
vllm/v1/worker/gpu/sample/penalties.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm.triton_utils import tl, triton from vllm.v1.worker.gpu.sample.metadata import SamplingMetadata @triton.jit def _penalties_and_temperature_kernel( logits_ptr, logits_stride, repetition_penalty_ptr, frequency_penalty_ptr, presence_penalty_ptr, temperature_ptr, idx_mapping_ptr, prompt_bin_mask_ptr, prompt_bin_mask_stride, output_bin_counts_ptr, output_bin_counts_stride, vocab_size, BLOCK_SIZE: tl.constexpr, ): batch_idx = tl.program_id(0) rep_penalty = tl.load(repetition_penalty_ptr + batch_idx) freq_penalty = tl.load(frequency_penalty_ptr + batch_idx) pres_penalty = tl.load(presence_penalty_ptr + batch_idx) temperature = tl.load(temperature_ptr + batch_idx) temperature = tl.where(temperature == 0.0, 1.0, temperature) use_rep_penalty = rep_penalty != 1.0 use_freq_penalty = freq_penalty != 0.0 use_pres_penalty = pres_penalty != 0.0 use_penalty = use_rep_penalty or use_freq_penalty or use_pres_penalty use_temperature = temperature != 1.0 if not (use_penalty or use_temperature): # Early return to avoid loading logits. return block_idx = tl.program_id(1) block = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = block < vocab_size logits = tl.load(logits_ptr + batch_idx * logits_stride + block, mask=mask) logits = logits.to(tl.float32) if use_penalty: req_state_idx = tl.load(idx_mapping_ptr + batch_idx) output_bin_counts = tl.load( output_bin_counts_ptr + req_state_idx * output_bin_counts_stride + block, mask=mask, ) output_bin_mask = output_bin_counts > 0 # Apply repetition penalties. if use_rep_penalty: packed_block = block_idx * BLOCK_SIZE // 32 + tl.arange(0, BLOCK_SIZE // 32) packed_mask = tl.load( prompt_bin_mask_ptr + req_state_idx * prompt_bin_mask_stride + packed_block, mask=packed_block < tl.cdiv(vocab_size, 32), ) prompt_bin_mask = (packed_mask[:, None] >> (tl.arange(0, 32)[None, :])) & 1 prompt_bin_mask = prompt_bin_mask.to(tl.int1) prompt_bin_mask = prompt_bin_mask.reshape(BLOCK_SIZE) # If token appears in prompt or output, apply, otherwise use 1.0 for no-op. scale = tl.where(prompt_bin_mask | output_bin_mask, rep_penalty, 1.0) # If logits are positive, divide by penalty, otherwise multiply by penalty. logits *= tl.where(logits > 0, 1.0 / scale, scale) # Apply frequency penalties. logits -= freq_penalty * output_bin_counts # Apply presence penalties. logits -= pres_penalty * output_bin_mask # Apply temperature. logits = logits / temperature # Store back to logits. tl.store(logits_ptr + batch_idx * logits_stride + block, logits, mask=mask) def apply_penalties_and_temperature( logits: torch.Tensor, sampling_metadata: SamplingMetadata, ) -> None: num_reqs, vocab_size = logits.shape BLOCK_SIZE = 8192 num_blocks = triton.cdiv(vocab_size, BLOCK_SIZE) _penalties_and_temperature_kernel[(num_reqs, num_blocks)]( logits, logits.stride(0), sampling_metadata.repetition_penalty, sampling_metadata.frequency_penalty, sampling_metadata.presence_penalty, sampling_metadata.temperature, sampling_metadata.idx_mapping, sampling_metadata.prompt_bin_mask, sampling_metadata.prompt_bin_mask.stride(0), sampling_metadata.output_bin_counts, sampling_metadata.output_bin_counts.stride(0), vocab_size, BLOCK_SIZE=BLOCK_SIZE, ) @triton.jit(do_not_specialize=["prefill_len", "prompt_len"]) def _bincount_kernel( prefill_token_ids_ptr, prefill_len, prompt_len, prompt_bin_mask_ptr, output_bin_counts_ptr, BLOCK_SIZE: tl.constexpr, ): block_idx = tl.program_id(0) if block_idx * BLOCK_SIZE >= prefill_len: return block = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) if block_idx * BLOCK_SIZE < prompt_len: mask = block < prompt_len prefill_tokens = tl.load(prefill_token_ids_ptr + block, mask=mask) idx = prefill_tokens // 32 bit_idx = prefill_tokens % 32 bit = tl.full((BLOCK_SIZE,), 1, tl.int32) << bit_idx tl.atomic_or(prompt_bin_mask_ptr + idx, bit, mask=mask) if (block_idx + 1) * BLOCK_SIZE >= prompt_len: mask = block < prefill_len mask &= block >= prompt_len prefill_tokens = tl.load(prefill_token_ids_ptr + block, mask=mask) tl.atomic_add(output_bin_counts_ptr + prefill_tokens, 1, mask=mask) def bincount( prefill_token_ids: torch.Tensor, prefill_len: int, prompt_len: int, prompt_bin_mask: torch.Tensor, output_bin_counts: torch.Tensor, ) -> None: prompt_bin_mask.zero_() output_bin_counts.zero_() BLOCK_SIZE = 1024 num_blocks = triton.cdiv(prefill_len, BLOCK_SIZE) _bincount_kernel[(num_blocks,)]( prefill_token_ids, prefill_len, prompt_len, prompt_bin_mask, output_bin_counts, BLOCK_SIZE=BLOCK_SIZE, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/metadata.py
vllm/v1/worker/gpu/sample/metadata.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass import torch from vllm.triton_utils import tl, triton @dataclass class SamplingMetadata: temperature: torch.Tensor top_p: torch.Tensor | None top_k: torch.Tensor | None min_p: torch.Tensor | None repetition_penalty: torch.Tensor frequency_penalty: torch.Tensor presence_penalty: torch.Tensor seeds: torch.Tensor pos: torch.Tensor # None means no logprobs, 0 means sampled token logprobs only max_num_logprobs: int | None # For penalties idx_mapping: torch.Tensor prompt_bin_mask: torch.Tensor output_bin_counts: torch.Tensor @classmethod def make_dummy( cls, num_reqs: int, device: torch.device, ) -> "SamplingMetadata": assert num_reqs > 0 temperature = torch.zeros(num_reqs, dtype=torch.float32, device=device) temperature[0] = 0.5 # TODO(woosuk): Use top-p and top-k for dummy sampler. # Currently, they are disabled because of memory usage. # top_p = torch.full((num_reqs,), 0.95, dtype=torch.float32, device=device) # top_k = torch.full((num_reqs,), 20, dtype=torch.int32, device=device) top_p = None top_k = None min_p = torch.zeros(num_reqs, dtype=torch.float32, device=device) # NOTE(woosuk): We must set penalties to their default values to make sure # the penalties kernel does not touch the placeholder bin_counts tensors. repetition_penalty = torch.ones(num_reqs, dtype=torch.float32, device=device) frequency_penalty = torch.zeros(num_reqs, dtype=torch.float32, device=device) presence_penalty = torch.zeros(num_reqs, dtype=torch.float32, device=device) seeds = torch.zeros(num_reqs, dtype=torch.int64, device=device) pos = torch.zeros(num_reqs, dtype=torch.int64, device=device) max_num_logprobs = 20 idx_mapping = torch.arange(num_reqs, dtype=torch.int32, device=device) # NOTE(woosuk): These are placeholder tensors to avoid None checks in the # penalties kernel. We use 2 instead of 1 as vocab_size to avoid Triton # specialization and re-compilation at runtime. prompt_bin_mask = torch.zeros(num_reqs, 2, dtype=torch.int32, device=device) output_bin_counts = torch.zeros(num_reqs, 2, dtype=torch.int32, device=device) return cls( temperature=temperature, top_p=top_p, top_k=top_k, min_p=min_p, repetition_penalty=repetition_penalty, frequency_penalty=frequency_penalty, presence_penalty=presence_penalty, seeds=seeds, pos=pos, max_num_logprobs=max_num_logprobs, idx_mapping=idx_mapping, prompt_bin_mask=prompt_bin_mask, output_bin_counts=output_bin_counts, ) # NOTE(woosuk): Re-compilation can happen at runtime since top_p and top_k can be None. @triton.jit def _expand_sampling_metadata_kernel( temp_ptr, expanded_temp_ptr, top_p_ptr, expanded_top_p_ptr, top_k_ptr, expanded_top_k_ptr, min_p_ptr, expanded_min_p_ptr, rep_penalty_ptr, expanded_rep_penalty_ptr, freq_penalty_ptr, expanded_freq_penalty_ptr, pres_penalty_ptr, expanded_pres_penalty_ptr, seeds_ptr, expanded_seeds_ptr, cu_num_logits_ptr, BLOCK_SIZE: tl.constexpr, ): req_idx = tl.program_id(0) start_idx = tl.load(cu_num_logits_ptr + req_idx) end_idx = tl.load(cu_num_logits_ptr + req_idx + 1) num_tokens = end_idx - start_idx block = tl.arange(0, BLOCK_SIZE) mask = block < num_tokens temp = tl.load(temp_ptr + req_idx) tl.store(expanded_temp_ptr + start_idx + block, temp, mask=mask) if top_p_ptr is not None: top_p = tl.load(top_p_ptr + req_idx) tl.store(expanded_top_p_ptr + start_idx + block, top_p, mask=mask) if top_k_ptr is not None: top_k = tl.load(top_k_ptr + req_idx) tl.store(expanded_top_k_ptr + start_idx + block, top_k, mask=mask) if min_p_ptr is not None: min_p = tl.load(min_p_ptr + req_idx) tl.store(expanded_min_p_ptr + start_idx + block, min_p, mask=mask) rep_penalty = tl.load(rep_penalty_ptr + req_idx) tl.store(expanded_rep_penalty_ptr + start_idx + block, rep_penalty, mask=mask) freq_penalty = tl.load(freq_penalty_ptr + req_idx) tl.store(expanded_freq_penalty_ptr + start_idx + block, freq_penalty, mask=mask) pres_penalty = tl.load(pres_penalty_ptr + req_idx) tl.store(expanded_pres_penalty_ptr + start_idx + block, pres_penalty, mask=mask) seed = tl.load(seeds_ptr + req_idx) tl.store(expanded_seeds_ptr + start_idx + block, seed, mask=mask) def expand_sampling_metadata( sampling_metadata: SamplingMetadata, cu_num_logits: torch.Tensor, max_expand_len: int, ) -> SamplingMetadata: total_num_logits = sampling_metadata.pos.shape[0] create_empty = lambda x: x.new_empty(total_num_logits) if x is not None else None expanded_temp = create_empty(sampling_metadata.temperature) expanded_top_p = create_empty(sampling_metadata.top_p) expanded_top_k = create_empty(sampling_metadata.top_k) expanded_min_p = create_empty(sampling_metadata.min_p) expanded_repetition_penalty = create_empty(sampling_metadata.repetition_penalty) expanded_frequency_penalty = create_empty(sampling_metadata.frequency_penalty) expanded_presence_penalty = create_empty(sampling_metadata.presence_penalty) expanded_seeds = create_empty(sampling_metadata.seeds) num_reqs = cu_num_logits.shape[0] - 1 _expand_sampling_metadata_kernel[(num_reqs,)]( sampling_metadata.temperature, expanded_temp, sampling_metadata.top_p, expanded_top_p, sampling_metadata.top_k, expanded_top_k, sampling_metadata.min_p, expanded_min_p, sampling_metadata.repetition_penalty, expanded_repetition_penalty, sampling_metadata.frequency_penalty, expanded_frequency_penalty, sampling_metadata.presence_penalty, expanded_presence_penalty, sampling_metadata.seeds, expanded_seeds, cu_num_logits, BLOCK_SIZE=triton.next_power_of_2(max_expand_len), ) return SamplingMetadata( temperature=expanded_temp, top_p=expanded_top_p, top_k=expanded_top_k, min_p=expanded_min_p, seeds=expanded_seeds, repetition_penalty=expanded_repetition_penalty, frequency_penalty=expanded_frequency_penalty, presence_penalty=expanded_presence_penalty, pos=sampling_metadata.pos, max_num_logprobs=sampling_metadata.max_num_logprobs, # TODO(woosuk): Support penalties with spec decoding. idx_mapping=sampling_metadata.idx_mapping, prompt_bin_mask=sampling_metadata.prompt_bin_mask, output_bin_counts=sampling_metadata.output_bin_counts, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/__init__.py
vllm/v1/worker/gpu/sample/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/logprob.py
vllm/v1/worker/gpu/sample/logprob.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Callable import torch from vllm.triton_utils import tl, triton from vllm.v1.outputs import LogprobsTensors @triton.jit def _topk_log_softmax_kernel( output_ptr, logits_ptr, logits_stride, topk_ids_ptr, topk, vocab_size, BLOCK_SIZE: tl.constexpr, PADDED_TOPK: tl.constexpr, ): req_idx = tl.program_id(0) row_ptr = logits_ptr + req_idx * logits_stride max_val = float("-inf") for i in range(0, vocab_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) logits = tl.load(row_ptr + block, mask=block < vocab_size, other=float("-inf")) max_val = tl.max(tl.maximum(logits, max_val)) max_val = max_val.to(tl.float32) # type: ignore se = 0.0 for i in range(0, vocab_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) logits = tl.load(row_ptr + block, mask=block < vocab_size, other=0.0) # NOTE(woosuk): Make sure that logits and all following operations use FP32. logits = logits.to(tl.float32) e = tl.exp(logits - max_val) e = tl.where(block < vocab_size, e, 0.0) se += tl.sum(e) lse = tl.log(se) k_offset = tl.arange(0, PADDED_TOPK) k_mask = k_offset < topk topk_ids = tl.load(topk_ids_ptr + req_idx * topk + k_offset, mask=k_mask, other=0) logits = tl.load(row_ptr + topk_ids, mask=k_mask) logits = logits.to(tl.float32) o = logits - max_val - lse tl.store(output_ptr + req_idx * topk + k_offset, o, mask=k_mask) @triton.jit def _ranks_kernel( output_ptr, logits_ptr, logits_stride, token_ids_ptr, vocab_size, BLOCK_SIZE: tl.constexpr, ): req_idx = tl.program_id(0) row_ptr = logits_ptr + req_idx * logits_stride token_id = tl.load(token_ids_ptr + req_idx) x = tl.load(row_ptr + token_id) n = 0 for i in range(0, vocab_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) logits = tl.load(row_ptr + block, mask=block < vocab_size, other=float("-inf")) n += tl.sum((logits > x).to(tl.int32)) tl.store(output_ptr + req_idx, n) def compute_token_logprobs( logits: torch.Tensor, token_ids: torch.Tensor, ) -> torch.Tensor: batch_size = logits.shape[0] vocab_size = logits.shape[1] token_ids = token_ids.to(torch.int64) num_logprobs = token_ids.shape[1] logprobs = torch.empty( batch_size, num_logprobs, dtype=torch.float32, device=logits.device, ) _topk_log_softmax_kernel[(batch_size,)]( logprobs, logits, logits.stride(0), token_ids, num_logprobs, vocab_size, BLOCK_SIZE=1024, # type: ignore PADDED_TOPK=triton.next_power_of_2(num_logprobs), ) return logprobs def compute_topk_logprobs( logits: torch.Tensor, num_logprobs: int, sampled_token_ids: torch.Tensor, ) -> LogprobsTensors: assert num_logprobs >= 0 batch_size, vocab_size = logits.shape if num_logprobs == 0: logprob_token_ids = sampled_token_ids.unsqueeze(-1) else: topk_indices = torch.topk(logits, num_logprobs, dim=-1).indices logprob_token_ids = torch.cat( (sampled_token_ids.unsqueeze(-1), topk_indices), dim=1 ) # NOTE(woosuk): Here, to save GPU memory, we do not materialize the full # logprobs tensor. Instead, we only compute and return the logprobs of # the topk + 1 tokens. logprobs = compute_token_logprobs(logits, logprob_token_ids) token_ranks = torch.empty( batch_size, dtype=torch.int64, device=logits.device, ) _ranks_kernel[(batch_size,)]( token_ranks, logits, logits.stride(0), sampled_token_ids, vocab_size, BLOCK_SIZE=8192, # type: ignore ) return LogprobsTensors( logprob_token_ids=logprob_token_ids, logprobs=logprobs, selected_token_ranks=token_ranks, ) def compute_prompt_logprobs( prompt_token_ids: torch.Tensor, prompt_hidden_states: torch.Tensor, logits_fn: Callable[[torch.Tensor], torch.Tensor], ) -> tuple[torch.Tensor, torch.Tensor]: # Since materializing the full prompt logits can take too much memory, # we compute it in chunks. CHUNK_SIZE = 1024 logprobs = [] ranks = [] prompt_token_ids = prompt_token_ids.to(torch.int64) for start_idx in range(0, prompt_token_ids.shape[0], CHUNK_SIZE): end_idx = start_idx + CHUNK_SIZE # NOTE(woosuk): logits_fn can be slow because it involves all-gather. prompt_logits = logits_fn(prompt_hidden_states[start_idx:end_idx]) prompt_logprobs = compute_topk_logprobs( prompt_logits, 0, # num_logprobs prompt_token_ids[start_idx:end_idx], ) logprobs.append(prompt_logprobs.logprobs) ranks.append(prompt_logprobs.selected_token_ranks) logprobs = torch.cat(logprobs, dim=0) if len(logprobs) > 1 else logprobs[0] ranks = torch.cat(ranks, dim=0) if len(ranks) > 1 else ranks[0] return logprobs, ranks
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/v1/worker/gpu/sample/min_p.py
vllm/v1/worker/gpu/sample/min_p.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from vllm.triton_utils import tl, triton @triton.jit def _min_p_kernel( logits_ptr, logits_stride, min_p_ptr, vocab_size, BLOCK_SIZE: tl.constexpr, ): req_idx = tl.program_id(0) min_p = tl.load(min_p_ptr + req_idx).to(tl.float32) if min_p == 0.0: return max_val = float("-inf") for i in range(0, vocab_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < vocab_size logits = tl.load( logits_ptr + req_idx * logits_stride + block, mask=mask, other=float("-inf") ) max_val = tl.max(tl.maximum(logits, max_val)) max_val = max_val.to(tl.float32) # type: ignore threshold = max_val + tl.log(min_p) for i in range(0, vocab_size, BLOCK_SIZE): block = i + tl.arange(0, BLOCK_SIZE) mask = block < vocab_size logits = tl.load( logits_ptr + req_idx * logits_stride + block, mask=mask, other=float("-inf") ) logits = tl.where(logits < threshold, float("-inf"), logits) tl.store(logits_ptr + req_idx * logits_stride + block, logits, mask=mask) def apply_min_p(logits: torch.Tensor, min_p: torch.Tensor) -> None: num_reqs, vocab_size = logits.shape BLOCK_SIZE = 1024 _min_p_kernel[(num_reqs,)]( logits, logits.stride(0), min_p, vocab_size, BLOCK_SIZE=BLOCK_SIZE, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false