Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvicorn/protocols/http/auto.py +15 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvloop/includes/__pycache__/__init__.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/_custom_ops.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/_version.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/beam_search.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/outputs.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/__pycache__/__init__.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/__pycache__/request.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/layers.py +16 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/request.py +26 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/utils.py +93 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__init__.py +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__pycache__/__init__.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__pycache__/base.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__pycache__/image.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/audio.py +45 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/__pycache__/__init__.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/__pycache__/layer.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/__pycache__/selector.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/__pycache__/flash_attn.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/__pycache__/flashmla.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/__pycache__/utils.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/abstract.py +325 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/differential_flash_attn.py +922 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/flash_attn.py +931 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/flashinfer.py +1098 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/flashmla.py +227 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/mla/common.py +1305 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/rocm_aiter_mla.py +410 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/rocm_flash_attn.py +948 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/utils.py +610 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/__init__.py +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/__pycache__/__init__.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/__pycache__/chunked_local_attention.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/chunked_local_attention.py +88 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/__init__.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/merge_attn_states.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/prefix_prefill.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/rocm_aiter_mla.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/triton_decode_attention.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/triton_merge_attn_states.cpython-312.pyc +0 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/chunked_prefill_paged_decode.py +391 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/paged_attn.py +256 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/pallas_kv_cache_update.py +124 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/rocm_aiter_mla.py +104 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/rocm_aiter_paged_attn.py +102 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/triton_decode_attention.py +676 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/triton_flash_attention.py +984 -0
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvicorn/protocols/http/auto.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
|
| 5 |
+
AutoHTTPProtocol: type[asyncio.Protocol]
|
| 6 |
+
try:
|
| 7 |
+
import httptools # noqa
|
| 8 |
+
except ImportError: # pragma: no cover
|
| 9 |
+
from uvicorn.protocols.http.h11_impl import H11Protocol
|
| 10 |
+
|
| 11 |
+
AutoHTTPProtocol = H11Protocol
|
| 12 |
+
else: # pragma: no cover
|
| 13 |
+
from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol
|
| 14 |
+
|
| 15 |
+
AutoHTTPProtocol = HttpToolsProtocol
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (735 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-312.pyc
ADDED
|
Binary file (2.84 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/uvloop/includes/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (583 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/_custom_ops.cpython-312.pyc
ADDED
|
Binary file (97.3 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/_version.cpython-312.pyc
ADDED
|
Binary file (785 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/beam_search.cpython-312.pyc
ADDED
|
Binary file (3.76 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/__pycache__/outputs.cpython-312.pyc
ADDED
|
Binary file (22.3 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (173 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/__pycache__/request.cpython-312.pyc
ADDED
|
Binary file (1.57 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/layers.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass
|
| 8 |
+
class AdapterMapping:
|
| 9 |
+
# Per every token in input_ids:
|
| 10 |
+
index_mapping: tuple[int, ...]
|
| 11 |
+
# Per sampled token:
|
| 12 |
+
prompt_mapping: tuple[int, ...]
|
| 13 |
+
|
| 14 |
+
def __post_init__(self):
|
| 15 |
+
self.index_mapping = tuple(self.index_mapping)
|
| 16 |
+
self.prompt_mapping = tuple(self.prompt_mapping)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/request.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from abc import ABC, abstractmethod
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AdapterRequest(ABC):
|
| 8 |
+
"""
|
| 9 |
+
Base class for adapter requests.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
@property
|
| 13 |
+
@abstractmethod
|
| 14 |
+
def adapter_id(self) -> int:
|
| 15 |
+
raise NotImplementedError
|
| 16 |
+
|
| 17 |
+
def __post_init__(self) -> None:
|
| 18 |
+
if self.adapter_id < 1:
|
| 19 |
+
raise ValueError(f"id must be > 0, got {self.adapter_id}")
|
| 20 |
+
|
| 21 |
+
def __eq__(self, value: object) -> bool:
|
| 22 |
+
return isinstance(
|
| 23 |
+
value, self.__class__) and self.adapter_id == value.adapter_id
|
| 24 |
+
|
| 25 |
+
def __hash__(self) -> int:
|
| 26 |
+
return hash(self.adapter_id)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/adapter_commons/utils.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from typing import Any, Callable, Optional
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
## model functions
|
| 8 |
+
def deactivate_adapter(adapter_id: int, active_adapters: dict[int, None],
|
| 9 |
+
deactivate_func: Callable) -> bool:
|
| 10 |
+
if adapter_id in active_adapters:
|
| 11 |
+
deactivate_func(adapter_id)
|
| 12 |
+
active_adapters.pop(adapter_id)
|
| 13 |
+
return True
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def add_adapter(adapter: Any, registered_adapters: dict[int, Any],
|
| 18 |
+
capacity: int, add_func: Callable) -> bool:
|
| 19 |
+
if adapter.id not in registered_adapters:
|
| 20 |
+
if len(registered_adapters) >= capacity:
|
| 21 |
+
raise RuntimeError('No free adapter slots.')
|
| 22 |
+
add_func(adapter)
|
| 23 |
+
registered_adapters[adapter.id] = adapter
|
| 24 |
+
return True
|
| 25 |
+
return False
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def set_adapter_mapping(mapping: Any, last_mapping: Any,
|
| 29 |
+
set_mapping_func: Callable) -> Any:
|
| 30 |
+
if last_mapping != mapping:
|
| 31 |
+
set_mapping_func(mapping)
|
| 32 |
+
return mapping
|
| 33 |
+
return last_mapping
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def remove_adapter(adapter_id: int, registered_adapters: dict[int, Any],
|
| 37 |
+
deactivate_func: Callable) -> bool:
|
| 38 |
+
deactivate_func(adapter_id)
|
| 39 |
+
return bool(registered_adapters.pop(adapter_id, None))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def list_adapters(registered_adapters: dict[int, Any]) -> dict[int, Any]:
|
| 43 |
+
return dict(registered_adapters)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_adapter(adapter_id: int,
|
| 47 |
+
registered_adapters: dict[int, Any]) -> Optional[Any]:
|
| 48 |
+
return registered_adapters.get(adapter_id)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
## worker functions
|
| 52 |
+
def set_active_adapters_worker(requests: set[Any], mapping: Optional[Any],
|
| 53 |
+
apply_adapters_func,
|
| 54 |
+
set_adapter_mapping_func) -> None:
|
| 55 |
+
apply_adapters_func(requests)
|
| 56 |
+
set_adapter_mapping_func(mapping)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def add_adapter_worker(adapter_request: Any, list_adapters_func,
|
| 60 |
+
load_adapter_func, add_adapter_func,
|
| 61 |
+
activate_adapter_func) -> bool:
|
| 62 |
+
if adapter_request.adapter_id in list_adapters_func():
|
| 63 |
+
return False
|
| 64 |
+
loaded_adapter = load_adapter_func(adapter_request)
|
| 65 |
+
loaded = add_adapter_func(loaded_adapter)
|
| 66 |
+
activate_adapter_func(loaded_adapter.id)
|
| 67 |
+
return loaded
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def apply_adapters_worker(adapter_requests: set[Any], list_adapters_func,
|
| 71 |
+
adapter_slots: int, remove_adapter_func,
|
| 72 |
+
add_adapter_func) -> None:
|
| 73 |
+
models_that_exist = list_adapters_func()
|
| 74 |
+
models_map = {
|
| 75 |
+
adapter_request.adapter_id: adapter_request
|
| 76 |
+
for adapter_request in adapter_requests if adapter_request
|
| 77 |
+
}
|
| 78 |
+
if len(models_map) > adapter_slots:
|
| 79 |
+
raise RuntimeError(
|
| 80 |
+
f"Number of requested models ({len(models_map)}) is greater "
|
| 81 |
+
f"than the number of GPU model slots "
|
| 82 |
+
f"({adapter_slots}).")
|
| 83 |
+
new_models = set(models_map)
|
| 84 |
+
models_to_add = new_models - models_that_exist
|
| 85 |
+
models_to_remove = models_that_exist - new_models
|
| 86 |
+
for adapter_id in models_to_remove:
|
| 87 |
+
remove_adapter_func(adapter_id)
|
| 88 |
+
for adapter_id in models_to_add:
|
| 89 |
+
add_adapter_func(models_map[adapter_id])
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def list_adapters_worker(adapter_manager_list_adapters_func) -> set[int]:
|
| 93 |
+
return set(adapter_manager_list_adapters_func())
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__init__.py
ADDED
|
File without changes
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (164 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__pycache__/base.cpython-312.pyc
ADDED
|
Binary file (1.67 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/__pycache__/image.cpython-312.pyc
ADDED
|
Binary file (1.67 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/assets/audio.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Literal
|
| 7 |
+
from urllib.parse import urljoin
|
| 8 |
+
|
| 9 |
+
import numpy.typing as npt
|
| 10 |
+
|
| 11 |
+
from vllm.utils import PlaceholderModule
|
| 12 |
+
|
| 13 |
+
from .base import VLLM_S3_BUCKET_URL, get_vllm_public_assets
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import librosa
|
| 17 |
+
except ImportError:
|
| 18 |
+
librosa = PlaceholderModule("librosa") # type: ignore[assignment]
|
| 19 |
+
|
| 20 |
+
ASSET_DIR = "multimodal_asset"
|
| 21 |
+
|
| 22 |
+
AudioAssetName = Literal["winning_call", "mary_had_lamb"]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass(frozen=True)
|
| 26 |
+
class AudioAsset:
|
| 27 |
+
name: AudioAssetName
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def filename(self) -> str:
|
| 31 |
+
return f"{self.name}.ogg"
|
| 32 |
+
|
| 33 |
+
@property
|
| 34 |
+
def audio_and_sample_rate(self) -> tuple[npt.NDArray, float]:
|
| 35 |
+
audio_path = get_vllm_public_assets(filename=self.filename,
|
| 36 |
+
s3_prefix=ASSET_DIR)
|
| 37 |
+
return librosa.load(audio_path, sr=None)
|
| 38 |
+
|
| 39 |
+
def get_local_path(self) -> Path:
|
| 40 |
+
return get_vllm_public_assets(filename=self.filename,
|
| 41 |
+
s3_prefix=ASSET_DIR)
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def url(self) -> str:
|
| 45 |
+
return urljoin(VLLM_S3_BUCKET_URL, f"{ASSET_DIR}/{self.name}.ogg")
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (552 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/__pycache__/layer.cpython-312.pyc
ADDED
|
Binary file (22.5 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/__pycache__/selector.cpython-312.pyc
ADDED
|
Binary file (7.39 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/__pycache__/flash_attn.cpython-312.pyc
ADDED
|
Binary file (36.7 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/__pycache__/flashmla.cpython-312.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/__pycache__/utils.cpython-312.pyc
ADDED
|
Binary file (25.7 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/abstract.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from abc import ABC, abstractmethod
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from dataclasses import dataclass, fields
|
| 7 |
+
from typing import (TYPE_CHECKING, Any, Dict, Generic, List, Optional,
|
| 8 |
+
Protocol, Set, Tuple, Type, TypeVar)
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
| 13 |
+
GroupShape)
|
| 14 |
+
from vllm.multimodal import MultiModalPlaceholderMap
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from vllm.worker.model_runner_base import (ModelRunnerBase,
|
| 18 |
+
ModelRunnerInputBase,
|
| 19 |
+
ModelRunnerInputBuilderBase)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class AttentionType:
|
| 23 |
+
"""
|
| 24 |
+
Attention type.
|
| 25 |
+
Use string to be compatible with `torch.compile`.
|
| 26 |
+
"""
|
| 27 |
+
# Decoder attention between previous layer Q/K/V
|
| 28 |
+
DECODER = "decoder"
|
| 29 |
+
# Encoder attention between previous layer Q/K/V for encoder-decoder
|
| 30 |
+
ENCODER = "encoder"
|
| 31 |
+
# Encoder attention between previous layer Q/K/V
|
| 32 |
+
ENCODER_ONLY = "encoder_only"
|
| 33 |
+
# Attention between dec. Q and enc. K/V for encoder-decoder
|
| 34 |
+
ENCODER_DECODER = "encoder_decoder"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class AttentionBackend(ABC):
|
| 38 |
+
"""Abstract class for attention backends."""
|
| 39 |
+
# For some attention backends, we allocate an output tensor before
|
| 40 |
+
# calling the custom op. When piecewise cudagraph is enabled, this
|
| 41 |
+
# makes sure the output tensor is allocated inside the cudagraph.
|
| 42 |
+
accept_output_buffer: bool = False
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
@abstractmethod
|
| 46 |
+
def get_name() -> str:
|
| 47 |
+
raise NotImplementedError
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
@abstractmethod
|
| 51 |
+
def get_impl_cls() -> Type["AttentionImpl"]:
|
| 52 |
+
raise NotImplementedError
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
@abstractmethod
|
| 56 |
+
def get_metadata_cls() -> Type["AttentionMetadata"]:
|
| 57 |
+
raise NotImplementedError
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
@abstractmethod
|
| 61 |
+
def get_state_cls() -> Type["AttentionState"]:
|
| 62 |
+
raise NotImplementedError
|
| 63 |
+
|
| 64 |
+
@classmethod
|
| 65 |
+
def make_metadata(cls, *args, **kwargs) -> "AttentionMetadata":
|
| 66 |
+
return cls.get_metadata_cls()(*args, **kwargs)
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
@abstractmethod
|
| 70 |
+
def get_builder_cls() -> Type["AttentionMetadataBuilder"]:
|
| 71 |
+
raise NotImplementedError
|
| 72 |
+
|
| 73 |
+
@staticmethod
|
| 74 |
+
@abstractmethod
|
| 75 |
+
def get_kv_cache_shape(
|
| 76 |
+
num_blocks: int,
|
| 77 |
+
block_size: int,
|
| 78 |
+
num_kv_heads: int,
|
| 79 |
+
head_size: int,
|
| 80 |
+
) -> Tuple[int, ...]:
|
| 81 |
+
raise NotImplementedError
|
| 82 |
+
|
| 83 |
+
@staticmethod
|
| 84 |
+
def get_kv_cache_stride_order() -> Tuple[int, ...]:
|
| 85 |
+
raise NotImplementedError
|
| 86 |
+
|
| 87 |
+
@staticmethod
|
| 88 |
+
@abstractmethod
|
| 89 |
+
def swap_blocks(
|
| 90 |
+
src_kv_cache: torch.Tensor,
|
| 91 |
+
dst_kv_cache: torch.Tensor,
|
| 92 |
+
src_to_dst: torch.Tensor,
|
| 93 |
+
) -> None:
|
| 94 |
+
raise NotImplementedError
|
| 95 |
+
|
| 96 |
+
@staticmethod
|
| 97 |
+
@abstractmethod
|
| 98 |
+
def copy_blocks(
|
| 99 |
+
kv_caches: List[torch.Tensor],
|
| 100 |
+
src_to_dists: torch.Tensor,
|
| 101 |
+
) -> None:
|
| 102 |
+
raise NotImplementedError
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def full_cls_name(cls) -> tuple[str, str]:
|
| 106 |
+
return (cls.__module__, cls.__qualname__)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclass
|
| 110 |
+
class AttentionMetadata:
|
| 111 |
+
"""Attention metadata for prefill and decode batched together."""
|
| 112 |
+
# Total number of prefill requests.
|
| 113 |
+
num_prefills: int
|
| 114 |
+
# Number of prefill tokens.
|
| 115 |
+
num_prefill_tokens: int
|
| 116 |
+
# Number of decode tokens. Note that it is equivalent to the number of
|
| 117 |
+
# decode requests.
|
| 118 |
+
num_decode_tokens: int
|
| 119 |
+
# (num_tokens,). The indices of the token slots that input tokens will be
|
| 120 |
+
# stored into. E.g., if `slot_mapping` is [35, 2, 17] and the block size
|
| 121 |
+
# is 16, the three tokens are stored in the 3rd slot in block 2, 2nd slot
|
| 122 |
+
# in block 0, and 1st slot in block 1, respectively.
|
| 123 |
+
slot_mapping: torch.Tensor
|
| 124 |
+
|
| 125 |
+
# The index maps that relate multi-modal embeddings to the corresponding
|
| 126 |
+
# placeholders.
|
| 127 |
+
#
|
| 128 |
+
# N.B. These aren't really related to attention and don't belong on this
|
| 129 |
+
# type -- this is just a temporary solution to make them available to
|
| 130 |
+
# `model_executable`.
|
| 131 |
+
multi_modal_placeholder_index_maps: Optional[Dict[
|
| 132 |
+
str, MultiModalPlaceholderMap.IndexMap]]
|
| 133 |
+
|
| 134 |
+
# Enable/disable KV scales calculation. This is so that we can disable the
|
| 135 |
+
# calculation until after prefill and cuda graph capture.
|
| 136 |
+
enable_kv_scales_calculation: bool
|
| 137 |
+
|
| 138 |
+
@property
|
| 139 |
+
@abstractmethod
|
| 140 |
+
def prefill_metadata(self) -> Optional["AttentionMetadata"]:
|
| 141 |
+
"""Return the attention metadata that's required to run prefill
|
| 142 |
+
attention."""
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
@abstractmethod
|
| 147 |
+
def decode_metadata(self) -> Optional["AttentionMetadata"]:
|
| 148 |
+
"""Return the attention metadata that's required to run decode
|
| 149 |
+
attention."""
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
def asdict_zerocopy(self,
|
| 153 |
+
skip_fields: Optional[Set[str]] = None
|
| 154 |
+
) -> Dict[str, Any]:
|
| 155 |
+
"""Similar to dataclasses.asdict, but avoids deepcopying."""
|
| 156 |
+
if skip_fields is None:
|
| 157 |
+
skip_fields = set()
|
| 158 |
+
# Note that if we add dataclasses as fields, they will need
|
| 159 |
+
# similar handling.
|
| 160 |
+
return {
|
| 161 |
+
field.name: getattr(self, field.name)
|
| 162 |
+
for field in fields(self) if field.name not in skip_fields
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
T = TypeVar("T", bound=AttentionMetadata)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class AttentionState(ABC, Generic[T]):
|
| 170 |
+
"""Holds attention backend-specific objects reused during the
|
| 171 |
+
lifetime of the model runner."""
|
| 172 |
+
|
| 173 |
+
@abstractmethod
|
| 174 |
+
def __init__(self, runner: "ModelRunnerBase"):
|
| 175 |
+
...
|
| 176 |
+
|
| 177 |
+
@abstractmethod
|
| 178 |
+
@contextmanager
|
| 179 |
+
def graph_capture(self, max_batch_size: int):
|
| 180 |
+
"""Context manager used when capturing CUDA graphs."""
|
| 181 |
+
yield
|
| 182 |
+
|
| 183 |
+
@abstractmethod
|
| 184 |
+
def graph_clone(self, batch_size: int) -> "AttentionState[T]":
|
| 185 |
+
"""Clone attention state to save in CUDA graph metadata."""
|
| 186 |
+
...
|
| 187 |
+
|
| 188 |
+
@abstractmethod
|
| 189 |
+
def graph_capture_get_metadata_for_batch(
|
| 190 |
+
self,
|
| 191 |
+
batch_size: int,
|
| 192 |
+
is_encoder_decoder_model: bool = False) -> T:
|
| 193 |
+
"""Get attention metadata for CUDA graph capture of batch_size."""
|
| 194 |
+
...
|
| 195 |
+
|
| 196 |
+
@abstractmethod
|
| 197 |
+
def get_graph_input_buffers(
|
| 198 |
+
self,
|
| 199 |
+
attn_metadata: T,
|
| 200 |
+
is_encoder_decoder_model: bool = False) -> Dict[str, Any]:
|
| 201 |
+
"""Get attention-specific input buffers for CUDA graph capture."""
|
| 202 |
+
...
|
| 203 |
+
|
| 204 |
+
@abstractmethod
|
| 205 |
+
def prepare_graph_input_buffers(
|
| 206 |
+
self,
|
| 207 |
+
input_buffers: Dict[str, Any],
|
| 208 |
+
attn_metadata: T,
|
| 209 |
+
is_encoder_decoder_model: bool = False) -> None:
|
| 210 |
+
"""In-place modify input buffers dict for CUDA graph replay."""
|
| 211 |
+
...
|
| 212 |
+
|
| 213 |
+
@abstractmethod
|
| 214 |
+
def begin_forward(self, model_input: "ModelRunnerInputBase") -> None:
|
| 215 |
+
"""Prepare state for forward pass."""
|
| 216 |
+
...
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class AttentionMetadataBuilder(ABC, Generic[T]):
|
| 220 |
+
"""Abstract class for attention metadata builders."""
|
| 221 |
+
|
| 222 |
+
@abstractmethod
|
| 223 |
+
def __init__(self, input_builder: "ModelRunnerInputBuilderBase") -> None:
|
| 224 |
+
"""Create the builder, remember some configuration and parameters."""
|
| 225 |
+
raise NotImplementedError
|
| 226 |
+
|
| 227 |
+
@abstractmethod
|
| 228 |
+
def prepare(self) -> None:
|
| 229 |
+
"""Prepare for one batch."""
|
| 230 |
+
raise NotImplementedError
|
| 231 |
+
|
| 232 |
+
@abstractmethod
|
| 233 |
+
def build(self, seq_lens: List[int], query_lens: List[int],
|
| 234 |
+
cuda_graph_pad_size: int, batch_size: int) -> T:
|
| 235 |
+
"""Build attention metadata with on-device tensors."""
|
| 236 |
+
raise NotImplementedError
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class AttentionLayer(Protocol):
|
| 240 |
+
|
| 241 |
+
_q_scale: torch.Tensor
|
| 242 |
+
_k_scale: torch.Tensor
|
| 243 |
+
_v_scale: torch.Tensor
|
| 244 |
+
_k_scale_float: float
|
| 245 |
+
_v_scale_float: float
|
| 246 |
+
_prob_scale: torch.Tensor
|
| 247 |
+
|
| 248 |
+
def forward(
|
| 249 |
+
self,
|
| 250 |
+
query: torch.Tensor,
|
| 251 |
+
key: torch.Tensor,
|
| 252 |
+
value: torch.Tensor,
|
| 253 |
+
kv_cache: torch.Tensor,
|
| 254 |
+
attn_metadata: AttentionMetadata,
|
| 255 |
+
) -> torch.Tensor:
|
| 256 |
+
...
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class AttentionImpl(ABC, Generic[T]):
|
| 260 |
+
|
| 261 |
+
@abstractmethod
|
| 262 |
+
def __init__(
|
| 263 |
+
self,
|
| 264 |
+
num_heads: int,
|
| 265 |
+
head_size: int,
|
| 266 |
+
scale: float,
|
| 267 |
+
num_kv_heads: Optional[int] = None,
|
| 268 |
+
alibi_slopes: Optional[List[float]] = None,
|
| 269 |
+
sliding_window: Optional[int] = None,
|
| 270 |
+
kv_cache_dtype: str = "auto",
|
| 271 |
+
logits_soft_cap: Optional[float] = None,
|
| 272 |
+
attn_type: str = AttentionType.DECODER,
|
| 273 |
+
kv_sharing_target_layer_name: Optional[str] = None,
|
| 274 |
+
) -> None:
|
| 275 |
+
raise NotImplementedError
|
| 276 |
+
|
| 277 |
+
@abstractmethod
|
| 278 |
+
def forward(
|
| 279 |
+
self,
|
| 280 |
+
layer: AttentionLayer,
|
| 281 |
+
query: torch.Tensor,
|
| 282 |
+
key: torch.Tensor,
|
| 283 |
+
value: torch.Tensor,
|
| 284 |
+
kv_cache: torch.Tensor,
|
| 285 |
+
attn_metadata: T,
|
| 286 |
+
output: Optional[torch.Tensor] = None,
|
| 287 |
+
output_scale: Optional[torch.Tensor] = None,
|
| 288 |
+
) -> torch.Tensor:
|
| 289 |
+
raise NotImplementedError
|
| 290 |
+
|
| 291 |
+
def fused_output_quant_supported(self, dtype: torch.dtype, static: bool,
|
| 292 |
+
group_shape: GroupShape):
|
| 293 |
+
"""
|
| 294 |
+
Does this attention implementation support fused output quantization.
|
| 295 |
+
This is used by the AttnFusionPass to only fuse output quantization
|
| 296 |
+
onto implementations that support it.
|
| 297 |
+
|
| 298 |
+
TODO(luka) merge parameters into QuantDescriptor
|
| 299 |
+
:param dtype: quantized dtype
|
| 300 |
+
:param static: static or dynamic quantization
|
| 301 |
+
:param group_shape: quant group shape.
|
| 302 |
+
:return: is fusion supported for this type of quantization
|
| 303 |
+
"""
|
| 304 |
+
return False
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class MLAAttentionImpl(AttentionImpl[T], Generic[T]):
|
| 308 |
+
|
| 309 |
+
@abstractmethod
|
| 310 |
+
def forward(
|
| 311 |
+
self,
|
| 312 |
+
layer: AttentionLayer,
|
| 313 |
+
hidden_states_or_cq: torch.Tensor,
|
| 314 |
+
kv_c_normed: torch.Tensor,
|
| 315 |
+
k_pe: torch.Tensor,
|
| 316 |
+
kv_cache: torch.Tensor,
|
| 317 |
+
attn_metadata: T,
|
| 318 |
+
output: Optional[torch.Tensor] = None,
|
| 319 |
+
output_scale: Optional[torch.Tensor] = None,
|
| 320 |
+
) -> torch.Tensor:
|
| 321 |
+
raise NotImplementedError
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def is_quantized_kv_cache(kv_cache_dtype: str) -> bool:
|
| 325 |
+
return kv_cache_dtype != "auto"
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/differential_flash_attn.py
ADDED
|
@@ -0,0 +1,922 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
"""" An implementation of https://arxiv.org/pdf/2410.05258 """
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from itertools import accumulate
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
|
| 12 |
+
from vllm import _custom_ops as ops
|
| 13 |
+
# yapf conflicts with isort for this block
|
| 14 |
+
# yapf: disable
|
| 15 |
+
from vllm.attention.backends.abstract import (AttentionBackend, AttentionImpl,
|
| 16 |
+
AttentionLayer,
|
| 17 |
+
AttentionMetadata,
|
| 18 |
+
AttentionMetadataBuilder,
|
| 19 |
+
AttentionType,
|
| 20 |
+
is_quantized_kv_cache)
|
| 21 |
+
from vllm.attention.backends.flash_attn import FlashAttentionBackend
|
| 22 |
+
# yapf: enable
|
| 23 |
+
from vllm.attention.backends.utils import (PAD_SLOT_ID, CommonAttentionState,
|
| 24 |
+
compute_slot_mapping,
|
| 25 |
+
compute_slot_mapping_start_idx,
|
| 26 |
+
is_all_cross_attn_metadata_set,
|
| 27 |
+
is_all_encoder_attn_metadata_set,
|
| 28 |
+
is_block_tables_empty)
|
| 29 |
+
from vllm.attention.utils.fa_utils import (flash_attn_supports_fp8,
|
| 30 |
+
get_flash_attn_version)
|
| 31 |
+
from vllm.logger import init_logger
|
| 32 |
+
from vllm.multimodal import MultiModalPlaceholderMap
|
| 33 |
+
from vllm.utils import async_tensor_h2d, make_tensor_with_pad
|
| 34 |
+
from vllm.vllm_flash_attn import (flash_attn_varlen_func,
|
| 35 |
+
flash_attn_with_kvcache)
|
| 36 |
+
|
| 37 |
+
if TYPE_CHECKING:
|
| 38 |
+
from vllm.worker.model_runner import ModelInputForGPUBuilder
|
| 39 |
+
|
| 40 |
+
logger = init_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DifferentialFlashAttentionBackend(AttentionBackend):
|
| 44 |
+
accept_output_buffer = False
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
def get_supported_head_sizes() -> List[int]:
|
| 48 |
+
return [32, 64, 96, 128, 160, 192, 224, 256]
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def get_kv_cache_shape(
|
| 52 |
+
num_blocks: int,
|
| 53 |
+
block_size: int,
|
| 54 |
+
num_kv_heads: int,
|
| 55 |
+
head_size: int,
|
| 56 |
+
) -> Tuple[int, ...]:
|
| 57 |
+
if block_size % 16 != 0:
|
| 58 |
+
raise ValueError("Block size must be a multiple of 16.")
|
| 59 |
+
assert num_kv_heads % 2 == 0, "num_kv_heads must be divisible by 2"
|
| 60 |
+
return (2, 2, num_blocks, block_size, num_kv_heads // 2, head_size)
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def get_name() -> str:
|
| 64 |
+
return "DIFFERENTIAL_FLASH_ATTN"
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def get_impl_cls() -> Type["DifferentialFlashAttentionImpl"]:
|
| 68 |
+
return DifferentialFlashAttentionImpl
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def get_metadata_cls() -> Type["DifferentialFlashAttentionMetadata"]:
|
| 72 |
+
return DifferentialFlashAttentionMetadata
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def get_builder_cls() -> Type["DifferentialFlashAttentionMetadataBuilder"]:
|
| 76 |
+
return DifferentialFlashAttentionMetadataBuilder
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def get_state_cls() -> Type["CommonAttentionState"]:
|
| 80 |
+
return CommonAttentionState
|
| 81 |
+
|
| 82 |
+
@staticmethod
|
| 83 |
+
def swap_blocks(
|
| 84 |
+
src_kv_cache: torch.Tensor,
|
| 85 |
+
dst_kv_cache: torch.Tensor,
|
| 86 |
+
src_to_dst: torch.Tensor,
|
| 87 |
+
) -> None:
|
| 88 |
+
src_key_cache = src_kv_cache[0]
|
| 89 |
+
dst_key_cache = dst_kv_cache[0]
|
| 90 |
+
ops.swap_blocks(src_key_cache, dst_key_cache, src_to_dst)
|
| 91 |
+
src_value_cache = src_kv_cache[1]
|
| 92 |
+
dst_value_cache = dst_kv_cache[1]
|
| 93 |
+
ops.swap_blocks(src_value_cache, dst_value_cache, src_to_dst)
|
| 94 |
+
|
| 95 |
+
@staticmethod
|
| 96 |
+
def copy_blocks(
|
| 97 |
+
kv_caches: List[torch.Tensor],
|
| 98 |
+
src_to_dists: torch.Tensor,
|
| 99 |
+
) -> None:
|
| 100 |
+
key_caches = [kv_cache[0] for kv_cache in kv_caches]
|
| 101 |
+
value_caches = [kv_cache[1] for kv_cache in kv_caches]
|
| 102 |
+
|
| 103 |
+
ops.copy_blocks(key_caches, value_caches, src_to_dists)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@dataclass
|
| 107 |
+
class DifferentialFlashAttentionMetadata(AttentionMetadata):
|
| 108 |
+
"""Metadata for FlashAttentionBackend.
|
| 109 |
+
|
| 110 |
+
NOTE: Any python object stored here is not updated when it is
|
| 111 |
+
cuda-graph replayed. If you have values that need to be changed
|
| 112 |
+
dynamically, it should be stored in tensor. The tensor has to be
|
| 113 |
+
updated from `CUDAGraphRunner.forward` API.
|
| 114 |
+
"""
|
| 115 |
+
# (batch_size,). The sequence length per sequence. Sequence length means
|
| 116 |
+
# the computed tokens + new tokens None if it is a decoding.
|
| 117 |
+
seq_lens: Optional[List[int]]
|
| 118 |
+
# seq_lens stored as a tensor.
|
| 119 |
+
seq_lens_tensor: Optional[torch.Tensor]
|
| 120 |
+
|
| 121 |
+
# NOTE(sang): Definition of context_len, query_len, and seq_len.
|
| 122 |
+
# |---------- N-1 iteration --------|
|
| 123 |
+
# |---------------- N iteration ---------------------|
|
| 124 |
+
# |- tokenA -|......................|-- newTokens ---|
|
| 125 |
+
# |---------- context_len ----------|
|
| 126 |
+
# |-------------------- seq_len ---------------------|
|
| 127 |
+
# |-- query_len ---|
|
| 128 |
+
|
| 129 |
+
# Maximum sequence length among prefill batch. 0 if there are decoding
|
| 130 |
+
# requests only.
|
| 131 |
+
max_prefill_seq_len: int
|
| 132 |
+
# Maximum sequence length among decode batch. 0 if there are prefill
|
| 133 |
+
# requests only.
|
| 134 |
+
max_decode_seq_len: int
|
| 135 |
+
# (batch_size,) A tensor of context lengths (tokens that are computed
|
| 136 |
+
# so far).
|
| 137 |
+
context_lens_tensor: Optional[torch.Tensor]
|
| 138 |
+
|
| 139 |
+
# (batch_size, max_blocks_per_seq).
|
| 140 |
+
# Block addresses per sequence. (Seq id -> list of physical block)
|
| 141 |
+
# E.g., [0, 1, 2] means tokens are stored in 0th, 1st, and 2nd blocks
|
| 142 |
+
# in the kv cache. Each block can contain up to block_size tokens.
|
| 143 |
+
# 2nd dimensions are padded up to max_blocks_per_seq if it is cuda-graph
|
| 144 |
+
# captured.
|
| 145 |
+
block_tables: Optional[torch.Tensor]
|
| 146 |
+
|
| 147 |
+
# Whether or not if cuda graph is enabled.
|
| 148 |
+
# Cuda-graph is currently enabled for decoding only.
|
| 149 |
+
# TODO(woosuk): Move `use_cuda_graph` out since it's unrelated to attention.
|
| 150 |
+
|
| 151 |
+
use_cuda_graph: bool
|
| 152 |
+
|
| 153 |
+
# Maximum query length in the batch.
|
| 154 |
+
max_query_len: Optional[int] = None
|
| 155 |
+
|
| 156 |
+
# Max number of query tokens among request in the batch.
|
| 157 |
+
max_decode_query_len: Optional[int] = None
|
| 158 |
+
|
| 159 |
+
# (batch_size + 1,). The cumulative subquery lengths of the sequences in
|
| 160 |
+
# the batch, used to index into subquery. E.g., if the subquery length
|
| 161 |
+
# is [4, 6], it is [0, 4, 10].
|
| 162 |
+
query_start_loc: Optional[torch.Tensor] = None
|
| 163 |
+
# (batch_size + 1,). The cumulative sequence lengths of the sequences in
|
| 164 |
+
# the batch, used to index into sequence. E.g., if the sequence length is
|
| 165 |
+
# [4, 6], it is [0, 4, 10].
|
| 166 |
+
seq_start_loc: Optional[torch.Tensor] = None
|
| 167 |
+
|
| 168 |
+
_cached_prefill_metadata: Optional[
|
| 169 |
+
"DifferentialFlashAttentionMetadata"] = None
|
| 170 |
+
_cached_decode_metadata: Optional[
|
| 171 |
+
"DifferentialFlashAttentionMetadata"] = None
|
| 172 |
+
|
| 173 |
+
# Begin encoder attn & enc/dec cross-attn fields...
|
| 174 |
+
|
| 175 |
+
# Encoder sequence lengths representation
|
| 176 |
+
encoder_seq_lens: Optional[List[int]] = None
|
| 177 |
+
encoder_seq_lens_tensor: Optional[torch.Tensor] = None
|
| 178 |
+
# (batch_size + 1,). The cumulative sequence lengths of the sequences in
|
| 179 |
+
# the batch, used to index into sequence. E.g., if the sequence length is
|
| 180 |
+
# [4, 6], it is [0, 4, 10].
|
| 181 |
+
encoder_seq_start_loc: Optional[torch.Tensor] = None
|
| 182 |
+
# Maximum sequence length among encoder sequences
|
| 183 |
+
max_encoder_seq_len: Optional[int] = None
|
| 184 |
+
# Number of tokens input to encoder
|
| 185 |
+
num_encoder_tokens: Optional[int] = None
|
| 186 |
+
|
| 187 |
+
# Cross-attention memory-mapping data structures: slot mapping
|
| 188 |
+
# and block tables
|
| 189 |
+
cross_slot_mapping: Optional[torch.Tensor] = None
|
| 190 |
+
cross_block_tables: Optional[torch.Tensor] = None
|
| 191 |
+
|
| 192 |
+
# Cross-layer shared attention block tables
|
| 193 |
+
cross_layer_shared_block_tables: Optional[torch.Tensor] = None
|
| 194 |
+
|
| 195 |
+
@property
|
| 196 |
+
def is_all_encoder_attn_metadata_set(self):
|
| 197 |
+
'''
|
| 198 |
+
All attention metadata required for encoder attention is set.
|
| 199 |
+
'''
|
| 200 |
+
return is_all_encoder_attn_metadata_set(self)
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def is_all_cross_attn_metadata_set(self):
|
| 204 |
+
'''
|
| 205 |
+
All attention metadata required for enc/dec cross-attention is set.
|
| 206 |
+
|
| 207 |
+
Superset of encoder attention required metadata.
|
| 208 |
+
'''
|
| 209 |
+
return is_all_cross_attn_metadata_set(self)
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def prefill_metadata(
|
| 213 |
+
self) -> Optional["DifferentialFlashAttentionMetadata"]:
|
| 214 |
+
if self.num_prefills == 0:
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
+
if self._cached_prefill_metadata is not None:
|
| 218 |
+
return self._cached_prefill_metadata
|
| 219 |
+
|
| 220 |
+
assert ((self.seq_lens is not None)
|
| 221 |
+
or (self.encoder_seq_lens is not None))
|
| 222 |
+
assert ((self.seq_lens_tensor is not None)
|
| 223 |
+
or (self.encoder_seq_lens_tensor is not None))
|
| 224 |
+
|
| 225 |
+
# Compute some attn_metadata fields which default to None
|
| 226 |
+
query_start_loc = (None if self.query_start_loc is None else
|
| 227 |
+
self.query_start_loc[:self.num_prefills + 1])
|
| 228 |
+
slot_mapping = (None if self.slot_mapping is None else
|
| 229 |
+
self.slot_mapping[:self.num_prefill_tokens])
|
| 230 |
+
seq_lens = (None if self.seq_lens is None else
|
| 231 |
+
self.seq_lens[:self.num_prefills])
|
| 232 |
+
seq_lens_tensor = (None if self.seq_lens_tensor is None else
|
| 233 |
+
self.seq_lens_tensor[:self.num_prefills])
|
| 234 |
+
seq_start_loc = (None if self.seq_start_loc is None else
|
| 235 |
+
self.seq_start_loc[:self.num_prefills + 1])
|
| 236 |
+
context_lens_tensor = (None if self.context_lens_tensor is None else
|
| 237 |
+
self.context_lens_tensor[:self.num_prefills])
|
| 238 |
+
block_tables = (None if self.block_tables is None else
|
| 239 |
+
self.block_tables[:self.num_prefills])
|
| 240 |
+
cross_layer_shared_block_tables = (
|
| 241 |
+
None if self.cross_layer_shared_block_tables is None else
|
| 242 |
+
self.cross_layer_shared_block_tables[:self.num_prefills])
|
| 243 |
+
|
| 244 |
+
self._cached_prefill_metadata = DifferentialFlashAttentionMetadata(
|
| 245 |
+
num_prefills=self.num_prefills,
|
| 246 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 247 |
+
num_decode_tokens=0,
|
| 248 |
+
slot_mapping=slot_mapping,
|
| 249 |
+
multi_modal_placeholder_index_maps=self.
|
| 250 |
+
multi_modal_placeholder_index_maps,
|
| 251 |
+
enable_kv_scales_calculation=self.enable_kv_scales_calculation,
|
| 252 |
+
seq_lens=seq_lens,
|
| 253 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 254 |
+
max_query_len=self.max_query_len,
|
| 255 |
+
max_prefill_seq_len=self.max_prefill_seq_len,
|
| 256 |
+
max_decode_query_len=0,
|
| 257 |
+
max_decode_seq_len=0,
|
| 258 |
+
query_start_loc=query_start_loc,
|
| 259 |
+
seq_start_loc=seq_start_loc,
|
| 260 |
+
context_lens_tensor=context_lens_tensor,
|
| 261 |
+
block_tables=block_tables,
|
| 262 |
+
cross_layer_shared_block_tables=cross_layer_shared_block_tables,
|
| 263 |
+
use_cuda_graph=False,
|
| 264 |
+
# Begin encoder & cross attn fields below...
|
| 265 |
+
encoder_seq_lens=self.encoder_seq_lens,
|
| 266 |
+
encoder_seq_lens_tensor=self.encoder_seq_lens_tensor,
|
| 267 |
+
encoder_seq_start_loc=self.encoder_seq_start_loc,
|
| 268 |
+
max_encoder_seq_len=self.max_encoder_seq_len,
|
| 269 |
+
cross_slot_mapping=self.cross_slot_mapping,
|
| 270 |
+
cross_block_tables=self.cross_block_tables)
|
| 271 |
+
return self._cached_prefill_metadata
|
| 272 |
+
|
| 273 |
+
@property
|
| 274 |
+
def decode_metadata(
|
| 275 |
+
self) -> Optional["DifferentialFlashAttentionMetadata"]:
|
| 276 |
+
if self.num_decode_tokens == 0:
|
| 277 |
+
return None
|
| 278 |
+
|
| 279 |
+
if self._cached_decode_metadata is not None:
|
| 280 |
+
return self._cached_decode_metadata
|
| 281 |
+
assert ((self.seq_lens_tensor is not None)
|
| 282 |
+
or (self.encoder_seq_lens_tensor is not None))
|
| 283 |
+
|
| 284 |
+
# Compute some attn_metadata fields which default to None
|
| 285 |
+
slot_mapping = (None if self.slot_mapping is None else
|
| 286 |
+
self.slot_mapping[self.num_prefill_tokens:])
|
| 287 |
+
seq_lens_tensor = (None if self.seq_lens_tensor is None else
|
| 288 |
+
self.seq_lens_tensor[self.num_prefills:])
|
| 289 |
+
block_tables = (None if self.block_tables is None else
|
| 290 |
+
self.block_tables[self.num_prefills:])
|
| 291 |
+
cross_layer_shared_block_tables = (
|
| 292 |
+
None if self.cross_layer_shared_block_tables is None else
|
| 293 |
+
self.cross_layer_shared_block_tables[self.num_prefills:])
|
| 294 |
+
self._cached_decode_metadata = DifferentialFlashAttentionMetadata(
|
| 295 |
+
num_prefills=0,
|
| 296 |
+
num_prefill_tokens=0,
|
| 297 |
+
num_decode_tokens=self.num_decode_tokens,
|
| 298 |
+
slot_mapping=slot_mapping,
|
| 299 |
+
multi_modal_placeholder_index_maps=None,
|
| 300 |
+
enable_kv_scales_calculation=True,
|
| 301 |
+
seq_lens=None,
|
| 302 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 303 |
+
max_decode_query_len=self.max_decode_query_len,
|
| 304 |
+
max_query_len=self.max_query_len,
|
| 305 |
+
max_prefill_seq_len=0,
|
| 306 |
+
max_decode_seq_len=self.max_decode_seq_len,
|
| 307 |
+
# Batch may be composed of prefill|decodes, adjust query start
|
| 308 |
+
# indices to refer to the start of decodes. E.g.
|
| 309 |
+
# in tokens:[3 prefills|6 decodes], query_start_loc=[3,9] => [0,6].
|
| 310 |
+
query_start_loc=(self.query_start_loc[self.num_prefills:] -
|
| 311 |
+
self.query_start_loc[self.num_prefills])
|
| 312 |
+
if self.query_start_loc is not None else None,
|
| 313 |
+
seq_start_loc=self.seq_start_loc[self.num_prefills:]
|
| 314 |
+
if self.seq_start_loc is not None else None,
|
| 315 |
+
context_lens_tensor=None,
|
| 316 |
+
block_tables=block_tables,
|
| 317 |
+
cross_layer_shared_block_tables=cross_layer_shared_block_tables,
|
| 318 |
+
use_cuda_graph=self.use_cuda_graph,
|
| 319 |
+
# Begin encoder & cross attn fields below...
|
| 320 |
+
encoder_seq_lens=self.encoder_seq_lens,
|
| 321 |
+
encoder_seq_lens_tensor=self.encoder_seq_lens_tensor,
|
| 322 |
+
encoder_seq_start_loc=self.encoder_seq_start_loc,
|
| 323 |
+
max_encoder_seq_len=self.max_encoder_seq_len,
|
| 324 |
+
cross_slot_mapping=self.cross_slot_mapping,
|
| 325 |
+
cross_block_tables=self.cross_block_tables)
|
| 326 |
+
return self._cached_decode_metadata
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class DifferentialFlashAttentionMetadataBuilder(
|
| 330 |
+
AttentionMetadataBuilder[DifferentialFlashAttentionMetadata]):
|
| 331 |
+
|
| 332 |
+
def __init__(self, input_builder: "ModelInputForGPUBuilder"):
|
| 333 |
+
self.input_builder = input_builder
|
| 334 |
+
self.runner = input_builder.runner
|
| 335 |
+
self.sliding_window = input_builder.sliding_window
|
| 336 |
+
self.block_size = input_builder.block_size
|
| 337 |
+
|
| 338 |
+
def prepare(self):
|
| 339 |
+
self.slot_mapping: List[int] = []
|
| 340 |
+
self.prefill_seq_lens: List[int] = []
|
| 341 |
+
self.context_lens: List[int] = []
|
| 342 |
+
self.block_tables: List[List[int]] = []
|
| 343 |
+
self.cross_layer_shared_block_tables: List[List[int]] = []
|
| 344 |
+
self.curr_seq_lens: List[int] = []
|
| 345 |
+
self.multimodal_placeholder_maps: Dict[
|
| 346 |
+
str,
|
| 347 |
+
MultiModalPlaceholderMap] = defaultdict(MultiModalPlaceholderMap)
|
| 348 |
+
self.num_prefills = 0
|
| 349 |
+
self.num_prefill_tokens = 0
|
| 350 |
+
self.num_decode_tokens = 0
|
| 351 |
+
self.has_prefix_cache_hit = False
|
| 352 |
+
|
| 353 |
+
def _add_seq_group(
|
| 354 |
+
self, inter_data: "ModelInputForGPUBuilder.InterDataForSeqGroup",
|
| 355 |
+
chunked_prefill_enabled: bool, prefix_cache_hit: bool):
|
| 356 |
+
"""Add a sequence group to the metadata. Specifically update/append
|
| 357 |
+
1. context length.
|
| 358 |
+
2. block table.
|
| 359 |
+
3. slot mapping.
|
| 360 |
+
"""
|
| 361 |
+
# TODO: add support for chunked prefill and prefix caching.
|
| 362 |
+
assert not chunked_prefill_enabled, \
|
| 363 |
+
"chunked prefill is not supported for now"
|
| 364 |
+
assert not prefix_cache_hit, "prefix caching is not supported for now"
|
| 365 |
+
|
| 366 |
+
is_prompt = inter_data.is_prompt
|
| 367 |
+
block_tables = inter_data.block_tables
|
| 368 |
+
|
| 369 |
+
for (seq_id, token_len, seq_len, curr_seq_len, query_len, context_len,
|
| 370 |
+
curr_sliding_window_block) in zip(
|
| 371 |
+
inter_data.seq_ids, [len(t) for t in inter_data.input_tokens],
|
| 372 |
+
inter_data.orig_seq_lens, inter_data.seq_lens,
|
| 373 |
+
inter_data.query_lens, inter_data.context_lens,
|
| 374 |
+
inter_data.curr_sliding_window_blocks):
|
| 375 |
+
self.context_lens.append(context_len)
|
| 376 |
+
|
| 377 |
+
if is_prompt:
|
| 378 |
+
mm_maps = inter_data.multi_modal_placeholder_maps
|
| 379 |
+
if mm_maps:
|
| 380 |
+
for modality, placeholders in mm_maps.items():
|
| 381 |
+
self.multimodal_placeholder_maps[modality].extend(
|
| 382 |
+
placeholders)
|
| 383 |
+
|
| 384 |
+
self.num_prefills += 1
|
| 385 |
+
self.num_prefill_tokens += token_len
|
| 386 |
+
self.prefill_seq_lens.append(seq_len)
|
| 387 |
+
else:
|
| 388 |
+
self.num_decode_tokens += query_len
|
| 389 |
+
self.curr_seq_lens.append(curr_seq_len)
|
| 390 |
+
|
| 391 |
+
# Compute block table.
|
| 392 |
+
# TODO(sang): Combine chunked prefill and prefix caching by
|
| 393 |
+
# only allowing multiple of block_size chunk size.
|
| 394 |
+
# NOTE: This only works for oooooooxxx style attention.
|
| 395 |
+
block_table = []
|
| 396 |
+
if prefix_cache_hit:
|
| 397 |
+
# NOTE(woosuk): For flash-attn, the block table should
|
| 398 |
+
# include the entries for the incoming prefill tokens.
|
| 399 |
+
block_table = block_tables[seq_id]
|
| 400 |
+
elif ((chunked_prefill_enabled or not is_prompt)
|
| 401 |
+
and block_tables is not None):
|
| 402 |
+
if curr_sliding_window_block == 0:
|
| 403 |
+
block_table = block_tables[seq_id]
|
| 404 |
+
else:
|
| 405 |
+
block_table = block_tables[seq_id][
|
| 406 |
+
-curr_sliding_window_block:]
|
| 407 |
+
self.block_tables.append(block_table)
|
| 408 |
+
|
| 409 |
+
cross_layer_shared_block_table = []
|
| 410 |
+
if prefix_cache_hit:
|
| 411 |
+
cross_layer_shared_block_table = block_tables[seq_id]
|
| 412 |
+
elif block_tables is not None:
|
| 413 |
+
if curr_sliding_window_block == 0:
|
| 414 |
+
cross_layer_shared_block_table = block_tables[seq_id]
|
| 415 |
+
else:
|
| 416 |
+
cross_layer_shared_block_table = block_tables[seq_id][
|
| 417 |
+
-curr_sliding_window_block:]
|
| 418 |
+
self.cross_layer_shared_block_tables.append(
|
| 419 |
+
cross_layer_shared_block_table)
|
| 420 |
+
|
| 421 |
+
# Compute slot mapping.
|
| 422 |
+
is_profile_run = is_block_tables_empty(block_tables)
|
| 423 |
+
start_idx = compute_slot_mapping_start_idx(is_prompt, query_len,
|
| 424 |
+
context_len,
|
| 425 |
+
self.sliding_window)
|
| 426 |
+
compute_slot_mapping(is_profile_run, self.slot_mapping, seq_id,
|
| 427 |
+
seq_len, context_len, start_idx,
|
| 428 |
+
self.block_size, inter_data.block_tables)
|
| 429 |
+
|
| 430 |
+
def _get_graph_runner_block_tables(self, num_seqs: int,
|
| 431 |
+
block_tables: List[List[int]],
|
| 432 |
+
graph_block_tables) -> torch.Tensor:
|
| 433 |
+
# The shape of graph_block_tables is
|
| 434 |
+
# [max batch size, max context len // block size].
|
| 435 |
+
# max_batch_size, max_blocks = self.runner.graph_block_tables.shape
|
| 436 |
+
max_batch_size, max_blocks = graph_block_tables.shape
|
| 437 |
+
assert max_batch_size >= num_seqs
|
| 438 |
+
|
| 439 |
+
# graph_block_tables = self.runner.graph_block_tables[:num_seqs]
|
| 440 |
+
graph_block_tables = graph_block_tables[:num_seqs]
|
| 441 |
+
for i, block_table in enumerate(block_tables):
|
| 442 |
+
if block_table:
|
| 443 |
+
num_blocks = len(block_table)
|
| 444 |
+
if num_blocks <= max_blocks:
|
| 445 |
+
graph_block_tables[i, :num_blocks] = block_table
|
| 446 |
+
else:
|
| 447 |
+
# It may be possible to have more blocks allocated due
|
| 448 |
+
# to lookahead slots of multi-step, however, they are
|
| 449 |
+
# not used anyway, so can be safely ignored.
|
| 450 |
+
graph_block_tables[
|
| 451 |
+
i, :max_blocks] = block_table[:max_blocks]
|
| 452 |
+
|
| 453 |
+
return torch.from_numpy(graph_block_tables).to(
|
| 454 |
+
device=self.runner.device, non_blocking=True)
|
| 455 |
+
|
| 456 |
+
def build(self, seq_lens: List[int], query_lens: List[int],
|
| 457 |
+
cuda_graph_pad_size: int, batch_size: int):
|
| 458 |
+
"""Build attention metadata with on-device tensors.
|
| 459 |
+
|
| 460 |
+
Args:
|
| 461 |
+
seq_lens: The maybe padded sequence lengths of the input sequences.
|
| 462 |
+
query_lens: The query lengths of the input sequences.
|
| 463 |
+
cuda_graph_pad_size: The padding size for cuda graph.
|
| 464 |
+
-1 if cuda graph is not used.
|
| 465 |
+
batch_size: The maybe padded batch size.
|
| 466 |
+
"""
|
| 467 |
+
prefix_cache_hit = any([
|
| 468 |
+
inter_data.prefix_cache_hit
|
| 469 |
+
for inter_data in self.input_builder.inter_data_list
|
| 470 |
+
])
|
| 471 |
+
for inter_data in self.input_builder.inter_data_list:
|
| 472 |
+
self._add_seq_group(inter_data,
|
| 473 |
+
self.input_builder.chunked_prefill_enabled,
|
| 474 |
+
prefix_cache_hit)
|
| 475 |
+
|
| 476 |
+
device = self.runner.device
|
| 477 |
+
use_captured_graph = cuda_graph_pad_size != -1
|
| 478 |
+
|
| 479 |
+
max_query_len = max(query_lens)
|
| 480 |
+
decode_query_lens = query_lens[self.num_prefills:]
|
| 481 |
+
if len(decode_query_lens) > 0:
|
| 482 |
+
max_decode_query_len = max(decode_query_lens)
|
| 483 |
+
else:
|
| 484 |
+
max_decode_query_len = 1
|
| 485 |
+
max_prefill_seq_len = max(self.prefill_seq_lens, default=0)
|
| 486 |
+
max_decode_seq_len = max(self.curr_seq_lens, default=0)
|
| 487 |
+
num_decode_tokens = self.num_decode_tokens
|
| 488 |
+
query_start_loc = list(accumulate(query_lens, initial=0))
|
| 489 |
+
seq_start_loc = list(accumulate(seq_lens, initial=0))
|
| 490 |
+
|
| 491 |
+
num_seqs = len(seq_lens)
|
| 492 |
+
if use_captured_graph:
|
| 493 |
+
self.slot_mapping.extend([PAD_SLOT_ID] * cuda_graph_pad_size)
|
| 494 |
+
self.block_tables.extend([] * cuda_graph_pad_size)
|
| 495 |
+
|
| 496 |
+
self.cross_layer_shared_block_tables.extend([] *
|
| 497 |
+
cuda_graph_pad_size)
|
| 498 |
+
|
| 499 |
+
num_decode_tokens = batch_size - self.num_prefill_tokens
|
| 500 |
+
block_tables = self._get_graph_runner_block_tables(
|
| 501 |
+
num_seqs, self.block_tables, self.runner.graph_block_tables)
|
| 502 |
+
cross_layer_shared_block_tables = \
|
| 503 |
+
self._get_graph_runner_block_tables(
|
| 504 |
+
num_seqs, self.cross_layer_shared_block_tables,
|
| 505 |
+
self.runner.cross_layer_shared_graph_block_tables)
|
| 506 |
+
else:
|
| 507 |
+
block_tables = make_tensor_with_pad(
|
| 508 |
+
self.block_tables,
|
| 509 |
+
pad=0,
|
| 510 |
+
dtype=torch.int,
|
| 511 |
+
device=device,
|
| 512 |
+
)
|
| 513 |
+
cross_layer_shared_block_tables = make_tensor_with_pad(
|
| 514 |
+
self.cross_layer_shared_block_tables,
|
| 515 |
+
pad=0,
|
| 516 |
+
dtype=torch.int,
|
| 517 |
+
device=device,
|
| 518 |
+
)
|
| 519 |
+
assert max_query_len > 0, ("query_lens: {}".format(query_lens))
|
| 520 |
+
|
| 521 |
+
assert device is not None
|
| 522 |
+
context_lens_tensor = async_tensor_h2d(self.context_lens, torch.int,
|
| 523 |
+
device, self.runner.pin_memory)
|
| 524 |
+
seq_lens_tensor = async_tensor_h2d(seq_lens, torch.int, device,
|
| 525 |
+
self.runner.pin_memory)
|
| 526 |
+
slot_mapping_tensor = async_tensor_h2d(self.slot_mapping, torch.long,
|
| 527 |
+
device, self.runner.pin_memory)
|
| 528 |
+
query_start_loc_tensor = async_tensor_h2d(query_start_loc, torch.int32,
|
| 529 |
+
device,
|
| 530 |
+
self.runner.pin_memory)
|
| 531 |
+
seq_start_loc_tensor = async_tensor_h2d(seq_start_loc, torch.int32,
|
| 532 |
+
device, self.runner.pin_memory)
|
| 533 |
+
placeholder_index_maps = {
|
| 534 |
+
modality: placeholder_map.index_map()
|
| 535 |
+
for modality, placeholder_map in
|
| 536 |
+
self.multimodal_placeholder_maps.items()
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
return DifferentialFlashAttentionMetadata(
|
| 540 |
+
num_prefills=self.num_prefills,
|
| 541 |
+
slot_mapping=slot_mapping_tensor,
|
| 542 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 543 |
+
num_decode_tokens=num_decode_tokens,
|
| 544 |
+
seq_lens=seq_lens,
|
| 545 |
+
multi_modal_placeholder_index_maps=placeholder_index_maps,
|
| 546 |
+
enable_kv_scales_calculation=True,
|
| 547 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 548 |
+
max_query_len=max_query_len,
|
| 549 |
+
max_decode_query_len=max_decode_query_len,
|
| 550 |
+
max_prefill_seq_len=max_prefill_seq_len,
|
| 551 |
+
max_decode_seq_len=max_decode_seq_len,
|
| 552 |
+
query_start_loc=query_start_loc_tensor,
|
| 553 |
+
seq_start_loc=seq_start_loc_tensor,
|
| 554 |
+
context_lens_tensor=context_lens_tensor,
|
| 555 |
+
block_tables=block_tables,
|
| 556 |
+
cross_layer_shared_block_tables=cross_layer_shared_block_tables,
|
| 557 |
+
use_cuda_graph=use_captured_graph,
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
class DifferentialFlashAttentionImpl(AttentionImpl):
|
| 562 |
+
"""
|
| 563 |
+
If the input tensors contain prompt tokens, the layout is as follows:
|
| 564 |
+
|<--------------- num_prefill_tokens ----------------->|
|
| 565 |
+
|<--prefill_0-->|<--prefill_1-->|...|<--prefill_N-1--->|
|
| 566 |
+
|
| 567 |
+
Otherwise, the layout is as follows:
|
| 568 |
+
|<----------------- num_decode_tokens ------------------>|
|
| 569 |
+
|<--decode_0-->|..........|<--decode_M-1-->|<--padding-->|
|
| 570 |
+
|
| 571 |
+
Generation tokens can contain padding when cuda-graph is used.
|
| 572 |
+
Currently, prompt tokens don't contain any padding.
|
| 573 |
+
|
| 574 |
+
The prompts might have different lengths, while the generation tokens
|
| 575 |
+
always have length 1.
|
| 576 |
+
|
| 577 |
+
If chunked prefill is enabled, prefill tokens and decode tokens can be
|
| 578 |
+
batched together in a flattened 1D query.
|
| 579 |
+
|
| 580 |
+
|<----- num_prefill_tokens ---->|<------- num_decode_tokens --------->|
|
| 581 |
+
|<-prefill_0->|...|<-prefill_N-1->|<--decode_0-->|...|<--decode_M-1-->|
|
| 582 |
+
|
| 583 |
+
Currently, cuda graph is disabled for chunked prefill, meaning there's no
|
| 584 |
+
padding between prefill and decode tokens.
|
| 585 |
+
"""
|
| 586 |
+
|
| 587 |
+
def __init__(
|
| 588 |
+
self,
|
| 589 |
+
num_heads: int,
|
| 590 |
+
head_size: int,
|
| 591 |
+
scale: float,
|
| 592 |
+
num_kv_heads: int,
|
| 593 |
+
alibi_slopes: Optional[List[float]],
|
| 594 |
+
sliding_window: Optional[int],
|
| 595 |
+
kv_cache_dtype: str,
|
| 596 |
+
logits_soft_cap: Optional[float] = None,
|
| 597 |
+
attn_type: str = AttentionType.DECODER,
|
| 598 |
+
kv_sharing_target_layer_name: Optional[str] = None,
|
| 599 |
+
use_irope: bool = False,
|
| 600 |
+
differential_flash_attention_config: Optional[Dict[str, Any]] = None,
|
| 601 |
+
) -> None:
|
| 602 |
+
if differential_flash_attention_config is None:
|
| 603 |
+
differential_flash_attention_config = {}
|
| 604 |
+
self.differential_flash_attention_config = \
|
| 605 |
+
differential_flash_attention_config
|
| 606 |
+
self.used_shared_kv_cache = kv_sharing_target_layer_name is not None
|
| 607 |
+
self.kv_sharing_target_layer_name = kv_sharing_target_layer_name
|
| 608 |
+
if use_irope:
|
| 609 |
+
logger.warning(
|
| 610 |
+
"Using irope in V0 is not supported yet, it will fall back "
|
| 611 |
+
"to global attention for long context.")
|
| 612 |
+
self.num_heads = num_heads
|
| 613 |
+
self.head_size = head_size
|
| 614 |
+
self.scale = float(scale)
|
| 615 |
+
self.num_kv_heads = num_kv_heads
|
| 616 |
+
if alibi_slopes is not None:
|
| 617 |
+
alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
|
| 618 |
+
self.alibi_slopes = alibi_slopes
|
| 619 |
+
self.sliding_window = ((sliding_window - 1,
|
| 620 |
+
0) if sliding_window is not None else (-1, -1))
|
| 621 |
+
self.kv_cache_dtype = kv_cache_dtype
|
| 622 |
+
self.vllm_flash_attn_version = get_flash_attn_version(
|
| 623 |
+
requires_alibi=self.alibi_slopes is not None)
|
| 624 |
+
if is_quantized_kv_cache(self.kv_cache_dtype) and (
|
| 625 |
+
not self.kv_cache_dtype.startswith("fp8")
|
| 626 |
+
or not flash_attn_supports_fp8()):
|
| 627 |
+
raise NotImplementedError(
|
| 628 |
+
f"FlashAttention does not support {self.kv_cache_dtype} "
|
| 629 |
+
"kv-cache on this device "
|
| 630 |
+
f"(FA supports fp8 = {flash_attn_supports_fp8()}).")
|
| 631 |
+
if logits_soft_cap is None:
|
| 632 |
+
# In flash-attn, setting logits_soft_cap as 0 means no soft cap.
|
| 633 |
+
logits_soft_cap = 0
|
| 634 |
+
self.logits_soft_cap = logits_soft_cap
|
| 635 |
+
|
| 636 |
+
assert self.num_heads % self.num_kv_heads == 0
|
| 637 |
+
self.num_queries_per_kv = self.num_heads // self.num_kv_heads
|
| 638 |
+
|
| 639 |
+
support_head_sizes = FlashAttentionBackend.get_supported_head_sizes()
|
| 640 |
+
if head_size not in support_head_sizes:
|
| 641 |
+
raise ValueError(
|
| 642 |
+
f"Head size {head_size} is not supported by FlashAttention. "
|
| 643 |
+
f"Supported head sizes are: {support_head_sizes}.")
|
| 644 |
+
self.attn_type = attn_type
|
| 645 |
+
|
| 646 |
+
self.lambda_full = None
|
| 647 |
+
self.subln = self.differential_flash_attention_config["subln"]
|
| 648 |
+
|
| 649 |
+
def split_heads(self, x):
|
| 650 |
+
# split by num_heads, the stripe pattern is friendly to tensor parallel.
|
| 651 |
+
x = rearrange(x, "... (H two) D -> ... H two D", two=2)
|
| 652 |
+
x1 = x[..., 0, :]
|
| 653 |
+
x2 = x[..., 1, :]
|
| 654 |
+
return x1.contiguous(), x2.contiguous()
|
| 655 |
+
|
| 656 |
+
def split_kv_cache(self, x):
|
| 657 |
+
# split by num_heads, the stripe pattern is friendly to tensor parallel.
|
| 658 |
+
if x.numel() == 0:
|
| 659 |
+
return torch.empty(0), torch.empty(0)
|
| 660 |
+
|
| 661 |
+
x1, x2 = x[0], x[1]
|
| 662 |
+
return x1, x2
|
| 663 |
+
|
| 664 |
+
def populate_kv_cache(self, layer: AttentionLayer, key: torch.Tensor,
|
| 665 |
+
value: torch.Tensor, kv_cache: torch.Tensor,
|
| 666 |
+
attn_metadata: DifferentialFlashAttentionMetadata):
|
| 667 |
+
if kv_cache.numel() > 0 and key is not None and value is not None:
|
| 668 |
+
updated_slot_mapping = attn_metadata.slot_mapping
|
| 669 |
+
torch.ops._C_cache_ops.reshape_and_cache_flash(
|
| 670 |
+
key,
|
| 671 |
+
value,
|
| 672 |
+
kv_cache[0],
|
| 673 |
+
kv_cache[1],
|
| 674 |
+
updated_slot_mapping.flatten(),
|
| 675 |
+
self.kv_cache_dtype,
|
| 676 |
+
layer._k_scale,
|
| 677 |
+
layer._v_scale,
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
def forward_generate_kv_cache(
|
| 681 |
+
self, query: torch.Tensor, key: Optional[torch.Tensor],
|
| 682 |
+
value: Optional[torch.Tensor], k_cache: torch.Tensor,
|
| 683 |
+
v_cache: torch.Tensor,
|
| 684 |
+
attn_metadata: DifferentialFlashAttentionMetadata) -> torch.Tensor:
|
| 685 |
+
|
| 686 |
+
head_size = self.head_size
|
| 687 |
+
num_heads = self.num_heads // 2
|
| 688 |
+
num_kv_heads = self.num_kv_heads // 2
|
| 689 |
+
|
| 690 |
+
query = query.view(-1, num_heads, head_size)
|
| 691 |
+
if key is not None:
|
| 692 |
+
assert value is not None
|
| 693 |
+
key = key.view(-1, num_kv_heads, head_size)
|
| 694 |
+
value = value.view(-1, num_kv_heads, head_size)
|
| 695 |
+
else:
|
| 696 |
+
assert value is None
|
| 697 |
+
|
| 698 |
+
num_prefill_tokens = attn_metadata.num_prefill_tokens
|
| 699 |
+
num_decode_tokens = attn_metadata.num_decode_tokens
|
| 700 |
+
assert key.shape[
|
| 701 |
+
0] == num_prefill_tokens + num_decode_tokens, "key shape mismatch"
|
| 702 |
+
assert value.shape[
|
| 703 |
+
0] == num_prefill_tokens + num_decode_tokens, "value shape mismatch"
|
| 704 |
+
|
| 705 |
+
output = torch.empty_like(query)
|
| 706 |
+
# Query for decode. KV is not needed because it is already cached.
|
| 707 |
+
decode_query = query[num_prefill_tokens:]
|
| 708 |
+
# QKV for prefill.
|
| 709 |
+
query = query[:num_prefill_tokens]
|
| 710 |
+
if key is not None and value is not None:
|
| 711 |
+
key = key[:num_prefill_tokens]
|
| 712 |
+
value = value[:num_prefill_tokens]
|
| 713 |
+
|
| 714 |
+
assert query.shape[0] == num_prefill_tokens, "query shape mismatch"
|
| 715 |
+
assert decode_query.shape[
|
| 716 |
+
0] == num_decode_tokens, "decode query shape mismatch"
|
| 717 |
+
|
| 718 |
+
if prefill_meta := attn_metadata.prefill_metadata:
|
| 719 |
+
# Prompt run.
|
| 720 |
+
if k_cache.numel() == 0 \
|
| 721 |
+
or prefill_meta.block_tables is None \
|
| 722 |
+
or prefill_meta.block_tables.numel() == 0:
|
| 723 |
+
# normal attention
|
| 724 |
+
prefill_output = flash_attn_varlen_func(
|
| 725 |
+
q=query,
|
| 726 |
+
k=key,
|
| 727 |
+
v=value,
|
| 728 |
+
cu_seqlens_q=prefill_meta.seq_start_loc,
|
| 729 |
+
cu_seqlens_k=prefill_meta.seq_start_loc,
|
| 730 |
+
max_seqlen_q=prefill_meta.max_prefill_seq_len,
|
| 731 |
+
max_seqlen_k=prefill_meta.max_prefill_seq_len,
|
| 732 |
+
softmax_scale=self.scale,
|
| 733 |
+
causal=True,
|
| 734 |
+
window_size=self.sliding_window,
|
| 735 |
+
alibi_slopes=self.alibi_slopes,
|
| 736 |
+
softcap=self.logits_soft_cap,
|
| 737 |
+
)
|
| 738 |
+
assert prefill_output.shape == output[:
|
| 739 |
+
num_prefill_tokens].shape
|
| 740 |
+
output[:num_prefill_tokens] = prefill_output
|
| 741 |
+
else:
|
| 742 |
+
raise Exception("prefix caching not supported")
|
| 743 |
+
|
| 744 |
+
if decode_meta := attn_metadata.decode_metadata:
|
| 745 |
+
block_tables_arg = decode_meta.block_tables
|
| 746 |
+
try:
|
| 747 |
+
output[num_prefill_tokens:] = flash_attn_with_kvcache(
|
| 748 |
+
q=decode_query.unsqueeze(1),
|
| 749 |
+
k_cache=k_cache,
|
| 750 |
+
v_cache=v_cache,
|
| 751 |
+
block_table=block_tables_arg,
|
| 752 |
+
cache_seqlens=decode_meta.seq_lens_tensor,
|
| 753 |
+
softmax_scale=self.scale,
|
| 754 |
+
causal=True,
|
| 755 |
+
window_size=self.sliding_window,
|
| 756 |
+
alibi_slopes=self.alibi_slopes,
|
| 757 |
+
softcap=self.logits_soft_cap,
|
| 758 |
+
).squeeze(1)
|
| 759 |
+
except Exception as e:
|
| 760 |
+
logger.error("Error in PagedAttention.forward_decode: %s",
|
| 761 |
+
str(e))
|
| 762 |
+
raise e
|
| 763 |
+
|
| 764 |
+
# Reshape the output tensor.
|
| 765 |
+
return output.view(-1, num_heads, head_size)
|
| 766 |
+
|
| 767 |
+
def forward_with_kv_cache_only(
|
| 768 |
+
self,
|
| 769 |
+
query: torch.Tensor,
|
| 770 |
+
k_cache: torch.Tensor,
|
| 771 |
+
v_cache: torch.Tensor,
|
| 772 |
+
attn_metadata: DifferentialFlashAttentionMetadata,
|
| 773 |
+
):
|
| 774 |
+
if not attn_metadata.decode_metadata:
|
| 775 |
+
block_tables_arg = attn_metadata.cross_layer_shared_block_tables
|
| 776 |
+
else:
|
| 777 |
+
block_tables_arg = attn_metadata.block_tables
|
| 778 |
+
|
| 779 |
+
output = flash_attn_with_kvcache(
|
| 780 |
+
q=query.unsqueeze(1),
|
| 781 |
+
k_cache=k_cache,
|
| 782 |
+
v_cache=v_cache,
|
| 783 |
+
block_table=block_tables_arg,
|
| 784 |
+
cache_seqlens=attn_metadata.seq_lens_tensor,
|
| 785 |
+
softmax_scale=self.scale,
|
| 786 |
+
causal=True,
|
| 787 |
+
window_size=self.sliding_window,
|
| 788 |
+
alibi_slopes=self.alibi_slopes,
|
| 789 |
+
softcap=self.logits_soft_cap,
|
| 790 |
+
).squeeze(1)
|
| 791 |
+
return output
|
| 792 |
+
|
| 793 |
+
def forward(
|
| 794 |
+
self,
|
| 795 |
+
layer: AttentionLayer,
|
| 796 |
+
q: torch.Tensor,
|
| 797 |
+
k: torch.Tensor,
|
| 798 |
+
v: torch.Tensor,
|
| 799 |
+
kv_cache: torch.Tensor,
|
| 800 |
+
attn_metadata: DifferentialFlashAttentionMetadata,
|
| 801 |
+
output: Optional[torch.Tensor] = None,
|
| 802 |
+
output_scale: Optional[torch.Tensor] = None,
|
| 803 |
+
) -> torch.Tensor:
|
| 804 |
+
"""Forward pass with FlashAttention.
|
| 805 |
+
|
| 806 |
+
Args:
|
| 807 |
+
query: shape = [num_tokens, num_heads, head_size]
|
| 808 |
+
key: shape = [num_tokens, num_kv_heads, head_size]
|
| 809 |
+
value: shape = [num_tokens, num_kv_heads, head_size]
|
| 810 |
+
output: shape = [num_tokens, num_heads, head_size]
|
| 811 |
+
kv_cache = [2, num_blocks, block_size, num_kv_heads, head_size]
|
| 812 |
+
NOTE: kv_cache will be an empty tensor with shape [0]
|
| 813 |
+
for profiling run.
|
| 814 |
+
attn_metadata: Metadata for attention.
|
| 815 |
+
NOTE: It in-place updates the output tensor.
|
| 816 |
+
NOTE: FP8 quantization, flash-attn expect the size of
|
| 817 |
+
{q,k,v}_descale to be (num_sequences, num_kv_heads).
|
| 818 |
+
We use torch's .expand() to avoid duplicating values
|
| 819 |
+
"""
|
| 820 |
+
if self.lambda_full is None:
|
| 821 |
+
self.lambda_init = self.differential_flash_attention_config[
|
| 822 |
+
"lambda_init"]
|
| 823 |
+
lambda_q1 = self.differential_flash_attention_config["lambda_q1"]
|
| 824 |
+
lambda_k1 = self.differential_flash_attention_config["lambda_k1"]
|
| 825 |
+
lambda_q2 = self.differential_flash_attention_config["lambda_q2"]
|
| 826 |
+
lambda_k2 = self.differential_flash_attention_config["lambda_k2"]
|
| 827 |
+
lambda_1 = torch.exp(
|
| 828 |
+
torch.sum(lambda_q1 * lambda_k1, dim=-1).float()).type_as(q)
|
| 829 |
+
lambda_2 = torch.exp(
|
| 830 |
+
torch.sum(lambda_q2 * lambda_k2, dim=-1).float()).type_as(q)
|
| 831 |
+
self.lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
| 832 |
+
|
| 833 |
+
if not self.used_shared_kv_cache: # need to generate kv-cache
|
| 834 |
+
q = q.view(-1, self.num_heads, self.head_size)
|
| 835 |
+
k = k.view(-1, self.num_kv_heads, self.head_size)
|
| 836 |
+
v = v.view(-1, self.num_kv_heads, self.head_size)
|
| 837 |
+
|
| 838 |
+
q1, q2 = self.split_heads(q)
|
| 839 |
+
k1, k2 = self.split_heads(k)
|
| 840 |
+
v1, v2 = self.split_heads(v)
|
| 841 |
+
|
| 842 |
+
# kv_cache shape is (2, 2, num_blocks, block_size, num_kv_heads // 2, head_size) # noqa: E501
|
| 843 |
+
# Split by half along the first dimension.
|
| 844 |
+
kv_cache1, kv_cache2 = self.split_kv_cache(kv_cache)
|
| 845 |
+
assert kv_cache1.is_contiguous(), "kv_cache1 is not contiguous"
|
| 846 |
+
assert kv_cache2.is_contiguous(), "kv_cache2 is not contiguous"
|
| 847 |
+
|
| 848 |
+
if kv_cache1.numel() != 0:
|
| 849 |
+
self.populate_kv_cache(layer, k1, v1, kv_cache1, attn_metadata)
|
| 850 |
+
self.populate_kv_cache(layer, k2, v2, kv_cache2, attn_metadata)
|
| 851 |
+
|
| 852 |
+
key_cache1, value_cache1 = self.split_kv_cache(kv_cache1)
|
| 853 |
+
key_cache2, value_cache2 = self.split_kv_cache(kv_cache2)
|
| 854 |
+
else:
|
| 855 |
+
key_cache1, value_cache1 = torch.empty(0), torch.empty(0)
|
| 856 |
+
key_cache2, value_cache2 = torch.empty(0), torch.empty(0)
|
| 857 |
+
attn11 = self.forward_generate_kv_cache(q1, k1, v1, key_cache1,
|
| 858 |
+
value_cache1,
|
| 859 |
+
attn_metadata)
|
| 860 |
+
attn12 = self.forward_generate_kv_cache(q1, k1, v2, key_cache1,
|
| 861 |
+
value_cache2,
|
| 862 |
+
attn_metadata)
|
| 863 |
+
attn11 = attn11.view(q1.shape)
|
| 864 |
+
attn12 = attn12.view(q1.shape)
|
| 865 |
+
attn1 = torch.cat([attn11, attn12], dim=-1)
|
| 866 |
+
|
| 867 |
+
attn21 = self.forward_generate_kv_cache(q2, k2, v1, key_cache2,
|
| 868 |
+
value_cache1,
|
| 869 |
+
attn_metadata)
|
| 870 |
+
attn22 = self.forward_generate_kv_cache(q2, k2, v2, key_cache2,
|
| 871 |
+
value_cache2,
|
| 872 |
+
attn_metadata)
|
| 873 |
+
attn21 = attn21.view(q2.shape)
|
| 874 |
+
attn22 = attn22.view(q2.shape)
|
| 875 |
+
attn2 = torch.cat([attn21, attn22], dim=-1)
|
| 876 |
+
|
| 877 |
+
attn = attn1 - self.lambda_full * attn2
|
| 878 |
+
# attn shape (-1, self.num_heads // 2, 2 * self.head_dim)
|
| 879 |
+
attn = self.subln(attn)
|
| 880 |
+
attn = attn * (1 - self.lambda_init)
|
| 881 |
+
# reshape back to 2 * num_head
|
| 882 |
+
attn_output = rearrange(attn,
|
| 883 |
+
"... H (two D) -> ... (H two) D",
|
| 884 |
+
two=2)
|
| 885 |
+
|
| 886 |
+
else: # reuse the kv cache, full attention
|
| 887 |
+
q = q.view(-1, self.num_heads, self.head_size)
|
| 888 |
+
q1, q2 = self.split_heads(q)
|
| 889 |
+
# kv_cache shape is (2, num_blocks, block_size, num_kv_heads, head_size) # noqa: E501
|
| 890 |
+
kv_cache1, kv_cache2 = self.split_kv_cache(kv_cache)
|
| 891 |
+
key_cache1, value_cache1 = kv_cache1[0], kv_cache1[1]
|
| 892 |
+
key_cache2, value_cache2 = kv_cache2[0], kv_cache2[1]
|
| 893 |
+
|
| 894 |
+
attn11 = self.forward_with_kv_cache_only(q1, key_cache1,
|
| 895 |
+
value_cache1,
|
| 896 |
+
attn_metadata)
|
| 897 |
+
attn12 = self.forward_with_kv_cache_only(q1, key_cache1,
|
| 898 |
+
value_cache2,
|
| 899 |
+
attn_metadata)
|
| 900 |
+
attn11 = attn11.view(q1.shape)
|
| 901 |
+
attn12 = attn12.view(q1.shape)
|
| 902 |
+
attn1 = torch.cat([attn11, attn12], dim=-1)
|
| 903 |
+
|
| 904 |
+
attn21 = self.forward_with_kv_cache_only(q2, key_cache2,
|
| 905 |
+
value_cache1,
|
| 906 |
+
attn_metadata)
|
| 907 |
+
attn22 = self.forward_with_kv_cache_only(q2, key_cache2,
|
| 908 |
+
value_cache2,
|
| 909 |
+
attn_metadata)
|
| 910 |
+
attn21 = attn21.view(q2.shape)
|
| 911 |
+
attn22 = attn22.view(q2.shape)
|
| 912 |
+
attn2 = torch.cat([attn21, attn22], dim=-1)
|
| 913 |
+
|
| 914 |
+
attn = attn1 - self.lambda_full * attn2
|
| 915 |
+
attn = self.subln(attn)
|
| 916 |
+
attn = attn * (1 - self.lambda_init)
|
| 917 |
+
# reshape back to 2 * num_head
|
| 918 |
+
attn_output = rearrange(attn,
|
| 919 |
+
"... H (two D) -> ... (H two) D",
|
| 920 |
+
two=2)
|
| 921 |
+
attn_output = attn_output.view(-1, self.num_heads * self.head_size)
|
| 922 |
+
return attn_output
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/flash_attn.py
ADDED
|
@@ -0,0 +1,931 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
"""Attention layer with FlashAttention."""
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from itertools import accumulate
|
| 7 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Type
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from vllm import _custom_ops as ops
|
| 12 |
+
# yapf conflicts with isort for this block
|
| 13 |
+
# yapf: disable
|
| 14 |
+
from vllm.attention.backends.abstract import (AttentionBackend, AttentionImpl,
|
| 15 |
+
AttentionLayer,
|
| 16 |
+
AttentionMetadata,
|
| 17 |
+
AttentionMetadataBuilder,
|
| 18 |
+
AttentionType,
|
| 19 |
+
is_quantized_kv_cache)
|
| 20 |
+
# yapf: enable
|
| 21 |
+
from vllm.attention.backends.utils import (
|
| 22 |
+
PAD_SLOT_ID, CommonAttentionState, compute_slot_mapping,
|
| 23 |
+
compute_slot_mapping_start_idx, get_num_prefill_decode_query_kv_tokens,
|
| 24 |
+
get_seq_len_block_table_args, is_all_cross_attn_metadata_set,
|
| 25 |
+
is_all_encoder_attn_metadata_set, is_block_tables_empty)
|
| 26 |
+
from vllm.attention.utils.fa_utils import (flash_attn_supports_fp8,
|
| 27 |
+
get_flash_attn_version)
|
| 28 |
+
from vllm.logger import init_logger
|
| 29 |
+
from vllm.multimodal import MultiModalPlaceholderMap
|
| 30 |
+
from vllm.utils import async_tensor_h2d, make_tensor_with_pad
|
| 31 |
+
from vllm.vllm_flash_attn import (flash_attn_varlen_func,
|
| 32 |
+
flash_attn_with_kvcache)
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from vllm.worker.model_runner import ModelInputForGPUBuilder
|
| 36 |
+
|
| 37 |
+
logger = init_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class FlashAttentionBackend(AttentionBackend):
|
| 41 |
+
|
| 42 |
+
accept_output_buffer: bool = True
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def get_supported_head_sizes() -> List[int]:
|
| 46 |
+
return [32, 64, 96, 128, 160, 192, 224, 256]
|
| 47 |
+
|
| 48 |
+
@staticmethod
|
| 49 |
+
def get_name() -> str:
|
| 50 |
+
return "FLASH_ATTN"
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def get_impl_cls() -> Type["FlashAttentionImpl"]:
|
| 54 |
+
return FlashAttentionImpl
|
| 55 |
+
|
| 56 |
+
@staticmethod
|
| 57 |
+
def get_metadata_cls() -> Type["AttentionMetadata"]:
|
| 58 |
+
return FlashAttentionMetadata
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def get_builder_cls() -> Type["FlashAttentionMetadataBuilder"]:
|
| 62 |
+
return FlashAttentionMetadataBuilder
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def get_state_cls() -> Type["CommonAttentionState"]:
|
| 66 |
+
return CommonAttentionState
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
def get_kv_cache_shape(
|
| 70 |
+
num_blocks: int,
|
| 71 |
+
block_size: int,
|
| 72 |
+
num_kv_heads: int,
|
| 73 |
+
head_size: int,
|
| 74 |
+
) -> Tuple[int, ...]:
|
| 75 |
+
if block_size % 16 != 0:
|
| 76 |
+
raise ValueError("Block size must be a multiple of 16.")
|
| 77 |
+
return (2, num_blocks, block_size, num_kv_heads, head_size)
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def swap_blocks(
|
| 81 |
+
src_kv_cache: torch.Tensor,
|
| 82 |
+
dst_kv_cache: torch.Tensor,
|
| 83 |
+
src_to_dst: torch.Tensor,
|
| 84 |
+
) -> None:
|
| 85 |
+
src_key_cache = src_kv_cache[0]
|
| 86 |
+
dst_key_cache = dst_kv_cache[0]
|
| 87 |
+
ops.swap_blocks(src_key_cache, dst_key_cache, src_to_dst)
|
| 88 |
+
src_value_cache = src_kv_cache[1]
|
| 89 |
+
dst_value_cache = dst_kv_cache[1]
|
| 90 |
+
ops.swap_blocks(src_value_cache, dst_value_cache, src_to_dst)
|
| 91 |
+
|
| 92 |
+
@staticmethod
|
| 93 |
+
def copy_blocks(
|
| 94 |
+
kv_caches: List[torch.Tensor],
|
| 95 |
+
src_to_dists: torch.Tensor,
|
| 96 |
+
) -> None:
|
| 97 |
+
key_caches = [kv_cache[0] for kv_cache in kv_caches]
|
| 98 |
+
value_caches = [kv_cache[1] for kv_cache in kv_caches]
|
| 99 |
+
|
| 100 |
+
ops.copy_blocks(key_caches, value_caches, src_to_dists)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class FlashAttentionMetadata(AttentionMetadata):
|
| 105 |
+
"""Metadata for FlashAttentionBackend.
|
| 106 |
+
|
| 107 |
+
NOTE: Any python object stored here is not updated when it is
|
| 108 |
+
cuda-graph replayed. If you have values that need to be changed
|
| 109 |
+
dynamically, it should be stored in tensor. The tensor has to be
|
| 110 |
+
updated from `CUDAGraphRunner.forward` API.
|
| 111 |
+
"""
|
| 112 |
+
# (batch_size,). The sequence length per sequence. Sequence length means
|
| 113 |
+
# the computed tokens + new tokens None if it is a decoding.
|
| 114 |
+
seq_lens: Optional[List[int]]
|
| 115 |
+
# seq_lens stored as a tensor.
|
| 116 |
+
seq_lens_tensor: Optional[torch.Tensor]
|
| 117 |
+
|
| 118 |
+
# NOTE(sang): Definition of context_len, query_len, and seq_len.
|
| 119 |
+
# |---------- N-1 iteration --------|
|
| 120 |
+
# |---------------- N iteration ---------------------|
|
| 121 |
+
# |- tokenA -|......................|-- newTokens ---|
|
| 122 |
+
# |---------- context_len ----------|
|
| 123 |
+
# |-------------------- seq_len ---------------------|
|
| 124 |
+
# |-- query_len ---|
|
| 125 |
+
|
| 126 |
+
# Maximum sequence length among prefill batch. 0 if there are decoding
|
| 127 |
+
# requests only.
|
| 128 |
+
max_prefill_seq_len: int
|
| 129 |
+
# Maximum sequence length among decode batch. 0 if there are prefill
|
| 130 |
+
# requests only.
|
| 131 |
+
max_decode_seq_len: int
|
| 132 |
+
# (batch_size,) A tensor of context lengths (tokens that are computed
|
| 133 |
+
# so far).
|
| 134 |
+
context_lens_tensor: Optional[torch.Tensor]
|
| 135 |
+
|
| 136 |
+
# (batch_size, max_blocks_per_seq).
|
| 137 |
+
# Block addresses per sequence. (Seq id -> list of physical block)
|
| 138 |
+
# E.g., [0, 1, 2] means tokens are stored in 0th, 1st, and 2nd blocks
|
| 139 |
+
# in the kv cache. Each block can contain up to block_size tokens.
|
| 140 |
+
# 2nd dimensions are padded up to max_blocks_per_seq if it is cuda-graph
|
| 141 |
+
# captured.
|
| 142 |
+
block_tables: Optional[torch.Tensor]
|
| 143 |
+
|
| 144 |
+
# Whether or not if cuda graph is enabled.
|
| 145 |
+
# Cuda-graph is currently enabled for decoding only.
|
| 146 |
+
# TODO(woosuk): Move `use_cuda_graph` out since it's unrelated to attention.
|
| 147 |
+
|
| 148 |
+
use_cuda_graph: bool
|
| 149 |
+
|
| 150 |
+
# Maximum query length in the batch.
|
| 151 |
+
max_query_len: Optional[int] = None
|
| 152 |
+
|
| 153 |
+
# Max number of query tokens among request in the batch.
|
| 154 |
+
max_decode_query_len: Optional[int] = None
|
| 155 |
+
|
| 156 |
+
# (batch_size + 1,). The cumulative subquery lengths of the sequences in
|
| 157 |
+
# the batch, used to index into subquery. E.g., if the subquery length
|
| 158 |
+
# is [4, 6], it is [0, 4, 10].
|
| 159 |
+
query_start_loc: Optional[torch.Tensor] = None
|
| 160 |
+
# (batch_size + 1,). The cumulative sequence lengths of the sequences in
|
| 161 |
+
# the batch, used to index into sequence. E.g., if the sequence length is
|
| 162 |
+
# [4, 6], it is [0, 4, 10].
|
| 163 |
+
seq_start_loc: Optional[torch.Tensor] = None
|
| 164 |
+
|
| 165 |
+
_cached_prefill_metadata: Optional["FlashAttentionMetadata"] = None
|
| 166 |
+
_cached_decode_metadata: Optional["FlashAttentionMetadata"] = None
|
| 167 |
+
|
| 168 |
+
# Begin encoder attn & enc/dec cross-attn fields...
|
| 169 |
+
|
| 170 |
+
# Encoder sequence lengths representation
|
| 171 |
+
encoder_seq_lens: Optional[List[int]] = None
|
| 172 |
+
encoder_seq_lens_tensor: Optional[torch.Tensor] = None
|
| 173 |
+
# (batch_size + 1,). The cumulative sequence lengths of the sequences in
|
| 174 |
+
# the batch, used to index into sequence. E.g., if the sequence length is
|
| 175 |
+
# [4, 6], it is [0, 4, 10].
|
| 176 |
+
encoder_seq_start_loc: Optional[torch.Tensor] = None
|
| 177 |
+
# Maximum sequence length among encoder sequences
|
| 178 |
+
max_encoder_seq_len: Optional[int] = None
|
| 179 |
+
# Number of tokens input to encoder
|
| 180 |
+
num_encoder_tokens: Optional[int] = None
|
| 181 |
+
|
| 182 |
+
# Cross-attention memory-mapping data structures: slot mapping
|
| 183 |
+
# and block tables
|
| 184 |
+
cross_slot_mapping: Optional[torch.Tensor] = None
|
| 185 |
+
cross_block_tables: Optional[torch.Tensor] = None
|
| 186 |
+
|
| 187 |
+
@property
|
| 188 |
+
def is_all_encoder_attn_metadata_set(self):
|
| 189 |
+
'''
|
| 190 |
+
All attention metadata required for encoder attention is set.
|
| 191 |
+
'''
|
| 192 |
+
return is_all_encoder_attn_metadata_set(self)
|
| 193 |
+
|
| 194 |
+
@property
|
| 195 |
+
def is_all_cross_attn_metadata_set(self):
|
| 196 |
+
'''
|
| 197 |
+
All attention metadata required for enc/dec cross-attention is set.
|
| 198 |
+
|
| 199 |
+
Superset of encoder attention required metadata.
|
| 200 |
+
'''
|
| 201 |
+
return is_all_cross_attn_metadata_set(self)
|
| 202 |
+
|
| 203 |
+
@property
|
| 204 |
+
def prefill_metadata(self) -> Optional["FlashAttentionMetadata"]:
|
| 205 |
+
if self.num_prefills == 0:
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
if self._cached_prefill_metadata is not None:
|
| 209 |
+
return self._cached_prefill_metadata
|
| 210 |
+
|
| 211 |
+
assert ((self.seq_lens is not None)
|
| 212 |
+
or (self.encoder_seq_lens is not None))
|
| 213 |
+
assert ((self.seq_lens_tensor is not None)
|
| 214 |
+
or (self.encoder_seq_lens_tensor is not None))
|
| 215 |
+
|
| 216 |
+
# Compute some attn_metadata fields which default to None
|
| 217 |
+
query_start_loc = (None if self.query_start_loc is None else
|
| 218 |
+
self.query_start_loc[:self.num_prefills + 1])
|
| 219 |
+
slot_mapping = (None if self.slot_mapping is None else
|
| 220 |
+
self.slot_mapping[:self.num_prefill_tokens])
|
| 221 |
+
seq_lens = (None if self.seq_lens is None else
|
| 222 |
+
self.seq_lens[:self.num_prefills])
|
| 223 |
+
seq_lens_tensor = (None if self.seq_lens_tensor is None else
|
| 224 |
+
self.seq_lens_tensor[:self.num_prefills])
|
| 225 |
+
seq_start_loc = (None if self.seq_start_loc is None else
|
| 226 |
+
self.seq_start_loc[:self.num_prefills + 1])
|
| 227 |
+
context_lens_tensor = (None if self.context_lens_tensor is None else
|
| 228 |
+
self.context_lens_tensor[:self.num_prefills])
|
| 229 |
+
block_tables = (None if self.block_tables is None else
|
| 230 |
+
self.block_tables[:self.num_prefills])
|
| 231 |
+
|
| 232 |
+
self._cached_prefill_metadata = FlashAttentionMetadata(
|
| 233 |
+
num_prefills=self.num_prefills,
|
| 234 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 235 |
+
num_decode_tokens=0,
|
| 236 |
+
slot_mapping=slot_mapping,
|
| 237 |
+
multi_modal_placeholder_index_maps=self.
|
| 238 |
+
multi_modal_placeholder_index_maps,
|
| 239 |
+
enable_kv_scales_calculation=self.enable_kv_scales_calculation,
|
| 240 |
+
seq_lens=seq_lens,
|
| 241 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 242 |
+
max_query_len=self.max_query_len,
|
| 243 |
+
max_prefill_seq_len=self.max_prefill_seq_len,
|
| 244 |
+
max_decode_query_len=0,
|
| 245 |
+
max_decode_seq_len=0,
|
| 246 |
+
query_start_loc=query_start_loc,
|
| 247 |
+
seq_start_loc=seq_start_loc,
|
| 248 |
+
context_lens_tensor=context_lens_tensor,
|
| 249 |
+
block_tables=block_tables,
|
| 250 |
+
use_cuda_graph=False,
|
| 251 |
+
# Begin encoder & cross attn fields below...
|
| 252 |
+
encoder_seq_lens=self.encoder_seq_lens,
|
| 253 |
+
encoder_seq_lens_tensor=self.encoder_seq_lens_tensor,
|
| 254 |
+
encoder_seq_start_loc=self.encoder_seq_start_loc,
|
| 255 |
+
max_encoder_seq_len=self.max_encoder_seq_len,
|
| 256 |
+
cross_slot_mapping=self.cross_slot_mapping,
|
| 257 |
+
cross_block_tables=self.cross_block_tables)
|
| 258 |
+
return self._cached_prefill_metadata
|
| 259 |
+
|
| 260 |
+
@property
|
| 261 |
+
def decode_metadata(self) -> Optional["FlashAttentionMetadata"]:
|
| 262 |
+
if self.num_decode_tokens == 0:
|
| 263 |
+
return None
|
| 264 |
+
|
| 265 |
+
if self._cached_decode_metadata is not None:
|
| 266 |
+
return self._cached_decode_metadata
|
| 267 |
+
assert ((self.seq_lens_tensor is not None)
|
| 268 |
+
or (self.encoder_seq_lens_tensor is not None))
|
| 269 |
+
|
| 270 |
+
# Compute some attn_metadata fields which default to None
|
| 271 |
+
slot_mapping = (None if self.slot_mapping is None else
|
| 272 |
+
self.slot_mapping[self.num_prefill_tokens:])
|
| 273 |
+
seq_lens_tensor = (None if self.seq_lens_tensor is None else
|
| 274 |
+
self.seq_lens_tensor[self.num_prefills:])
|
| 275 |
+
block_tables = (None if self.block_tables is None else
|
| 276 |
+
self.block_tables[self.num_prefills:])
|
| 277 |
+
|
| 278 |
+
self._cached_decode_metadata = FlashAttentionMetadata(
|
| 279 |
+
num_prefills=0,
|
| 280 |
+
num_prefill_tokens=0,
|
| 281 |
+
num_decode_tokens=self.num_decode_tokens,
|
| 282 |
+
slot_mapping=slot_mapping,
|
| 283 |
+
multi_modal_placeholder_index_maps=None,
|
| 284 |
+
enable_kv_scales_calculation=True,
|
| 285 |
+
seq_lens=None,
|
| 286 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 287 |
+
max_decode_query_len=self.max_decode_query_len,
|
| 288 |
+
max_query_len=self.max_query_len,
|
| 289 |
+
max_prefill_seq_len=0,
|
| 290 |
+
max_decode_seq_len=self.max_decode_seq_len,
|
| 291 |
+
# Batch may be composed of prefill|decodes, adjust query start
|
| 292 |
+
# indices to refer to the start of decodes. E.g.
|
| 293 |
+
# in tokens:[3 prefills|6 decodes], query_start_loc=[3,9] => [0,6].
|
| 294 |
+
query_start_loc=(self.query_start_loc[self.num_prefills:] -
|
| 295 |
+
self.query_start_loc[self.num_prefills])
|
| 296 |
+
if self.query_start_loc is not None else None,
|
| 297 |
+
seq_start_loc=self.seq_start_loc[self.num_prefills:]
|
| 298 |
+
if self.seq_start_loc is not None else None,
|
| 299 |
+
context_lens_tensor=None,
|
| 300 |
+
block_tables=block_tables,
|
| 301 |
+
use_cuda_graph=self.use_cuda_graph,
|
| 302 |
+
# Begin encoder & cross attn fields below...
|
| 303 |
+
encoder_seq_lens=self.encoder_seq_lens,
|
| 304 |
+
encoder_seq_lens_tensor=self.encoder_seq_lens_tensor,
|
| 305 |
+
encoder_seq_start_loc=self.encoder_seq_start_loc,
|
| 306 |
+
max_encoder_seq_len=self.max_encoder_seq_len,
|
| 307 |
+
cross_slot_mapping=self.cross_slot_mapping,
|
| 308 |
+
cross_block_tables=self.cross_block_tables)
|
| 309 |
+
return self._cached_decode_metadata
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class FlashAttentionMetadataBuilder(
|
| 313 |
+
AttentionMetadataBuilder[FlashAttentionMetadata]):
|
| 314 |
+
|
| 315 |
+
def __init__(self, input_builder: "ModelInputForGPUBuilder"):
|
| 316 |
+
self.input_builder = input_builder
|
| 317 |
+
self.runner = input_builder.runner
|
| 318 |
+
self.sliding_window = input_builder.sliding_window
|
| 319 |
+
self.block_size = input_builder.block_size
|
| 320 |
+
|
| 321 |
+
def prepare(self):
|
| 322 |
+
self.slot_mapping: List[int] = []
|
| 323 |
+
self.prefill_seq_lens: List[int] = []
|
| 324 |
+
self.context_lens: List[int] = []
|
| 325 |
+
self.block_tables: List[List[int]] = []
|
| 326 |
+
self.curr_seq_lens: List[int] = []
|
| 327 |
+
self.multimodal_placeholder_maps: Dict[
|
| 328 |
+
str,
|
| 329 |
+
MultiModalPlaceholderMap] = defaultdict(MultiModalPlaceholderMap)
|
| 330 |
+
self.num_prefills = 0
|
| 331 |
+
self.num_prefill_tokens = 0
|
| 332 |
+
self.num_decode_tokens = 0
|
| 333 |
+
self.has_prefix_cache_hit = False
|
| 334 |
+
|
| 335 |
+
def _add_seq_group(
|
| 336 |
+
self, inter_data: "ModelInputForGPUBuilder.InterDataForSeqGroup",
|
| 337 |
+
chunked_prefill_enabled: bool, prefix_cache_hit: bool):
|
| 338 |
+
"""Add a sequence group to the metadata. Specifically update/append
|
| 339 |
+
1. context length.
|
| 340 |
+
2. block table.
|
| 341 |
+
3. slot mapping.
|
| 342 |
+
"""
|
| 343 |
+
is_prompt = inter_data.is_prompt
|
| 344 |
+
block_tables = inter_data.block_tables
|
| 345 |
+
|
| 346 |
+
for (seq_id, token_len, seq_len, curr_seq_len, query_len, context_len,
|
| 347 |
+
curr_sliding_window_block) in zip(
|
| 348 |
+
inter_data.seq_ids, [len(t) for t in inter_data.input_tokens],
|
| 349 |
+
inter_data.orig_seq_lens, inter_data.seq_lens,
|
| 350 |
+
inter_data.query_lens, inter_data.context_lens,
|
| 351 |
+
inter_data.curr_sliding_window_blocks):
|
| 352 |
+
self.context_lens.append(context_len)
|
| 353 |
+
|
| 354 |
+
if is_prompt:
|
| 355 |
+
mm_maps = inter_data.multi_modal_placeholder_maps
|
| 356 |
+
if mm_maps:
|
| 357 |
+
for modality, placeholders in mm_maps.items():
|
| 358 |
+
self.multimodal_placeholder_maps[modality].extend(
|
| 359 |
+
placeholders)
|
| 360 |
+
|
| 361 |
+
self.num_prefills += 1
|
| 362 |
+
self.num_prefill_tokens += token_len
|
| 363 |
+
self.prefill_seq_lens.append(seq_len)
|
| 364 |
+
else:
|
| 365 |
+
self.num_decode_tokens += query_len
|
| 366 |
+
self.curr_seq_lens.append(curr_seq_len)
|
| 367 |
+
|
| 368 |
+
# Compute block table.
|
| 369 |
+
# TODO(sang): Combine chunked prefill and prefix caching by
|
| 370 |
+
# only allowing multiple of block_size chunk size.
|
| 371 |
+
# NOTE: This only works for oooooooxxx style attention.
|
| 372 |
+
block_table = []
|
| 373 |
+
if prefix_cache_hit:
|
| 374 |
+
# NOTE(woosuk): For flash-attn, the block table should
|
| 375 |
+
# include the entries for the incoming prefill tokens.
|
| 376 |
+
block_table = block_tables[seq_id]
|
| 377 |
+
elif ((chunked_prefill_enabled or not is_prompt)
|
| 378 |
+
and block_tables is not None):
|
| 379 |
+
if curr_sliding_window_block == 0:
|
| 380 |
+
block_table = block_tables[seq_id]
|
| 381 |
+
else:
|
| 382 |
+
block_table = block_tables[seq_id][
|
| 383 |
+
-curr_sliding_window_block:]
|
| 384 |
+
self.block_tables.append(block_table)
|
| 385 |
+
|
| 386 |
+
# Compute slot mapping.
|
| 387 |
+
is_profile_run = is_block_tables_empty(block_tables)
|
| 388 |
+
start_idx = compute_slot_mapping_start_idx(is_prompt, query_len,
|
| 389 |
+
context_len,
|
| 390 |
+
self.sliding_window)
|
| 391 |
+
compute_slot_mapping(is_profile_run, self.slot_mapping, seq_id,
|
| 392 |
+
seq_len, context_len, start_idx,
|
| 393 |
+
self.block_size, inter_data.block_tables)
|
| 394 |
+
|
| 395 |
+
def _get_graph_runner_block_tables(
|
| 396 |
+
self, num_seqs: int,
|
| 397 |
+
block_tables: List[List[int]]) -> torch.Tensor:
|
| 398 |
+
# The shape of graph_block_tables is
|
| 399 |
+
# [max batch size, max context len // block size].
|
| 400 |
+
max_batch_size, max_blocks = self.runner.graph_block_tables.shape
|
| 401 |
+
assert max_batch_size >= num_seqs
|
| 402 |
+
|
| 403 |
+
graph_block_tables = self.runner.graph_block_tables[:num_seqs]
|
| 404 |
+
for i, block_table in enumerate(block_tables):
|
| 405 |
+
if block_table:
|
| 406 |
+
num_blocks = len(block_table)
|
| 407 |
+
if num_blocks <= max_blocks:
|
| 408 |
+
graph_block_tables[i, :num_blocks] = block_table
|
| 409 |
+
else:
|
| 410 |
+
# It may be possible to have more blocks allocated due
|
| 411 |
+
# to lookahead slots of multi-step, however, they are
|
| 412 |
+
# not used anyway, so can be safely ignored.
|
| 413 |
+
graph_block_tables[
|
| 414 |
+
i, :max_blocks] = block_table[:max_blocks]
|
| 415 |
+
|
| 416 |
+
return torch.from_numpy(graph_block_tables).to(
|
| 417 |
+
device=self.runner.device, non_blocking=True)
|
| 418 |
+
|
| 419 |
+
def build(self, seq_lens: List[int], query_lens: List[int],
|
| 420 |
+
cuda_graph_pad_size: int, batch_size: int):
|
| 421 |
+
"""Build attention metadata with on-device tensors.
|
| 422 |
+
|
| 423 |
+
Args:
|
| 424 |
+
seq_lens: The maybe padded sequence lengths of the input sequences.
|
| 425 |
+
query_lens: The query lengths of the input sequences.
|
| 426 |
+
cuda_graph_pad_size: The padding size for cuda graph.
|
| 427 |
+
-1 if cuda graph is not used.
|
| 428 |
+
batch_size: The maybe padded batch size.
|
| 429 |
+
"""
|
| 430 |
+
prefix_cache_hit = any([
|
| 431 |
+
inter_data.prefix_cache_hit
|
| 432 |
+
for inter_data in self.input_builder.inter_data_list
|
| 433 |
+
])
|
| 434 |
+
for inter_data in self.input_builder.inter_data_list:
|
| 435 |
+
self._add_seq_group(inter_data,
|
| 436 |
+
self.input_builder.chunked_prefill_enabled,
|
| 437 |
+
prefix_cache_hit)
|
| 438 |
+
|
| 439 |
+
device = self.runner.device
|
| 440 |
+
use_captured_graph = cuda_graph_pad_size != -1
|
| 441 |
+
|
| 442 |
+
max_query_len = max(query_lens)
|
| 443 |
+
decode_query_lens = query_lens[self.num_prefills:]
|
| 444 |
+
if len(decode_query_lens) > 0:
|
| 445 |
+
max_decode_query_len = max(decode_query_lens)
|
| 446 |
+
else:
|
| 447 |
+
max_decode_query_len = 1
|
| 448 |
+
max_prefill_seq_len = max(self.prefill_seq_lens, default=0)
|
| 449 |
+
max_decode_seq_len = max(self.curr_seq_lens, default=0)
|
| 450 |
+
num_decode_tokens = self.num_decode_tokens
|
| 451 |
+
query_start_loc = list(accumulate(query_lens, initial=0))
|
| 452 |
+
seq_start_loc = list(accumulate(seq_lens, initial=0))
|
| 453 |
+
|
| 454 |
+
num_seqs = len(seq_lens)
|
| 455 |
+
if use_captured_graph:
|
| 456 |
+
self.slot_mapping.extend([PAD_SLOT_ID] * cuda_graph_pad_size)
|
| 457 |
+
self.block_tables.extend([] * cuda_graph_pad_size)
|
| 458 |
+
num_decode_tokens = batch_size - self.num_prefill_tokens
|
| 459 |
+
block_tables = self._get_graph_runner_block_tables(
|
| 460 |
+
num_seqs, self.block_tables)
|
| 461 |
+
else:
|
| 462 |
+
block_tables = make_tensor_with_pad(
|
| 463 |
+
self.block_tables,
|
| 464 |
+
pad=0,
|
| 465 |
+
dtype=torch.int,
|
| 466 |
+
device=device,
|
| 467 |
+
)
|
| 468 |
+
assert max_query_len > 0, ("query_lens: {}".format(query_lens))
|
| 469 |
+
|
| 470 |
+
assert device is not None
|
| 471 |
+
context_lens_tensor = async_tensor_h2d(self.context_lens, torch.int,
|
| 472 |
+
device, self.runner.pin_memory)
|
| 473 |
+
seq_lens_tensor = async_tensor_h2d(seq_lens, torch.int, device,
|
| 474 |
+
self.runner.pin_memory)
|
| 475 |
+
slot_mapping_tensor = async_tensor_h2d(self.slot_mapping, torch.long,
|
| 476 |
+
device, self.runner.pin_memory)
|
| 477 |
+
query_start_loc_tensor = async_tensor_h2d(query_start_loc, torch.int32,
|
| 478 |
+
device,
|
| 479 |
+
self.runner.pin_memory)
|
| 480 |
+
seq_start_loc_tensor = async_tensor_h2d(seq_start_loc, torch.int32,
|
| 481 |
+
device, self.runner.pin_memory)
|
| 482 |
+
placeholder_index_maps = {
|
| 483 |
+
modality: placeholder_map.index_map()
|
| 484 |
+
for modality, placeholder_map in
|
| 485 |
+
self.multimodal_placeholder_maps.items()
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
return FlashAttentionMetadata(
|
| 489 |
+
num_prefills=self.num_prefills,
|
| 490 |
+
slot_mapping=slot_mapping_tensor,
|
| 491 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 492 |
+
num_decode_tokens=num_decode_tokens,
|
| 493 |
+
seq_lens=seq_lens,
|
| 494 |
+
multi_modal_placeholder_index_maps=placeholder_index_maps,
|
| 495 |
+
enable_kv_scales_calculation=True,
|
| 496 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 497 |
+
max_query_len=max_query_len,
|
| 498 |
+
max_decode_query_len=max_decode_query_len,
|
| 499 |
+
max_prefill_seq_len=max_prefill_seq_len,
|
| 500 |
+
max_decode_seq_len=max_decode_seq_len,
|
| 501 |
+
query_start_loc=query_start_loc_tensor,
|
| 502 |
+
seq_start_loc=seq_start_loc_tensor,
|
| 503 |
+
context_lens_tensor=context_lens_tensor,
|
| 504 |
+
block_tables=block_tables,
|
| 505 |
+
use_cuda_graph=use_captured_graph,
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
class FlashAttentionImpl(AttentionImpl):
|
| 510 |
+
"""
|
| 511 |
+
If the input tensors contain prompt tokens, the layout is as follows:
|
| 512 |
+
|<--------------- num_prefill_tokens ----------------->|
|
| 513 |
+
|<--prefill_0-->|<--prefill_1-->|...|<--prefill_N-1--->|
|
| 514 |
+
|
| 515 |
+
Otherwise, the layout is as follows:
|
| 516 |
+
|<----------------- num_decode_tokens ------------------>|
|
| 517 |
+
|<--decode_0-->|..........|<--decode_M-1-->|<--padding-->|
|
| 518 |
+
|
| 519 |
+
Generation tokens can contain padding when cuda-graph is used.
|
| 520 |
+
Currently, prompt tokens don't contain any padding.
|
| 521 |
+
|
| 522 |
+
The prompts might have different lengths, while the generation tokens
|
| 523 |
+
always have length 1.
|
| 524 |
+
|
| 525 |
+
If chunked prefill is enabled, prefill tokens and decode tokens can be
|
| 526 |
+
batched together in a flattened 1D query.
|
| 527 |
+
|
| 528 |
+
|<----- num_prefill_tokens ---->|<------- num_decode_tokens --------->|
|
| 529 |
+
|<-prefill_0->|...|<-prefill_N-1->|<--decode_0-->|...|<--decode_M-1-->|
|
| 530 |
+
|
| 531 |
+
Currently, cuda graph is disabled for chunked prefill, meaning there's no
|
| 532 |
+
padding between prefill and decode tokens.
|
| 533 |
+
"""
|
| 534 |
+
|
| 535 |
+
def __init__(
|
| 536 |
+
self,
|
| 537 |
+
num_heads: int,
|
| 538 |
+
head_size: int,
|
| 539 |
+
scale: float,
|
| 540 |
+
num_kv_heads: int,
|
| 541 |
+
alibi_slopes: Optional[List[float]],
|
| 542 |
+
sliding_window: Optional[int],
|
| 543 |
+
kv_cache_dtype: str,
|
| 544 |
+
logits_soft_cap: Optional[float] = None,
|
| 545 |
+
attn_type: str = AttentionType.DECODER,
|
| 546 |
+
kv_sharing_target_layer_name: Optional[str] = None,
|
| 547 |
+
use_irope: bool = False,
|
| 548 |
+
) -> None:
|
| 549 |
+
if kv_sharing_target_layer_name is not None:
|
| 550 |
+
raise NotImplementedError("KV sharing is not supported in V0 "
|
| 551 |
+
"FLASH_ATTN backend.")
|
| 552 |
+
if use_irope:
|
| 553 |
+
logger.warning(
|
| 554 |
+
"Using irope in V0 is not supported yet, it will fall back "
|
| 555 |
+
"to global attention for long context.")
|
| 556 |
+
self.num_heads = num_heads
|
| 557 |
+
self.head_size = head_size
|
| 558 |
+
self.scale = float(scale)
|
| 559 |
+
self.num_kv_heads = num_kv_heads
|
| 560 |
+
if alibi_slopes is not None:
|
| 561 |
+
alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
|
| 562 |
+
self.alibi_slopes = alibi_slopes
|
| 563 |
+
self.sliding_window = ((sliding_window - 1,
|
| 564 |
+
0) if sliding_window is not None else (-1, -1))
|
| 565 |
+
self.kv_cache_dtype = kv_cache_dtype
|
| 566 |
+
self.vllm_flash_attn_version = get_flash_attn_version(
|
| 567 |
+
requires_alibi=self.alibi_slopes is not None)
|
| 568 |
+
if is_quantized_kv_cache(self.kv_cache_dtype) and (
|
| 569 |
+
not self.kv_cache_dtype.startswith("fp8")
|
| 570 |
+
or not flash_attn_supports_fp8()):
|
| 571 |
+
raise NotImplementedError(
|
| 572 |
+
f"FlashAttention does not support {self.kv_cache_dtype} "
|
| 573 |
+
"kv-cache on this device "
|
| 574 |
+
f"(FA supports fp8 = {flash_attn_supports_fp8()}).")
|
| 575 |
+
if logits_soft_cap is None:
|
| 576 |
+
# In flash-attn, setting logits_soft_cap as 0 means no soft cap.
|
| 577 |
+
logits_soft_cap = 0
|
| 578 |
+
self.logits_soft_cap = logits_soft_cap
|
| 579 |
+
|
| 580 |
+
self.num_queries_per_kv = self.num_heads // self.num_kv_heads
|
| 581 |
+
|
| 582 |
+
support_head_sizes = FlashAttentionBackend.get_supported_head_sizes()
|
| 583 |
+
if head_size not in support_head_sizes:
|
| 584 |
+
raise ValueError(
|
| 585 |
+
f"Head size {head_size} is not supported by FlashAttention. "
|
| 586 |
+
f"Supported head sizes are: {support_head_sizes}.")
|
| 587 |
+
self.attn_type = attn_type
|
| 588 |
+
|
| 589 |
+
def forward(
|
| 590 |
+
self,
|
| 591 |
+
layer: AttentionLayer,
|
| 592 |
+
query: torch.Tensor,
|
| 593 |
+
key: torch.Tensor,
|
| 594 |
+
value: torch.Tensor,
|
| 595 |
+
kv_cache: torch.Tensor,
|
| 596 |
+
attn_metadata: FlashAttentionMetadata,
|
| 597 |
+
output: Optional[torch.Tensor] = None,
|
| 598 |
+
output_scale: Optional[torch.Tensor] = None,
|
| 599 |
+
) -> torch.Tensor:
|
| 600 |
+
"""Forward pass with FlashAttention.
|
| 601 |
+
|
| 602 |
+
Args:
|
| 603 |
+
query: shape = [num_tokens, num_heads, head_size]
|
| 604 |
+
key: shape = [num_tokens, num_kv_heads, head_size]
|
| 605 |
+
value: shape = [num_tokens, num_kv_heads, head_size]
|
| 606 |
+
output: shape = [num_tokens, num_heads, head_size]
|
| 607 |
+
kv_cache = [2, num_blocks, block_size, num_kv_heads, head_size]
|
| 608 |
+
NOTE: kv_cache will be an empty tensor with shape [0]
|
| 609 |
+
for profiling run.
|
| 610 |
+
attn_metadata: Metadata for attention.
|
| 611 |
+
NOTE: It in-place updates the output tensor.
|
| 612 |
+
NOTE: FP8 quantization, flash-attn expect the size of
|
| 613 |
+
{q,k,v}_descale to be (num_sequences, num_kv_heads).
|
| 614 |
+
We use torch's .expand() to avoid duplicating values
|
| 615 |
+
"""
|
| 616 |
+
assert output is not None, "Output tensor must be provided."
|
| 617 |
+
|
| 618 |
+
if output_scale is not None:
|
| 619 |
+
raise NotImplementedError(
|
| 620 |
+
"fused output quantization is not yet supported"
|
| 621 |
+
" for FlashAttentionImpl")
|
| 622 |
+
|
| 623 |
+
# NOTE(woosuk): FlashAttention2 does not support FP8 KV cache.
|
| 624 |
+
if not flash_attn_supports_fp8() or output.dtype != torch.bfloat16:
|
| 625 |
+
assert (
|
| 626 |
+
layer._k_scale_float == 1.0 and layer._v_scale_float == 1.0), (
|
| 627 |
+
"key/v_scale is only supported in FlashAttention 3 with "
|
| 628 |
+
"base dtype bfloat16")
|
| 629 |
+
|
| 630 |
+
attn_type = self.attn_type
|
| 631 |
+
if (attn_type == AttentionType.ENCODER
|
| 632 |
+
and (not attn_metadata.is_all_encoder_attn_metadata_set)):
|
| 633 |
+
raise AttributeError("Encoder attention requires setting "
|
| 634 |
+
"encoder metadata attributes.")
|
| 635 |
+
elif (attn_type == AttentionType.ENCODER_DECODER
|
| 636 |
+
and (not attn_metadata.is_all_cross_attn_metadata_set)):
|
| 637 |
+
raise AttributeError("Encoder/decoder cross-attention "
|
| 638 |
+
"requires setting cross-attention "
|
| 639 |
+
"metadata attributes.")
|
| 640 |
+
|
| 641 |
+
kv_cache_dtype: str = self.kv_cache_dtype
|
| 642 |
+
softmax_scale: float = self.scale
|
| 643 |
+
window_size = self.sliding_window
|
| 644 |
+
alibi_slopes: Optional[torch.Tensor] = self.alibi_slopes
|
| 645 |
+
logits_soft_cap: Optional[float] = self.logits_soft_cap
|
| 646 |
+
fp8_attention = kv_cache_dtype.startswith("fp8")
|
| 647 |
+
|
| 648 |
+
if fp8_attention and not flash_attn_supports_fp8():
|
| 649 |
+
raise NotImplementedError(
|
| 650 |
+
"FlashAttention does not support FP8 kv-cache on this device.")
|
| 651 |
+
|
| 652 |
+
if kv_cache.numel() > 0:
|
| 653 |
+
key_cache = kv_cache[0]
|
| 654 |
+
value_cache = kv_cache[1]
|
| 655 |
+
# We skip updating the KV cache under two conditions:
|
| 656 |
+
# a. When the Attention Type is ENCODER. In this phase, we compute
|
| 657 |
+
# only the encoder attention without updating the cache.
|
| 658 |
+
# b. When both Key and Value are None. This occurs during
|
| 659 |
+
# cross-attention computation in the decoding phase, where the
|
| 660 |
+
# KV cache is already populated with the cross-attention
|
| 661 |
+
# tensor. Thus, we skip cache updates during this time.
|
| 662 |
+
if (attn_type != AttentionType.ENCODER) and (key is not None) and (
|
| 663 |
+
value is not None):
|
| 664 |
+
if attn_type == AttentionType.ENCODER_DECODER:
|
| 665 |
+
# Update cross-attention KV cache (prefill-only)
|
| 666 |
+
updated_slot_mapping = attn_metadata.cross_slot_mapping
|
| 667 |
+
else:
|
| 668 |
+
# Update self-attention KV cache (prefill/decode)
|
| 669 |
+
updated_slot_mapping = attn_metadata.slot_mapping
|
| 670 |
+
|
| 671 |
+
# Reshape the input keys and values and store them in the cache.
|
| 672 |
+
# If kv_cache is not provided, the new key and value tensors are
|
| 673 |
+
# not cached. This happens during the initial memory
|
| 674 |
+
# profiling run.
|
| 675 |
+
torch.ops._C_cache_ops.reshape_and_cache_flash(
|
| 676 |
+
key,
|
| 677 |
+
value,
|
| 678 |
+
kv_cache[0],
|
| 679 |
+
kv_cache[1],
|
| 680 |
+
updated_slot_mapping.flatten(), # type: ignore[union-attr]
|
| 681 |
+
kv_cache_dtype,
|
| 682 |
+
layer._k_scale,
|
| 683 |
+
layer._v_scale,
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
if fp8_attention:
|
| 687 |
+
kv_cache = kv_cache.view(torch.float8_e4m3fn)
|
| 688 |
+
key_cache = key_cache.view(torch.float8_e4m3fn)
|
| 689 |
+
value_cache = value_cache.view(torch.float8_e4m3fn)
|
| 690 |
+
|
| 691 |
+
if fp8_attention:
|
| 692 |
+
num_tokens, num_heads, head_size = query.shape
|
| 693 |
+
query, _ = ops.scaled_fp8_quant(
|
| 694 |
+
query.reshape(
|
| 695 |
+
(num_tokens, num_heads * head_size)).contiguous(),
|
| 696 |
+
layer._q_scale)
|
| 697 |
+
query = query.reshape((num_tokens, num_heads, head_size))
|
| 698 |
+
|
| 699 |
+
(num_prefill_query_tokens, num_prefill_kv_tokens,
|
| 700 |
+
num_decode_query_tokens) = \
|
| 701 |
+
get_num_prefill_decode_query_kv_tokens(attn_metadata, attn_type)
|
| 702 |
+
decode_query = query[num_prefill_query_tokens:]
|
| 703 |
+
decode_output = output[num_prefill_query_tokens:]
|
| 704 |
+
# QKV for prefill.
|
| 705 |
+
query = query[:num_prefill_query_tokens]
|
| 706 |
+
prefill_output = output[:num_prefill_query_tokens]
|
| 707 |
+
assert query.shape[0] == num_prefill_query_tokens
|
| 708 |
+
assert decode_query.shape[0] == num_decode_query_tokens
|
| 709 |
+
|
| 710 |
+
if prefill_meta := attn_metadata.prefill_metadata:
|
| 711 |
+
# Prompt run.
|
| 712 |
+
if (kv_cache.numel() == 0 or prefill_meta.block_tables is None
|
| 713 |
+
or prefill_meta.block_tables.numel() == 0):
|
| 714 |
+
# normal attention
|
| 715 |
+
# When block_tables are not filled, it means q and k are the
|
| 716 |
+
# prompt, and they have the same length.
|
| 717 |
+
q_seq_start_loc, q_seq_len, k_seq_start_loc, k_seq_len = \
|
| 718 |
+
_get_query_key_seq_metadata(prefill_meta, True, attn_type)
|
| 719 |
+
|
| 720 |
+
key = key[:num_prefill_kv_tokens]
|
| 721 |
+
value = value[:num_prefill_kv_tokens]
|
| 722 |
+
|
| 723 |
+
if fp8_attention:
|
| 724 |
+
num_kv_tokens, num_kv_heads, head_size = key.shape
|
| 725 |
+
|
| 726 |
+
key, _ = ops.scaled_fp8_quant(
|
| 727 |
+
key.reshape((num_kv_tokens,
|
| 728 |
+
num_kv_heads * head_size)).contiguous(),
|
| 729 |
+
layer._k_scale)
|
| 730 |
+
key = key.reshape((num_kv_tokens, num_kv_heads, head_size))
|
| 731 |
+
|
| 732 |
+
value, _ = ops.scaled_fp8_quant(
|
| 733 |
+
value.reshape((num_kv_tokens,
|
| 734 |
+
num_kv_heads * head_size)).contiguous(),
|
| 735 |
+
layer._v_scale)
|
| 736 |
+
value = value.reshape(
|
| 737 |
+
(num_kv_tokens, num_kv_heads, head_size))
|
| 738 |
+
|
| 739 |
+
descale_shape = (q_seq_start_loc.shape[0] - 1, key.shape[1])
|
| 740 |
+
flash_attn_varlen_func(
|
| 741 |
+
q=query,
|
| 742 |
+
k=key,
|
| 743 |
+
v=value,
|
| 744 |
+
cu_seqlens_q=q_seq_start_loc,
|
| 745 |
+
cu_seqlens_k=k_seq_start_loc,
|
| 746 |
+
max_seqlen_q=q_seq_len,
|
| 747 |
+
max_seqlen_k=k_seq_len,
|
| 748 |
+
softmax_scale=softmax_scale,
|
| 749 |
+
causal=_get_causal_option(attn_type),
|
| 750 |
+
window_size=window_size,
|
| 751 |
+
alibi_slopes=alibi_slopes,
|
| 752 |
+
softcap=logits_soft_cap,
|
| 753 |
+
out=prefill_output,
|
| 754 |
+
fa_version=self.vllm_flash_attn_version,
|
| 755 |
+
q_descale=layer._q_scale.expand(descale_shape),
|
| 756 |
+
k_descale=layer._k_scale.expand(descale_shape),
|
| 757 |
+
v_descale=layer._v_scale.expand(descale_shape),
|
| 758 |
+
)
|
| 759 |
+
else:
|
| 760 |
+
# prefix-enabled attention
|
| 761 |
+
assert attn_type == AttentionType.DECODER, (
|
| 762 |
+
"Only decoder-only models support prefix caching")
|
| 763 |
+
assert prefill_meta.seq_lens is not None
|
| 764 |
+
assert prefill_meta.query_start_loc is not None
|
| 765 |
+
max_seq_len = max(prefill_meta.seq_lens)
|
| 766 |
+
descale_shape = (prefill_meta.query_start_loc.shape[0] - 1,
|
| 767 |
+
key.shape[1])
|
| 768 |
+
flash_attn_varlen_func( # noqa
|
| 769 |
+
q=query,
|
| 770 |
+
k=key_cache,
|
| 771 |
+
v=value_cache,
|
| 772 |
+
cu_seqlens_q=prefill_meta.query_start_loc,
|
| 773 |
+
max_seqlen_q=prefill_meta.max_query_len,
|
| 774 |
+
seqused_k=prefill_meta.seq_lens_tensor,
|
| 775 |
+
max_seqlen_k=max_seq_len,
|
| 776 |
+
softmax_scale=softmax_scale,
|
| 777 |
+
causal=True,
|
| 778 |
+
window_size=window_size,
|
| 779 |
+
alibi_slopes=alibi_slopes,
|
| 780 |
+
block_table=prefill_meta.block_tables,
|
| 781 |
+
softcap=logits_soft_cap,
|
| 782 |
+
out=prefill_output,
|
| 783 |
+
fa_version=self.vllm_flash_attn_version,
|
| 784 |
+
q_descale=layer._q_scale.expand(descale_shape),
|
| 785 |
+
k_descale=layer._k_scale.expand(descale_shape),
|
| 786 |
+
v_descale=layer._v_scale.expand(descale_shape),
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
if decode_meta := attn_metadata.decode_metadata:
|
| 790 |
+
# Decoding run.
|
| 791 |
+
# Use flash_attn_varlen_func kernel for speculative decoding
|
| 792 |
+
# because different queries might have different lengths.
|
| 793 |
+
|
| 794 |
+
assert decode_meta.max_decode_query_len is not None
|
| 795 |
+
# use only for actual varlen decoding
|
| 796 |
+
if decode_meta.max_decode_query_len > 1:
|
| 797 |
+
assert attn_type == AttentionType.DECODER, (
|
| 798 |
+
"Only decoder-only models support max_decode_query_len > 1"
|
| 799 |
+
)
|
| 800 |
+
assert decode_meta.query_start_loc is not None
|
| 801 |
+
descale_shape = (decode_meta.query_start_loc.shape[0] - 1,
|
| 802 |
+
key.shape[1])
|
| 803 |
+
flash_attn_varlen_func(
|
| 804 |
+
q=decode_query,
|
| 805 |
+
k=key_cache,
|
| 806 |
+
v=value_cache,
|
| 807 |
+
cu_seqlens_q=decode_meta.query_start_loc,
|
| 808 |
+
max_seqlen_q=decode_meta.max_decode_query_len,
|
| 809 |
+
seqused_k=decode_meta.seq_lens_tensor,
|
| 810 |
+
max_seqlen_k=decode_meta.max_decode_seq_len,
|
| 811 |
+
softmax_scale=softmax_scale,
|
| 812 |
+
causal=True,
|
| 813 |
+
window_size=window_size,
|
| 814 |
+
alibi_slopes=alibi_slopes,
|
| 815 |
+
softcap=logits_soft_cap,
|
| 816 |
+
block_table=decode_meta.block_tables,
|
| 817 |
+
out=decode_output,
|
| 818 |
+
fa_version=self.vllm_flash_attn_version,
|
| 819 |
+
q_descale=layer._q_scale.expand(descale_shape),
|
| 820 |
+
k_descale=layer._k_scale.expand(descale_shape),
|
| 821 |
+
v_descale=layer._v_scale.expand(descale_shape),
|
| 822 |
+
)
|
| 823 |
+
else:
|
| 824 |
+
# Use flash_attn_with_kvcache for normal decoding.
|
| 825 |
+
(
|
| 826 |
+
seq_lens_arg,
|
| 827 |
+
_,
|
| 828 |
+
block_tables_arg,
|
| 829 |
+
) = get_seq_len_block_table_args(decode_meta, False, attn_type)
|
| 830 |
+
descale_shape = (seq_lens_arg.shape[0], key_cache.shape[-2])
|
| 831 |
+
flash_attn_with_kvcache(
|
| 832 |
+
q=decode_query.unsqueeze(1),
|
| 833 |
+
k_cache=key_cache,
|
| 834 |
+
v_cache=value_cache,
|
| 835 |
+
block_table=block_tables_arg,
|
| 836 |
+
cache_seqlens=seq_lens_arg,
|
| 837 |
+
softmax_scale=softmax_scale,
|
| 838 |
+
causal=True,
|
| 839 |
+
window_size=window_size,
|
| 840 |
+
alibi_slopes=alibi_slopes,
|
| 841 |
+
softcap=logits_soft_cap,
|
| 842 |
+
out=decode_output.unsqueeze(1),
|
| 843 |
+
fa_version=self.vllm_flash_attn_version,
|
| 844 |
+
q_descale=layer._q_scale.expand(descale_shape),
|
| 845 |
+
k_descale=layer._k_scale.expand(descale_shape),
|
| 846 |
+
v_descale=layer._v_scale.expand(descale_shape),
|
| 847 |
+
)
|
| 848 |
+
return output
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def _get_query_key_seq_metadata(
|
| 852 |
+
attn_metadata,
|
| 853 |
+
is_prompt: bool,
|
| 854 |
+
attn_type: str,
|
| 855 |
+
) -> tuple:
|
| 856 |
+
"""
|
| 857 |
+
Returns sequence metadata for key and query based on the specified
|
| 858 |
+
attention type and whether input is a prompt.
|
| 859 |
+
|
| 860 |
+
This function computes the starting locations and maximum sequence lengths
|
| 861 |
+
for key and query sequences for different attention types.
|
| 862 |
+
|
| 863 |
+
Args:
|
| 864 |
+
attn_metadata: The attention metadata object
|
| 865 |
+
is_prompt (bool): A flag indicating if the input is a prompt
|
| 866 |
+
attn_type (AttentionType): The type of attention being used.
|
| 867 |
+
|
| 868 |
+
Returns:
|
| 869 |
+
tuple: A tuple containing four integers:
|
| 870 |
+
- Starting location for the query sequence.
|
| 871 |
+
- Maximum sequence length for the query sequence.
|
| 872 |
+
- Starting location for the key sequence.
|
| 873 |
+
- Maximum sequence length for the key sequence.
|
| 874 |
+
|
| 875 |
+
Raises:
|
| 876 |
+
AttributeError: If an invalid attention type is provided.
|
| 877 |
+
"""
|
| 878 |
+
if attn_type == AttentionType.DECODER:
|
| 879 |
+
# Decoder self-attention
|
| 880 |
+
# Choose max_seq_len based on whether we are in prompt_run
|
| 881 |
+
if is_prompt:
|
| 882 |
+
max_seq_len = attn_metadata.max_prefill_seq_len
|
| 883 |
+
else:
|
| 884 |
+
max_seq_len = attn_metadata.max_decode_seq_len
|
| 885 |
+
return (attn_metadata.seq_start_loc, max_seq_len,
|
| 886 |
+
attn_metadata.seq_start_loc, max_seq_len)
|
| 887 |
+
|
| 888 |
+
elif attn_type == AttentionType.ENCODER_DECODER:
|
| 889 |
+
# This is cross attention between the where the key
|
| 890 |
+
# is the precomputed encoder attention and query
|
| 891 |
+
# is the input sequence.
|
| 892 |
+
# Choose query max length based on whether it is prompt
|
| 893 |
+
# or not.
|
| 894 |
+
if is_prompt:
|
| 895 |
+
max_seq_len = attn_metadata.max_prefill_seq_len
|
| 896 |
+
else:
|
| 897 |
+
max_seq_len = attn_metadata.max_decode_seq_len
|
| 898 |
+
return (attn_metadata.seq_start_loc, max_seq_len,
|
| 899 |
+
attn_metadata.encoder_seq_start_loc,
|
| 900 |
+
attn_metadata.max_encoder_seq_len)
|
| 901 |
+
elif attn_type == AttentionType.ENCODER:
|
| 902 |
+
# For encoder attention both the query and the key are same i.e the
|
| 903 |
+
# encoder sequence.
|
| 904 |
+
return (attn_metadata.encoder_seq_start_loc,
|
| 905 |
+
attn_metadata.max_encoder_seq_len,
|
| 906 |
+
attn_metadata.encoder_seq_start_loc,
|
| 907 |
+
attn_metadata.max_encoder_seq_len)
|
| 908 |
+
elif attn_type == AttentionType.ENCODER_ONLY:
|
| 909 |
+
assert is_prompt, "Should not have decode for encoder only model."
|
| 910 |
+
return (attn_metadata.seq_start_loc, attn_metadata.max_prefill_seq_len,
|
| 911 |
+
attn_metadata.seq_start_loc, attn_metadata.max_prefill_seq_len)
|
| 912 |
+
else:
|
| 913 |
+
raise AttributeError(f"Invalid attention type {str(attn_type)}")
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
def _get_causal_option(attn_type: str) -> bool:
|
| 917 |
+
"""
|
| 918 |
+
Determine whether the given attention type is suitable for causal
|
| 919 |
+
attention mechanisms.
|
| 920 |
+
|
| 921 |
+
Args:
|
| 922 |
+
attn_type (AttentionType): The type of attention being evaluated
|
| 923 |
+
|
| 924 |
+
Returns:
|
| 925 |
+
bool: Returns `True` if the attention type is suitable for causal
|
| 926 |
+
attention (i.e., not encoder, encoder-only, or encoder-decoder),
|
| 927 |
+
otherwise returns `False`.
|
| 928 |
+
"""
|
| 929 |
+
return not (attn_type == AttentionType.ENCODER
|
| 930 |
+
or attn_type == AttentionType.ENCODER_ONLY
|
| 931 |
+
or attn_type == AttentionType.ENCODER_DECODER)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/flashinfer.py
ADDED
|
@@ -0,0 +1,1098 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
import dataclasses
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Type
|
| 9 |
+
|
| 10 |
+
from vllm.multimodal import MultiModalPlaceholderMap
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from flashinfer import BatchDecodeWithPagedKVCacheWrapper
|
| 14 |
+
from flashinfer.decode import (CUDAGraphBatchDecodeWithPagedKVCacheWrapper,
|
| 15 |
+
trtllm_batch_decode_with_kv_cache)
|
| 16 |
+
from flashinfer.prefill import BatchPrefillWithPagedKVCacheWrapper
|
| 17 |
+
|
| 18 |
+
from vllm.vllm_flash_attn import flash_attn_varlen_func
|
| 19 |
+
FLASHINFER_WORKSPACE_BUFFER_SIZE = 256 * 1024 * 1024
|
| 20 |
+
except ImportError:
|
| 21 |
+
# Avoid turning these types into variables during type checking
|
| 22 |
+
if not TYPE_CHECKING:
|
| 23 |
+
BatchDecodeWithPagedKVCacheWrapper = None
|
| 24 |
+
CUDAGraphBatchDecodeWithPagedKVCacheWrapper = None
|
| 25 |
+
BatchPrefillWithPagedKVCacheWrapper = None
|
| 26 |
+
trtllm_batch_decode_with_kv_cache = None
|
| 27 |
+
FLASHINFER_WORKSPACE_BUFFER_SIZE = 0
|
| 28 |
+
raise ImportError("FlashInfer is not installed. Please install it from "
|
| 29 |
+
"https://github.com/flashinfer-ai/flashinfer") from None
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
import vllm.envs as envs
|
| 34 |
+
from vllm import _custom_ops as ops
|
| 35 |
+
from vllm.attention.backends.abstract import (AttentionBackend, AttentionImpl,
|
| 36 |
+
AttentionLayer,
|
| 37 |
+
AttentionMetadata,
|
| 38 |
+
AttentionMetadataBuilder,
|
| 39 |
+
AttentionState, AttentionType)
|
| 40 |
+
from vllm.attention.backends.utils import (PAD_SLOT_ID, compute_slot_mapping,
|
| 41 |
+
compute_slot_mapping_start_idx,
|
| 42 |
+
is_block_tables_empty)
|
| 43 |
+
from vllm.attention.layer import Attention
|
| 44 |
+
from vllm.attention.ops.paged_attn import PagedAttention
|
| 45 |
+
from vllm.config import VllmConfig, get_layers_from_vllm_config
|
| 46 |
+
from vllm.logger import init_logger
|
| 47 |
+
from vllm.utils import (async_tensor_h2d, get_kv_cache_torch_dtype,
|
| 48 |
+
make_tensor_with_pad)
|
| 49 |
+
from vllm.utils.flashinfer import use_trtllm_attention
|
| 50 |
+
|
| 51 |
+
logger = init_logger(__name__)
|
| 52 |
+
|
| 53 |
+
if TYPE_CHECKING:
|
| 54 |
+
from vllm.worker.model_runner import ModelInputForGPUBuilder
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class FlashInferBackend(AttentionBackend):
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
def get_name() -> str:
|
| 61 |
+
return "FLASHINFER"
|
| 62 |
+
|
| 63 |
+
@staticmethod
|
| 64 |
+
def get_impl_cls() -> Type["FlashInferImpl"]:
|
| 65 |
+
return FlashInferImpl
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def get_metadata_cls() -> Type["AttentionMetadata"]:
|
| 69 |
+
return FlashInferMetadata
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def get_builder_cls() -> Type["FlashInferMetadataBuilder"]:
|
| 73 |
+
return FlashInferMetadataBuilder
|
| 74 |
+
|
| 75 |
+
@staticmethod
|
| 76 |
+
def get_state_cls() -> Type["FlashInferState"]:
|
| 77 |
+
return FlashInferState
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def get_kv_cache_shape(
|
| 81 |
+
num_blocks: int,
|
| 82 |
+
block_size: int,
|
| 83 |
+
num_kv_heads: int,
|
| 84 |
+
head_size: int,
|
| 85 |
+
) -> Tuple[int, ...]:
|
| 86 |
+
return (num_blocks, 2, block_size, num_kv_heads, head_size)
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def get_kv_cache_stride_order() -> Tuple[int, ...]:
|
| 90 |
+
cache_layout = FlashInferState.get_kv_cache_layout()
|
| 91 |
+
assert (cache_layout in ("NHD", "HND"))
|
| 92 |
+
stride_order = (0, 1, 2, 3, 4) if cache_layout == "NHD" else (0, 1, 3,
|
| 93 |
+
2, 4)
|
| 94 |
+
return stride_order
|
| 95 |
+
|
| 96 |
+
@staticmethod
|
| 97 |
+
def swap_blocks(
|
| 98 |
+
src_kv_cache: torch.Tensor,
|
| 99 |
+
dst_kv_cache: torch.Tensor,
|
| 100 |
+
src_to_dst: torch.Tensor,
|
| 101 |
+
) -> None:
|
| 102 |
+
PagedAttention.swap_blocks(src_kv_cache, dst_kv_cache, src_to_dst)
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def copy_blocks(
|
| 106 |
+
kv_caches: List[torch.Tensor],
|
| 107 |
+
src_to_dists: torch.Tensor,
|
| 108 |
+
) -> None:
|
| 109 |
+
PagedAttention.copy_blocks(kv_caches, src_to_dists)
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def get_supported_head_sizes() -> List[int]:
|
| 113 |
+
return [64, 128, 256]
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
def get_fp8_dtype_for_flashinfer(kv_cache_dtype: str) -> torch.dtype:
|
| 117 |
+
if kv_cache_dtype in ("fp8", "fp8_e4m3"):
|
| 118 |
+
return torch.float8_e4m3fn
|
| 119 |
+
elif kv_cache_dtype == "fp8_e5m2":
|
| 120 |
+
return torch.float8_e5m2
|
| 121 |
+
else:
|
| 122 |
+
raise ValueError(f"Unrecognized FP8 dtype: {kv_cache_dtype}")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@dataclass
|
| 126 |
+
class PerLayerParameters:
|
| 127 |
+
"""
|
| 128 |
+
Currently, FlashInfer backend only support models in which all layers share
|
| 129 |
+
the same values for the following hyperparameters.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
window_left: int
|
| 133 |
+
logits_soft_cap: Optional[float]
|
| 134 |
+
sm_scale: float
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def get_per_layer_parameters(
|
| 138 |
+
vllm_config: VllmConfig) -> Dict[str, PerLayerParameters]:
|
| 139 |
+
"""
|
| 140 |
+
Scan all attention layers and determine some hyperparameters
|
| 141 |
+
to use during `plan`.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
layers = get_layers_from_vllm_config(vllm_config, Attention)
|
| 145 |
+
per_layer_params: Dict[str, PerLayerParameters] = {}
|
| 146 |
+
|
| 147 |
+
for key, layer in layers.items():
|
| 148 |
+
impl = layer.impl
|
| 149 |
+
assert isinstance(impl, FlashInferImpl)
|
| 150 |
+
|
| 151 |
+
# Infer hyperparameters from the attention layer
|
| 152 |
+
window_size = impl.sliding_window
|
| 153 |
+
window_left = window_size[0] if window_size is not None else -1
|
| 154 |
+
logits_soft_cap = impl.logits_soft_cap
|
| 155 |
+
sm_scale = impl.scale
|
| 156 |
+
|
| 157 |
+
per_layer_params[key] = PerLayerParameters(window_left,
|
| 158 |
+
logits_soft_cap, sm_scale)
|
| 159 |
+
|
| 160 |
+
return per_layer_params
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def infer_global_hyperparameters(
|
| 164 |
+
per_layer_params: Dict[str, PerLayerParameters]) -> PerLayerParameters:
|
| 165 |
+
"""
|
| 166 |
+
Currently, FlashInfer backend only support models in which all layers share
|
| 167 |
+
the same values for the following hyperparameters:
|
| 168 |
+
- `window_left`
|
| 169 |
+
- `logits_soft_cap`
|
| 170 |
+
- `sm_scale`
|
| 171 |
+
|
| 172 |
+
So this function asserts that all layers share the same values for these
|
| 173 |
+
hyperparameters and returns the global values.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
assert len(per_layer_params) > 0, "No attention layers found in the model."
|
| 177 |
+
|
| 178 |
+
param_sets = list(per_layer_params.values())
|
| 179 |
+
global_params = param_sets[0]
|
| 180 |
+
for params in param_sets:
|
| 181 |
+
assert params == global_params, (
|
| 182 |
+
"FlashInfer backend currently only supports models in which all "
|
| 183 |
+
"layers share the same values for the following hyperparameters: "
|
| 184 |
+
"`window_left`, `logits_soft_cap`, `sm_scale`.")
|
| 185 |
+
|
| 186 |
+
return global_params
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class FlashInferState(AttentionState):
|
| 190 |
+
|
| 191 |
+
def __init__(self, runner):
|
| 192 |
+
self.runner = runner
|
| 193 |
+
self._is_graph_capturing = False
|
| 194 |
+
self._workspace_buffer = None
|
| 195 |
+
self._decode_wrapper = None
|
| 196 |
+
self._prefill_wrapper = None
|
| 197 |
+
|
| 198 |
+
# Global hyperparameters shared by all attention layers
|
| 199 |
+
self.global_hyperparameters: Optional[PerLayerParameters] = None
|
| 200 |
+
|
| 201 |
+
self.vllm_config = self.runner.vllm_config
|
| 202 |
+
self._kv_cache_layout = None
|
| 203 |
+
|
| 204 |
+
def _get_workspace_buffer(self):
|
| 205 |
+
if self._workspace_buffer is None:
|
| 206 |
+
self._workspace_buffer = torch.zeros(
|
| 207 |
+
FLASHINFER_WORKSPACE_BUFFER_SIZE,
|
| 208 |
+
dtype=torch.uint8,
|
| 209 |
+
device=self.runner.device)
|
| 210 |
+
return self._workspace_buffer
|
| 211 |
+
|
| 212 |
+
@staticmethod
|
| 213 |
+
def get_kv_cache_layout():
|
| 214 |
+
from vllm.v1.attention.backends.utils import _KV_CACHE_LAYOUT_OVERRIDE
|
| 215 |
+
if _KV_CACHE_LAYOUT_OVERRIDE is not None:
|
| 216 |
+
logger.info_once("Using KV cache layout %s",
|
| 217 |
+
_KV_CACHE_LAYOUT_OVERRIDE)
|
| 218 |
+
return _KV_CACHE_LAYOUT_OVERRIDE
|
| 219 |
+
cache_layout = envs.VLLM_KV_CACHE_LAYOUT
|
| 220 |
+
if cache_layout is None:
|
| 221 |
+
logger.info_once("Using default KV cache layout NHD")
|
| 222 |
+
return "NHD"
|
| 223 |
+
logger.info_once("Using KV cache layout %s", cache_layout)
|
| 224 |
+
return cache_layout
|
| 225 |
+
|
| 226 |
+
def _get_prefill_wrapper(self):
|
| 227 |
+
if self._prefill_wrapper is None:
|
| 228 |
+
self._prefill_wrapper = BatchPrefillWithPagedKVCacheWrapper(
|
| 229 |
+
self._get_workspace_buffer(), self.get_kv_cache_layout())
|
| 230 |
+
return self._prefill_wrapper
|
| 231 |
+
|
| 232 |
+
def _get_decode_wrapper(self):
|
| 233 |
+
if self._decode_wrapper is None:
|
| 234 |
+
num_qo_heads = (self.runner.model_config.get_num_attention_heads(
|
| 235 |
+
self.runner.parallel_config))
|
| 236 |
+
num_kv_heads = self.runner.model_config.get_num_kv_heads(
|
| 237 |
+
self.runner.parallel_config)
|
| 238 |
+
use_tensor_cores = envs.VLLM_FLASHINFER_FORCE_TENSOR_CORES or (
|
| 239 |
+
num_qo_heads // num_kv_heads > 4)
|
| 240 |
+
self._decode_wrapper = BatchDecodeWithPagedKVCacheWrapper(
|
| 241 |
+
self._get_workspace_buffer(),
|
| 242 |
+
self.get_kv_cache_layout(),
|
| 243 |
+
use_tensor_cores=use_tensor_cores)
|
| 244 |
+
return self._decode_wrapper
|
| 245 |
+
|
| 246 |
+
@contextmanager
|
| 247 |
+
def graph_capture(self, max_batch_size: int):
|
| 248 |
+
self._is_graph_capturing = True
|
| 249 |
+
self._graph_decode_wrapper = None
|
| 250 |
+
self._graph_slot_mapping = torch.full((max_batch_size, ),
|
| 251 |
+
PAD_SLOT_ID,
|
| 252 |
+
dtype=torch.long,
|
| 253 |
+
device=self.runner.device)
|
| 254 |
+
self._graph_seq_lens = torch.ones(max_batch_size,
|
| 255 |
+
dtype=torch.int32,
|
| 256 |
+
device=self.runner.device)
|
| 257 |
+
self._graph_block_tables = torch.from_numpy(
|
| 258 |
+
self.runner.graph_block_tables).to(device=self.runner.device)
|
| 259 |
+
self._graph_decode_workspace_buffer = self._get_workspace_buffer()
|
| 260 |
+
self._graph_indices_buffer = torch.empty(
|
| 261 |
+
max_batch_size * self.runner.cache_config.num_gpu_blocks,
|
| 262 |
+
dtype=torch.int32,
|
| 263 |
+
device=self.runner.device)
|
| 264 |
+
self._graph_indptr_buffer = torch.empty(max_batch_size + 1,
|
| 265 |
+
dtype=torch.int32,
|
| 266 |
+
device=self.runner.device)
|
| 267 |
+
self._graph_last_page_len_buffer = torch.empty(
|
| 268 |
+
max_batch_size, dtype=torch.int32, device=self.runner.device)
|
| 269 |
+
yield
|
| 270 |
+
self._is_graph_capturing = False
|
| 271 |
+
del self._graph_slot_mapping
|
| 272 |
+
del self._graph_seq_lens
|
| 273 |
+
del self._graph_block_tables
|
| 274 |
+
del self._graph_decode_workspace_buffer
|
| 275 |
+
del self._graph_indices_buffer
|
| 276 |
+
del self._graph_indptr_buffer
|
| 277 |
+
del self._graph_last_page_len_buffer
|
| 278 |
+
del self._graph_decode_wrapper
|
| 279 |
+
|
| 280 |
+
def graph_clone(self, batch_size: int):
|
| 281 |
+
assert self._is_graph_capturing
|
| 282 |
+
state = self.__class__(self.runner)
|
| 283 |
+
state._workspace_buffer = self._graph_decode_workspace_buffer
|
| 284 |
+
state._decode_wrapper = self._graph_decode_wrapper
|
| 285 |
+
state._prefill_wrapper = self._get_prefill_wrapper()
|
| 286 |
+
return state
|
| 287 |
+
|
| 288 |
+
def graph_capture_get_metadata_for_batch(
|
| 289 |
+
self, batch_size: int, is_encoder_decoder_model: bool = False):
|
| 290 |
+
assert self._is_graph_capturing
|
| 291 |
+
_indptr_buffer = self._graph_indptr_buffer[:batch_size + 1]
|
| 292 |
+
_last_page_len_buffer = self._graph_last_page_len_buffer[:batch_size]
|
| 293 |
+
|
| 294 |
+
num_qo_heads = (self.runner.model_config.get_num_attention_heads(
|
| 295 |
+
self.runner.parallel_config))
|
| 296 |
+
num_kv_heads = self.runner.model_config.get_num_kv_heads(
|
| 297 |
+
self.runner.parallel_config)
|
| 298 |
+
use_tensor_cores = envs.VLLM_FLASHINFER_FORCE_TENSOR_CORES or (
|
| 299 |
+
num_qo_heads // num_kv_heads > 4)
|
| 300 |
+
self._graph_decode_wrapper = \
|
| 301 |
+
CUDAGraphBatchDecodeWithPagedKVCacheWrapper(
|
| 302 |
+
self._graph_decode_workspace_buffer, _indptr_buffer,
|
| 303 |
+
self._graph_indices_buffer, _last_page_len_buffer,
|
| 304 |
+
self.get_kv_cache_layout(),
|
| 305 |
+
use_tensor_cores)
|
| 306 |
+
if self.runner.kv_cache_dtype.startswith("fp8"):
|
| 307 |
+
kv_cache_dtype = FlashInferBackend.get_fp8_dtype_for_flashinfer(
|
| 308 |
+
self.runner.kv_cache_dtype)
|
| 309 |
+
else:
|
| 310 |
+
kv_cache_dtype = get_kv_cache_torch_dtype(
|
| 311 |
+
self.runner.kv_cache_dtype, self.runner.model_config.dtype)
|
| 312 |
+
|
| 313 |
+
paged_kv_indptr_tensor_host = torch.arange(0,
|
| 314 |
+
batch_size + 1,
|
| 315 |
+
dtype=torch.int32)
|
| 316 |
+
paged_kv_indices_tensor_host = torch.arange(0,
|
| 317 |
+
batch_size,
|
| 318 |
+
dtype=torch.int32)
|
| 319 |
+
paged_kv_last_page_len_tensor_host = torch.full((batch_size, ),
|
| 320 |
+
self.runner.block_size,
|
| 321 |
+
dtype=torch.int32)
|
| 322 |
+
query_start_loc_host = torch.arange(0,
|
| 323 |
+
batch_size + 1,
|
| 324 |
+
dtype=torch.int32)
|
| 325 |
+
|
| 326 |
+
global_params = infer_global_hyperparameters(
|
| 327 |
+
get_per_layer_parameters(self.vllm_config))
|
| 328 |
+
|
| 329 |
+
attn_metadata = self.runner.attn_backend.make_metadata(
|
| 330 |
+
num_prefills=0,
|
| 331 |
+
slot_mapping=self._graph_slot_mapping[:batch_size],
|
| 332 |
+
multi_modal_placeholder_index_maps=None,
|
| 333 |
+
enable_kv_scales_calculation=False,
|
| 334 |
+
num_prefill_tokens=0,
|
| 335 |
+
num_decode_tokens=batch_size,
|
| 336 |
+
max_prefill_seq_len=0,
|
| 337 |
+
max_decode_seq_len=0,
|
| 338 |
+
seq_lens_tensor=self._graph_seq_lens,
|
| 339 |
+
block_tables=self._graph_block_tables,
|
| 340 |
+
paged_kv_indptr=paged_kv_indptr_tensor_host,
|
| 341 |
+
paged_kv_indices=paged_kv_indices_tensor_host,
|
| 342 |
+
paged_kv_last_page_len=paged_kv_last_page_len_tensor_host,
|
| 343 |
+
num_qo_heads=num_qo_heads,
|
| 344 |
+
num_kv_heads=num_kv_heads,
|
| 345 |
+
head_dim=self.runner.model_config.get_head_size(),
|
| 346 |
+
page_size=self.runner.block_size,
|
| 347 |
+
seq_start_loc=None,
|
| 348 |
+
query_start_loc=query_start_loc_host,
|
| 349 |
+
device=self.runner.device,
|
| 350 |
+
data_type=kv_cache_dtype,
|
| 351 |
+
q_data_type=self.runner.model_config.dtype,
|
| 352 |
+
use_cuda_graph=True,
|
| 353 |
+
decode_wrapper=self._graph_decode_wrapper,
|
| 354 |
+
prefill_wrapper=None,
|
| 355 |
+
**dataclasses.asdict(global_params),
|
| 356 |
+
)
|
| 357 |
+
attn_metadata.begin_forward()
|
| 358 |
+
return attn_metadata
|
| 359 |
+
|
| 360 |
+
def get_graph_input_buffers(self,
|
| 361 |
+
attn_metadata,
|
| 362 |
+
is_encoder_decoder_model: bool = False):
|
| 363 |
+
return {
|
| 364 |
+
"block_tables": attn_metadata.block_tables,
|
| 365 |
+
"seq_lens_tensor": attn_metadata.seq_lens_tensor,
|
| 366 |
+
"slot_mapping": attn_metadata.slot_mapping,
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
def prepare_graph_input_buffers(self,
|
| 370 |
+
input_buffers,
|
| 371 |
+
attn_metadata,
|
| 372 |
+
is_encoder_decoder_model: bool = False):
|
| 373 |
+
# FlashInfer-specific logic: copy additional tensors
|
| 374 |
+
num_total_blocks = attn_metadata.decode_metadata.seq_lens_tensor.shape[
|
| 375 |
+
0]
|
| 376 |
+
input_buffers["seq_lens_tensor"][:num_total_blocks].copy_(
|
| 377 |
+
attn_metadata.seq_lens_tensor, non_blocking=True)
|
| 378 |
+
input_buffers["block_tables"][:num_total_blocks].copy_(
|
| 379 |
+
attn_metadata.block_tables, non_blocking=True)
|
| 380 |
+
|
| 381 |
+
def begin_forward(self, model_input):
|
| 382 |
+
assert not self._is_graph_capturing
|
| 383 |
+
state = self
|
| 384 |
+
use_cuda_graph = model_input.attn_metadata.use_cuda_graph
|
| 385 |
+
is_decode = model_input.attn_metadata.num_prefills == 0
|
| 386 |
+
# In case of multistep chunked-prefill, there might be prefill requests
|
| 387 |
+
# scheduled while CUDA graph mode is enabled. We don't run graph in that
|
| 388 |
+
# case.
|
| 389 |
+
if use_cuda_graph and is_decode:
|
| 390 |
+
if model_input.inputs_embeds is None:
|
| 391 |
+
batch_size = model_input.input_tokens.shape[0]
|
| 392 |
+
state = (
|
| 393 |
+
self.runner.graph_runners[model_input.virtual_engine][(
|
| 394 |
+
batch_size, False)].attn_state)
|
| 395 |
+
else:
|
| 396 |
+
batch_size = model_input.inputs_embeds.shape[0]
|
| 397 |
+
state = (
|
| 398 |
+
self.runner.graph_runners[model_input.virtual_engine][(
|
| 399 |
+
batch_size, True)].attn_state)
|
| 400 |
+
|
| 401 |
+
model_input.attn_metadata.prefill_wrapper = state._get_prefill_wrapper(
|
| 402 |
+
)
|
| 403 |
+
model_input.attn_metadata.decode_wrapper = state._get_decode_wrapper()
|
| 404 |
+
model_input.attn_metadata.begin_forward()
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
@dataclass
|
| 408 |
+
class FlashInferMetadata(AttentionMetadata):
|
| 409 |
+
# Maximum sequence length among prefill batch. 0 if there are decoding
|
| 410 |
+
# requests only.
|
| 411 |
+
max_prefill_seq_len: int
|
| 412 |
+
max_decode_seq_len: int
|
| 413 |
+
|
| 414 |
+
# Number of query tokens for each request in the batch.
|
| 415 |
+
# Currently, we require that all requests have the same number of query
|
| 416 |
+
# tokens during the decoding phase. When speculavie decoding is enabled,
|
| 417 |
+
# decode_query_len might be greater than 1. In all other cases, it is 1.
|
| 418 |
+
decode_query_len: Optional[int] = 1
|
| 419 |
+
|
| 420 |
+
use_cuda_graph: bool = True
|
| 421 |
+
|
| 422 |
+
prefill_wrapper: Optional[BatchPrefillWithPagedKVCacheWrapper] = None
|
| 423 |
+
decode_wrapper: Optional[BatchDecodeWithPagedKVCacheWrapper] = None
|
| 424 |
+
|
| 425 |
+
# Metadata for the prefill stage
|
| 426 |
+
seq_start_loc: Optional[torch.Tensor] = None
|
| 427 |
+
query_start_loc: Optional[torch.Tensor] = None
|
| 428 |
+
block_tables: Optional[torch.Tensor] = None
|
| 429 |
+
|
| 430 |
+
# used for GPU operations
|
| 431 |
+
seq_lens_tensor: Optional[torch.Tensor] = None
|
| 432 |
+
block_table_bound: Optional[torch.Tensor] = None
|
| 433 |
+
|
| 434 |
+
# An example for paged_kv_indices, paged_kv_indptr:
|
| 435 |
+
# request 1, page indices [0, 5, 8]
|
| 436 |
+
# request 2, page indices [1, 6, 7]
|
| 437 |
+
# request 3, page indices [3, 4]
|
| 438 |
+
# paged_kv_indices is a concatenation of page indices of all requests:
|
| 439 |
+
# [0, 5, 8, 1, 6, 7, 3, 4]
|
| 440 |
+
# paged_kv_indptr is used to index into paged_kv_indices:
|
| 441 |
+
# [0, 3, 6, 8]
|
| 442 |
+
# The indptr of the paged kv cache, shape: [batch_size + 1]
|
| 443 |
+
paged_kv_indptr: Optional[torch.Tensor] = None
|
| 444 |
+
# The page indices of the paged kv cache
|
| 445 |
+
paged_kv_indices: Optional[torch.Tensor] = None
|
| 446 |
+
# The number of entries in the last page of each request in
|
| 447 |
+
# the paged kv cache, shape: [batch_size]
|
| 448 |
+
paged_kv_last_page_len: Optional[torch.Tensor] = None
|
| 449 |
+
# The number of query/output heads
|
| 450 |
+
num_qo_heads: Optional[int] = None
|
| 451 |
+
# The number of key/value heads
|
| 452 |
+
num_kv_heads: Optional[int] = None
|
| 453 |
+
# The dimension of the attention heads
|
| 454 |
+
head_dim: Optional[int] = None
|
| 455 |
+
# Block size of vllm
|
| 456 |
+
page_size: Optional[int] = None
|
| 457 |
+
# The data type of the paged kv cache
|
| 458 |
+
data_type: torch.dtype = None
|
| 459 |
+
# The data type of the query
|
| 460 |
+
q_data_type: torch.dtype = None
|
| 461 |
+
# FlashInfer 0.2 encourages passing host tensors
|
| 462 |
+
device: torch.device = torch.device("cpu")
|
| 463 |
+
is_profile_run: bool = False
|
| 464 |
+
|
| 465 |
+
# The FlashInfer backend currently supports only models in which all layers
|
| 466 |
+
# share the same following hyperparameters:
|
| 467 |
+
|
| 468 |
+
# The left (inclusive) window size for the attention window, when
|
| 469 |
+
# set to `-1`, the window size will be set to the full length of
|
| 470 |
+
# the sequence. Defaults to `-1`.
|
| 471 |
+
window_left: int = -1
|
| 472 |
+
# The attention logits soft capping value (used in Gemini, Grok and
|
| 473 |
+
# Gemma-2, etc.), if not provided, will be set to `0`. If greater
|
| 474 |
+
# than 0, the logits will be capped according to formula:
|
| 475 |
+
# $$\texttt{logits\_soft\_cap} \times
|
| 476 |
+
# \mathrm{tanh}(x / \texttt{logits\_soft\_cap})$$,
|
| 477 |
+
# where $x$ is the input logits.
|
| 478 |
+
logits_soft_cap: Optional[float] = None
|
| 479 |
+
# The scale used in softmax, if not provided, will be set to
|
| 480 |
+
# `1.0 / sqrt(head_dim)`.
|
| 481 |
+
sm_scale: Optional[float] = None
|
| 482 |
+
|
| 483 |
+
def __post_init__(self):
|
| 484 |
+
# Refer to
|
| 485 |
+
# https://github.com/flashinfer-ai/flashinfer/blob/3d55c71a62052c590c130897d3a3db49b14fcc34/include/flashinfer/utils.cuh#L157
|
| 486 |
+
supported_head_sizes = FlashInferBackend.get_supported_head_sizes()
|
| 487 |
+
if self.head_dim is not None and self.head_dim \
|
| 488 |
+
not in supported_head_sizes:
|
| 489 |
+
raise ValueError(
|
| 490 |
+
f"Only {supported_head_sizes} are supported for head_dim,",
|
| 491 |
+
f" received {self.head_dim}.")
|
| 492 |
+
|
| 493 |
+
def begin_forward(self):
|
| 494 |
+
if self.num_prefill_tokens > 0:
|
| 495 |
+
if self.paged_kv_indices is None:
|
| 496 |
+
return
|
| 497 |
+
|
| 498 |
+
assert self.prefill_wrapper is not None
|
| 499 |
+
assert self.query_start_loc is not None
|
| 500 |
+
assert self.paged_kv_indices is not None
|
| 501 |
+
assert self.paged_kv_indptr is not None
|
| 502 |
+
assert self.paged_kv_last_page_len is not None
|
| 503 |
+
assert self.block_table_bound is not None
|
| 504 |
+
assert self.seq_lens_tensor is not None
|
| 505 |
+
self.query_start_loc = self.query_start_loc[:self.num_prefills + 1]
|
| 506 |
+
batch_size = self.query_start_loc.shape[0] - 1
|
| 507 |
+
assert batch_size >= 0
|
| 508 |
+
# We will use flash attention for profiling to
|
| 509 |
+
# determine the number of blocks. Therefore,
|
| 510 |
+
# we don't need to prepare the input for flashinfer for profile run.
|
| 511 |
+
if not self.is_profile_run:
|
| 512 |
+
self.paged_kv_indptr = self.paged_kv_indptr.to(self.device)
|
| 513 |
+
self.paged_kv_last_page_len = self.paged_kv_last_page_len.to(
|
| 514 |
+
self.device)
|
| 515 |
+
self.block_table_bound = self.block_table_bound.to(self.device)
|
| 516 |
+
self.seq_lens_tensor = self.seq_lens_tensor.to(self.device)
|
| 517 |
+
self.paged_kv_indices = self.paged_kv_indices.to(self.device)
|
| 518 |
+
self.prefill_wrapper.plan(
|
| 519 |
+
self.query_start_loc,
|
| 520 |
+
self.paged_kv_indptr[:self.num_prefills + 1],
|
| 521 |
+
self.paged_kv_indices,
|
| 522 |
+
self.paged_kv_last_page_len[:self.num_prefills],
|
| 523 |
+
self.num_qo_heads,
|
| 524 |
+
self.num_kv_heads,
|
| 525 |
+
self.head_dim,
|
| 526 |
+
self.page_size,
|
| 527 |
+
causal=True,
|
| 528 |
+
sm_scale=self.sm_scale,
|
| 529 |
+
window_left=self.window_left,
|
| 530 |
+
logits_soft_cap=self.logits_soft_cap,
|
| 531 |
+
q_data_type=self.q_data_type,
|
| 532 |
+
kv_data_type=self.data_type)
|
| 533 |
+
if self.num_decode_tokens > 0:
|
| 534 |
+
assert self.paged_kv_indices is not None
|
| 535 |
+
assert self.paged_kv_indptr is not None
|
| 536 |
+
assert self.paged_kv_last_page_len is not None
|
| 537 |
+
self.paged_kv_indices = self.paged_kv_indices.to(self.device)
|
| 538 |
+
self.paged_kv_indptr = self.paged_kv_indptr.to(self.device)
|
| 539 |
+
self.paged_kv_last_page_len = self.paged_kv_last_page_len.to(
|
| 540 |
+
self.device)
|
| 541 |
+
# handle model warmup path
|
| 542 |
+
if self.block_table_bound is not None:
|
| 543 |
+
self.block_table_bound = self.block_table_bound.to(self.device)
|
| 544 |
+
if self.seq_lens_tensor is not None:
|
| 545 |
+
self.seq_lens_tensor = self.seq_lens_tensor.to(self.device)
|
| 546 |
+
|
| 547 |
+
assert self.decode_wrapper is not None
|
| 548 |
+
self.decode_wrapper.plan(
|
| 549 |
+
self.paged_kv_indptr[self.num_prefills:],
|
| 550 |
+
self.paged_kv_indices,
|
| 551 |
+
self.paged_kv_last_page_len[self.num_prefills:],
|
| 552 |
+
self.num_qo_heads,
|
| 553 |
+
self.num_kv_heads,
|
| 554 |
+
self.head_dim,
|
| 555 |
+
self.page_size,
|
| 556 |
+
# Disable flashinfer's pos encoding and use vllm's rope.
|
| 557 |
+
pos_encoding_mode="NONE",
|
| 558 |
+
window_left=self.window_left,
|
| 559 |
+
logits_soft_cap=self.logits_soft_cap,
|
| 560 |
+
sm_scale=self.sm_scale,
|
| 561 |
+
# kv-cache data type.
|
| 562 |
+
kv_data_type=self.data_type,
|
| 563 |
+
# query data type.
|
| 564 |
+
q_data_type=self.q_data_type)
|
| 565 |
+
|
| 566 |
+
def asdict_zerocopy(self,
|
| 567 |
+
skip_fields: Optional[Set[str]] = None
|
| 568 |
+
) -> Dict[str, Any]:
|
| 569 |
+
if skip_fields is None:
|
| 570 |
+
skip_fields = set()
|
| 571 |
+
# We need to skip the prefill/decode_wrapper field since it cannot be
|
| 572 |
+
# broadcasted with nccl when TP is enabled.
|
| 573 |
+
skip_fields.add('prefill_wrapper')
|
| 574 |
+
skip_fields.add('decode_wrapper')
|
| 575 |
+
return super().asdict_zerocopy(skip_fields)
|
| 576 |
+
|
| 577 |
+
@property
|
| 578 |
+
def prefill_metadata(self) -> Optional["FlashInferMetadata"]:
|
| 579 |
+
if self.num_prefills == 0:
|
| 580 |
+
return None
|
| 581 |
+
return self
|
| 582 |
+
|
| 583 |
+
@property
|
| 584 |
+
def decode_metadata(self) -> Optional["FlashInferMetadata"]:
|
| 585 |
+
if self.num_decode_tokens == 0:
|
| 586 |
+
return None
|
| 587 |
+
return self
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
| 591 |
+
|
| 592 |
+
def __init__(self, input_builder: "ModelInputForGPUBuilder"):
|
| 593 |
+
|
| 594 |
+
self.input_builder = input_builder
|
| 595 |
+
self.runner = input_builder.runner
|
| 596 |
+
|
| 597 |
+
self.sliding_window = input_builder.sliding_window
|
| 598 |
+
self.block_size = input_builder.block_size
|
| 599 |
+
|
| 600 |
+
# Global hyperparameters shared by all attention layers
|
| 601 |
+
self.global_hyperparameters: Optional[PerLayerParameters] = None
|
| 602 |
+
|
| 603 |
+
self.vllm_config = self.runner.vllm_config
|
| 604 |
+
|
| 605 |
+
def prepare(self):
|
| 606 |
+
self.slot_mapping: List[int] = []
|
| 607 |
+
self.prefill_seq_lens: List[int] = []
|
| 608 |
+
self.context_lens: List[int] = []
|
| 609 |
+
self.block_tables: List[List[int]] = []
|
| 610 |
+
self.curr_seq_lens: List[int] = []
|
| 611 |
+
self.multimodal_placeholder_maps: Dict[
|
| 612 |
+
str,
|
| 613 |
+
MultiModalPlaceholderMap] = defaultdict(MultiModalPlaceholderMap)
|
| 614 |
+
self.num_prefills = 0
|
| 615 |
+
self.num_prefill_tokens = 0
|
| 616 |
+
self.num_decode_tokens = 0
|
| 617 |
+
|
| 618 |
+
# Please follow https://docs.flashinfer.ai/tutorials/kv_layout.html#page-layout
|
| 619 |
+
# for the precise definition of the following fields.
|
| 620 |
+
# An example:
|
| 621 |
+
# request 1, page indices [0, 5, 8]
|
| 622 |
+
# request 2, page indices [1, 6, 7]
|
| 623 |
+
# request 3, page indices [3, 4]
|
| 624 |
+
# paged_kv_indices is a concatenation of page indices of all requests:
|
| 625 |
+
# [0, 5, 8, 1, 6, 7, 3, 4]
|
| 626 |
+
# paged_kv_indptr is used to index into paged_kv_indices:
|
| 627 |
+
# [0, 3, 6, 8]
|
| 628 |
+
self.paged_kv_indices: List[int] = []
|
| 629 |
+
# 0 at the beginning of paged_kv_indptr indicates the start of the
|
| 630 |
+
# first request’s page indices in the paged_kv_indices list.
|
| 631 |
+
self.paged_kv_indptr: List[int] = [0]
|
| 632 |
+
# paged_kv_last_page_len is the length of the last page of each request
|
| 633 |
+
self.paged_kv_last_page_len: List[int] = []
|
| 634 |
+
self.total_blocks = 0
|
| 635 |
+
self.is_profile_run: bool = False
|
| 636 |
+
|
| 637 |
+
if self.global_hyperparameters is None:
|
| 638 |
+
# Infer global hyperparameters, since currently we only support
|
| 639 |
+
# models in which all layers share the same values for the
|
| 640 |
+
# following hyperparameters:
|
| 641 |
+
# - `window_left`
|
| 642 |
+
# - `logits_soft_cap`
|
| 643 |
+
# - `sm_scale`
|
| 644 |
+
inferred_params = infer_global_hyperparameters(
|
| 645 |
+
get_per_layer_parameters(self.vllm_config))
|
| 646 |
+
self.global_hyperparameters = inferred_params
|
| 647 |
+
self.window_left = inferred_params.window_left
|
| 648 |
+
self.logits_soft_cap = inferred_params.logits_soft_cap
|
| 649 |
+
self.sm_scale = inferred_params.sm_scale
|
| 650 |
+
|
| 651 |
+
def _add_seq_group(
|
| 652 |
+
self, inter_data: "ModelInputForGPUBuilder.InterDataForSeqGroup",
|
| 653 |
+
chunked_prefill_enabled: bool):
|
| 654 |
+
"""Add a sequence group to the metadata. Specifically update/append
|
| 655 |
+
1. context length.
|
| 656 |
+
2. block table.
|
| 657 |
+
3. slot mapping.
|
| 658 |
+
"""
|
| 659 |
+
is_prompt = inter_data.is_prompt
|
| 660 |
+
block_tables = inter_data.block_tables
|
| 661 |
+
computed_block_nums = inter_data.computed_block_nums
|
| 662 |
+
|
| 663 |
+
for (seq_id, token_len, seq_len, curr_seq_len, query_len, context_len,
|
| 664 |
+
curr_sliding_window_block) in zip(
|
| 665 |
+
inter_data.seq_ids, [len(t) for t in inter_data.input_tokens],
|
| 666 |
+
inter_data.orig_seq_lens, inter_data.seq_lens,
|
| 667 |
+
inter_data.query_lens, inter_data.context_lens,
|
| 668 |
+
inter_data.curr_sliding_window_blocks):
|
| 669 |
+
self.context_lens.append(context_len)
|
| 670 |
+
if is_prompt:
|
| 671 |
+
mm_maps = inter_data.multi_modal_placeholder_maps
|
| 672 |
+
if mm_maps:
|
| 673 |
+
for modality, placeholders in mm_maps.items():
|
| 674 |
+
self.multimodal_placeholder_maps[modality].extend(
|
| 675 |
+
placeholders)
|
| 676 |
+
self.num_prefills += 1
|
| 677 |
+
self.num_prefill_tokens += token_len
|
| 678 |
+
self.prefill_seq_lens.append(seq_len)
|
| 679 |
+
else:
|
| 680 |
+
assert query_len == 1, (
|
| 681 |
+
"seq_len: {}, context_len: {}, query_len: {}".format(
|
| 682 |
+
seq_len, context_len, query_len))
|
| 683 |
+
self.num_decode_tokens += query_len
|
| 684 |
+
self.curr_seq_lens.append(curr_seq_len)
|
| 685 |
+
|
| 686 |
+
# Compute block table.
|
| 687 |
+
# TODO(sang): Combine chunked prefill and prefix caching by
|
| 688 |
+
# only allowing multiple of block_size chunk size.
|
| 689 |
+
# NOTE: This only works for oooooooxxx style attention.
|
| 690 |
+
block_table = []
|
| 691 |
+
if inter_data.prefix_cache_hit:
|
| 692 |
+
block_table = computed_block_nums
|
| 693 |
+
elif ((chunked_prefill_enabled or not is_prompt)
|
| 694 |
+
and block_tables is not None):
|
| 695 |
+
block_table = block_tables[seq_id][-curr_sliding_window_block:]
|
| 696 |
+
self.block_tables.append(block_table)
|
| 697 |
+
|
| 698 |
+
is_profile_run = is_block_tables_empty(block_tables)
|
| 699 |
+
|
| 700 |
+
# Compute slot mapping.
|
| 701 |
+
start_idx = compute_slot_mapping_start_idx(is_prompt, query_len,
|
| 702 |
+
context_len,
|
| 703 |
+
self.sliding_window)
|
| 704 |
+
compute_slot_mapping(is_profile_run, self.slot_mapping, seq_id,
|
| 705 |
+
seq_len, context_len, start_idx,
|
| 706 |
+
self.block_size, inter_data.block_tables)
|
| 707 |
+
|
| 708 |
+
# It is not necessary to add paged_kv_indices, paged_kv_indptr,
|
| 709 |
+
# and paged_kv_last_page_len for profile run because we will
|
| 710 |
+
# create dummy inputs.
|
| 711 |
+
if is_profile_run:
|
| 712 |
+
self.is_profile_run = is_profile_run
|
| 713 |
+
return
|
| 714 |
+
|
| 715 |
+
block_table = block_tables[seq_id]
|
| 716 |
+
self._update_paged_kv_tensors(block_table, seq_len)
|
| 717 |
+
|
| 718 |
+
def _update_paged_kv_tensors(self, block_table: List[int], seq_len: int):
|
| 719 |
+
# Get the number of valid blocks based on sequence length.
|
| 720 |
+
# If seq_len = 16, block_size = 16,
|
| 721 |
+
# block_table_bound is 1 with 1 valid block.
|
| 722 |
+
# If seq_len = 15, block_size = 16,
|
| 723 |
+
# block_table_bound is 0 + 1 with 1 valid block.
|
| 724 |
+
self.total_blocks += len(block_table)
|
| 725 |
+
block_table_bound = seq_len // self.block_size + 1 \
|
| 726 |
+
if seq_len % self.block_size != 0 \
|
| 727 |
+
else seq_len // self.block_size
|
| 728 |
+
self.paged_kv_indices.extend(block_table[:block_table_bound])
|
| 729 |
+
self.paged_kv_indptr.append(self.paged_kv_indptr[-1] +
|
| 730 |
+
block_table_bound)
|
| 731 |
+
|
| 732 |
+
last_page_len = seq_len % self.block_size
|
| 733 |
+
if last_page_len == 0:
|
| 734 |
+
last_page_len = self.block_size
|
| 735 |
+
self.paged_kv_last_page_len.append(last_page_len)
|
| 736 |
+
|
| 737 |
+
def build(self, seq_lens: List[int], query_lens: List[int],
|
| 738 |
+
cuda_graph_pad_size: int, batch_size: int):
|
| 739 |
+
"""Build attention metadata with on-device tensors.
|
| 740 |
+
|
| 741 |
+
Args:
|
| 742 |
+
seq_lens: The maybe padded sequence lengths of the input sequences.
|
| 743 |
+
query_lens: The query lengths of the input sequences.
|
| 744 |
+
cuda_graph_pad_size: The padding size for cuda graph.
|
| 745 |
+
-1 if cuda graph is not used.
|
| 746 |
+
batch_size: The maybe padded batch size.
|
| 747 |
+
"""
|
| 748 |
+
for inter_data in self.input_builder.inter_data_list:
|
| 749 |
+
self._add_seq_group(inter_data,
|
| 750 |
+
self.input_builder.chunked_prefill_enabled)
|
| 751 |
+
|
| 752 |
+
device = self.runner.device
|
| 753 |
+
use_captured_graph = cuda_graph_pad_size != -1
|
| 754 |
+
|
| 755 |
+
max_prefill_seq_len = max(self.prefill_seq_lens, default=0)
|
| 756 |
+
max_decode_seq_len = max(self.curr_seq_lens, default=0)
|
| 757 |
+
num_decode_tokens = self.num_decode_tokens
|
| 758 |
+
decode_query_len = max(query_lens[self.num_prefills:], default=1)
|
| 759 |
+
|
| 760 |
+
if use_captured_graph:
|
| 761 |
+
self.slot_mapping.extend([PAD_SLOT_ID] * cuda_graph_pad_size)
|
| 762 |
+
self.block_tables.extend([] * cuda_graph_pad_size)
|
| 763 |
+
num_decode_tokens = batch_size - self.num_prefill_tokens
|
| 764 |
+
|
| 765 |
+
# The shape of graph_block_tables is
|
| 766 |
+
# [max batch size, max context len // block size].
|
| 767 |
+
input_block_tables = self.runner.graph_block_tables[:batch_size]
|
| 768 |
+
max_blocks = input_block_tables.shape[1]
|
| 769 |
+
for i, block_table in enumerate(self.block_tables):
|
| 770 |
+
if block_table:
|
| 771 |
+
num_blocks = len(block_table)
|
| 772 |
+
if num_blocks <= max_blocks:
|
| 773 |
+
input_block_tables[i, :num_blocks] = block_table
|
| 774 |
+
else:
|
| 775 |
+
# It may be possible to have more blocks allocated due
|
| 776 |
+
# to lookahead slots of multi-step, however, they are
|
| 777 |
+
# not used anyway, so can be safely ignored.
|
| 778 |
+
input_block_tables[
|
| 779 |
+
i, :max_blocks] = block_table[:max_blocks]
|
| 780 |
+
|
| 781 |
+
block_tables = torch.from_numpy(input_block_tables).to(
|
| 782 |
+
device, non_blocking=True)
|
| 783 |
+
|
| 784 |
+
last_paged_kv_indptr = self.paged_kv_indptr[-1]
|
| 785 |
+
self.paged_kv_indptr.extend([last_paged_kv_indptr] *
|
| 786 |
+
cuda_graph_pad_size)
|
| 787 |
+
self.paged_kv_last_page_len.extend([0] * cuda_graph_pad_size)
|
| 788 |
+
else:
|
| 789 |
+
block_tables = make_tensor_with_pad(
|
| 790 |
+
self.block_tables,
|
| 791 |
+
pad=0,
|
| 792 |
+
dtype=torch.int,
|
| 793 |
+
device=device,
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
assert device is not None
|
| 797 |
+
seq_lens_tensor = async_tensor_h2d(seq_lens, torch.int, device,
|
| 798 |
+
self.runner.pin_memory)
|
| 799 |
+
query_lens_tensor = async_tensor_h2d(query_lens, torch.long, device,
|
| 800 |
+
self.runner.pin_memory)
|
| 801 |
+
slot_mapping_tensor = async_tensor_h2d(self.slot_mapping, torch.long,
|
| 802 |
+
device, self.runner.pin_memory)
|
| 803 |
+
query_start_loc = torch.zeros(query_lens_tensor.shape[0] + 1,
|
| 804 |
+
dtype=torch.int32,
|
| 805 |
+
device=device)
|
| 806 |
+
seq_start_loc = torch.zeros(seq_lens_tensor.shape[0] + 1,
|
| 807 |
+
dtype=torch.int32,
|
| 808 |
+
device=device)
|
| 809 |
+
placeholder_index_maps = {
|
| 810 |
+
modality: placeholder_map.index_map()
|
| 811 |
+
for modality, placeholder_map in
|
| 812 |
+
self.multimodal_placeholder_maps.items()
|
| 813 |
+
}
|
| 814 |
+
torch.cumsum(seq_lens_tensor,
|
| 815 |
+
dim=0,
|
| 816 |
+
dtype=seq_start_loc.dtype,
|
| 817 |
+
out=seq_start_loc[1:])
|
| 818 |
+
torch.cumsum(query_lens_tensor,
|
| 819 |
+
dim=0,
|
| 820 |
+
dtype=query_start_loc.dtype,
|
| 821 |
+
out=query_start_loc[1:])
|
| 822 |
+
|
| 823 |
+
if len(self.paged_kv_indptr) > 0:
|
| 824 |
+
# extend to the maximum number of blocks as returned by the
|
| 825 |
+
# scheduler
|
| 826 |
+
self.paged_kv_indices.extend(
|
| 827 |
+
[0] * (self.total_blocks - len(self.paged_kv_indices)))
|
| 828 |
+
paged_kv_indices_tensor = torch.tensor(self.paged_kv_indices,
|
| 829 |
+
device="cpu",
|
| 830 |
+
dtype=torch.int)
|
| 831 |
+
paged_kv_indptr_tensor = torch.tensor(self.paged_kv_indptr,
|
| 832 |
+
device="cpu",
|
| 833 |
+
dtype=torch.int)
|
| 834 |
+
paged_kv_last_page_len_tensor = torch.tensor(
|
| 835 |
+
self.paged_kv_last_page_len, device="cpu", dtype=torch.int)
|
| 836 |
+
block_table_bound_tensor = torch.zeros(len(self.paged_kv_indptr) -
|
| 837 |
+
1,
|
| 838 |
+
device="cpu",
|
| 839 |
+
dtype=torch.int)
|
| 840 |
+
else:
|
| 841 |
+
paged_kv_indices_tensor = None
|
| 842 |
+
paged_kv_indptr_tensor = None
|
| 843 |
+
paged_kv_last_page_len_tensor = None
|
| 844 |
+
block_table_bound_tensor = None
|
| 845 |
+
|
| 846 |
+
if self.runner.kv_cache_dtype.startswith("fp8"):
|
| 847 |
+
kv_cache_dtype = FlashInferBackend.get_fp8_dtype_for_flashinfer(
|
| 848 |
+
self.runner.kv_cache_dtype)
|
| 849 |
+
else:
|
| 850 |
+
kv_cache_dtype = get_kv_cache_torch_dtype(
|
| 851 |
+
self.runner.kv_cache_dtype, self.runner.model_config.dtype)
|
| 852 |
+
|
| 853 |
+
return FlashInferMetadata(
|
| 854 |
+
decode_query_len=decode_query_len,
|
| 855 |
+
num_prefills=self.num_prefills,
|
| 856 |
+
slot_mapping=slot_mapping_tensor,
|
| 857 |
+
multi_modal_placeholder_index_maps=placeholder_index_maps,
|
| 858 |
+
enable_kv_scales_calculation=False,
|
| 859 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 860 |
+
num_decode_tokens=num_decode_tokens,
|
| 861 |
+
max_prefill_seq_len=max_prefill_seq_len,
|
| 862 |
+
max_decode_seq_len=max_decode_seq_len,
|
| 863 |
+
block_tables=block_tables,
|
| 864 |
+
paged_kv_indptr=paged_kv_indptr_tensor,
|
| 865 |
+
paged_kv_indices=paged_kv_indices_tensor,
|
| 866 |
+
paged_kv_last_page_len=paged_kv_last_page_len_tensor,
|
| 867 |
+
block_table_bound=block_table_bound_tensor,
|
| 868 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 869 |
+
num_qo_heads=self.runner.model_config.get_num_attention_heads(
|
| 870 |
+
self.runner.parallel_config),
|
| 871 |
+
num_kv_heads=self.runner.model_config.get_num_kv_heads(
|
| 872 |
+
self.runner.parallel_config),
|
| 873 |
+
head_dim=self.runner.model_config.get_head_size(),
|
| 874 |
+
page_size=self.block_size,
|
| 875 |
+
seq_start_loc=seq_start_loc,
|
| 876 |
+
query_start_loc=query_start_loc,
|
| 877 |
+
device=device,
|
| 878 |
+
data_type=kv_cache_dtype,
|
| 879 |
+
q_data_type=self.runner.model_config.dtype,
|
| 880 |
+
use_cuda_graph=use_captured_graph,
|
| 881 |
+
is_profile_run=self.is_profile_run,
|
| 882 |
+
window_left=self.window_left,
|
| 883 |
+
logits_soft_cap=self.logits_soft_cap,
|
| 884 |
+
sm_scale=self.sm_scale,
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
class FlashInferImpl(AttentionImpl):
|
| 889 |
+
|
| 890 |
+
def __init__(
|
| 891 |
+
self,
|
| 892 |
+
num_heads: int,
|
| 893 |
+
head_size: int,
|
| 894 |
+
scale: float,
|
| 895 |
+
num_kv_heads: int,
|
| 896 |
+
alibi_slopes: Optional[List[float]],
|
| 897 |
+
sliding_window: Optional[int],
|
| 898 |
+
kv_cache_dtype: str,
|
| 899 |
+
logits_soft_cap: Optional[float] = None,
|
| 900 |
+
attn_type: str = AttentionType.DECODER,
|
| 901 |
+
kv_sharing_target_layer_name: Optional[str] = None,
|
| 902 |
+
use_irope: bool = False,
|
| 903 |
+
) -> None:
|
| 904 |
+
if kv_sharing_target_layer_name is not None:
|
| 905 |
+
raise NotImplementedError("KV sharing is not supported in V0 "
|
| 906 |
+
"FLASHINFER backend.")
|
| 907 |
+
if use_irope:
|
| 908 |
+
logger.warning_once(
|
| 909 |
+
"Using irope in FlashInfer is not supported yet, it will fall"
|
| 910 |
+
" back to global attention for long context.")
|
| 911 |
+
self.num_heads = num_heads
|
| 912 |
+
self.head_size = head_size
|
| 913 |
+
self.scale = float(scale)
|
| 914 |
+
self.num_kv_heads = num_kv_heads
|
| 915 |
+
if alibi_slopes is not None:
|
| 916 |
+
alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
|
| 917 |
+
self.alibi_slopes = alibi_slopes
|
| 918 |
+
self.sliding_window = ((sliding_window - 1,
|
| 919 |
+
0) if sliding_window is not None else (-1, -1))
|
| 920 |
+
self.kv_cache_dtype = kv_cache_dtype
|
| 921 |
+
self.logits_soft_cap = logits_soft_cap
|
| 922 |
+
|
| 923 |
+
self.num_queries_per_kv = self.num_heads // self.num_kv_heads
|
| 924 |
+
|
| 925 |
+
if attn_type != AttentionType.DECODER:
|
| 926 |
+
raise NotImplementedError("Encoder self-attention and "
|
| 927 |
+
"encoder/decoder cross-attention "
|
| 928 |
+
"are not implemented for "
|
| 929 |
+
"FlashInferImpl")
|
| 930 |
+
|
| 931 |
+
def forward(
|
| 932 |
+
self,
|
| 933 |
+
layer: AttentionLayer,
|
| 934 |
+
query: torch.Tensor,
|
| 935 |
+
key: torch.Tensor,
|
| 936 |
+
value: torch.Tensor,
|
| 937 |
+
kv_cache: torch.Tensor,
|
| 938 |
+
attn_metadata: FlashInferMetadata,
|
| 939 |
+
output: Optional[torch.Tensor] = None,
|
| 940 |
+
output_scale: Optional[torch.Tensor] = None,
|
| 941 |
+
) -> torch.Tensor:
|
| 942 |
+
|
| 943 |
+
if output_scale is not None:
|
| 944 |
+
raise NotImplementedError(
|
| 945 |
+
"fused output quantization is not yet supported"
|
| 946 |
+
" for FlashInferImpl")
|
| 947 |
+
|
| 948 |
+
# TODO: directly write to output tensor
|
| 949 |
+
num_heads: int = self.num_heads
|
| 950 |
+
head_size: int = self.head_size
|
| 951 |
+
num_kv_heads: int = self.num_kv_heads
|
| 952 |
+
kv_cache_dtype: str = self.kv_cache_dtype
|
| 953 |
+
softmax_scale: float = self.scale
|
| 954 |
+
window_size = self.sliding_window
|
| 955 |
+
alibi_slopes = self.alibi_slopes
|
| 956 |
+
logits_soft_cap = self.logits_soft_cap
|
| 957 |
+
|
| 958 |
+
num_tokens, hidden_size = query.shape
|
| 959 |
+
query = query.view(-1, num_heads, head_size)
|
| 960 |
+
key = key.view(-1, num_kv_heads, head_size)
|
| 961 |
+
value = value.view(-1, num_kv_heads, head_size)
|
| 962 |
+
|
| 963 |
+
if kv_cache.numel() > 0:
|
| 964 |
+
# Use the same reshape and cache kernel as flash attention.
|
| 965 |
+
ops.reshape_and_cache_flash(
|
| 966 |
+
key,
|
| 967 |
+
value,
|
| 968 |
+
kv_cache[:, 0],
|
| 969 |
+
kv_cache[:, 1],
|
| 970 |
+
attn_metadata.slot_mapping.flatten(),
|
| 971 |
+
kv_cache_dtype,
|
| 972 |
+
layer._k_scale,
|
| 973 |
+
layer._v_scale,
|
| 974 |
+
)
|
| 975 |
+
# The FlashInfer api requires data to be in fp8_e4m3 or fp8_e5m2
|
| 976 |
+
# to process the cache when the kv_cache_dtype is fp8
|
| 977 |
+
if kv_cache_dtype.startswith("fp8"):
|
| 978 |
+
torch_dtype = FlashInferBackend.get_fp8_dtype_for_flashinfer(
|
| 979 |
+
kv_cache_dtype)
|
| 980 |
+
kv_cache = kv_cache.view(torch_dtype)
|
| 981 |
+
|
| 982 |
+
num_prefill_tokens = attn_metadata.num_prefill_tokens
|
| 983 |
+
num_decode_tokens = attn_metadata.num_decode_tokens
|
| 984 |
+
assert key.shape[0] == num_prefill_tokens + num_decode_tokens, \
|
| 985 |
+
f"key : {key.shape} : #prefill tokens {num_prefill_tokens} : #decode tokens {num_decode_tokens}" # noqa
|
| 986 |
+
assert value.shape[0] == num_prefill_tokens + num_decode_tokens, \
|
| 987 |
+
f"value : {value.shape} : #prefill toks {num_prefill_tokens} : #decode toks {num_decode_tokens}" # noqa
|
| 988 |
+
query = query.contiguous(
|
| 989 |
+
) # Flashinfer requires query to be contiguous
|
| 990 |
+
# Query for decode. KV is not needed because it is already cached.
|
| 991 |
+
# QKV for prefill.
|
| 992 |
+
decode_query = query[num_prefill_tokens:]
|
| 993 |
+
query = query[:num_prefill_tokens]
|
| 994 |
+
|
| 995 |
+
key = key[:num_prefill_tokens]
|
| 996 |
+
value = value[:num_prefill_tokens]
|
| 997 |
+
|
| 998 |
+
assert query.shape[0] == num_prefill_tokens
|
| 999 |
+
assert decode_query.shape[0] == num_decode_tokens
|
| 1000 |
+
|
| 1001 |
+
window_left = window_size[0] if window_size is not None else -1
|
| 1002 |
+
|
| 1003 |
+
prefill_output: Optional[torch.Tensor] = None
|
| 1004 |
+
if num_decode_tokens > 0:
|
| 1005 |
+
decode_output = torch.empty(decode_query.shape,
|
| 1006 |
+
dtype=decode_query.dtype,
|
| 1007 |
+
device=decode_query.device)
|
| 1008 |
+
else:
|
| 1009 |
+
decode_output = None
|
| 1010 |
+
stride_order = FlashInferBackend.get_kv_cache_stride_order()
|
| 1011 |
+
if prefill_meta := attn_metadata.prefill_metadata:
|
| 1012 |
+
# We will use flash attention for prefill
|
| 1013 |
+
# when kv_cache is not provided.
|
| 1014 |
+
# This happens when vllm runs the profiling to
|
| 1015 |
+
# determine the number of blocks.
|
| 1016 |
+
if kv_cache.numel() == 0:
|
| 1017 |
+
prefill_output = flash_attn_varlen_func(
|
| 1018 |
+
q=query,
|
| 1019 |
+
k=key,
|
| 1020 |
+
v=value,
|
| 1021 |
+
cu_seqlens_q=prefill_meta.seq_start_loc,
|
| 1022 |
+
cu_seqlens_k=prefill_meta.seq_start_loc,
|
| 1023 |
+
max_seqlen_q=prefill_meta.max_prefill_seq_len,
|
| 1024 |
+
max_seqlen_k=prefill_meta.max_prefill_seq_len,
|
| 1025 |
+
softmax_scale=softmax_scale,
|
| 1026 |
+
causal=True,
|
| 1027 |
+
window_size=window_size,
|
| 1028 |
+
alibi_slopes=alibi_slopes,
|
| 1029 |
+
)
|
| 1030 |
+
else:
|
| 1031 |
+
assert prefill_meta is not None
|
| 1032 |
+
assert prefill_meta.prefill_wrapper is not None
|
| 1033 |
+
|
| 1034 |
+
assert prefill_meta.prefill_wrapper._causal
|
| 1035 |
+
assert prefill_meta.prefill_wrapper._window_left == window_left
|
| 1036 |
+
assert prefill_meta.prefill_wrapper._logits_soft_cap == (
|
| 1037 |
+
logits_soft_cap or 0.0)
|
| 1038 |
+
assert prefill_meta.prefill_wrapper._sm_scale == softmax_scale
|
| 1039 |
+
|
| 1040 |
+
prefill_output = prefill_meta.prefill_wrapper.run(
|
| 1041 |
+
query,
|
| 1042 |
+
kv_cache.permute(*stride_order),
|
| 1043 |
+
k_scale=layer._k_scale_float,
|
| 1044 |
+
v_scale=layer._v_scale_float,
|
| 1045 |
+
)
|
| 1046 |
+
if decode_meta := attn_metadata.decode_metadata:
|
| 1047 |
+
assert decode_meta is not None
|
| 1048 |
+
assert decode_meta.decode_wrapper is not None
|
| 1049 |
+
|
| 1050 |
+
assert decode_meta.decode_wrapper._window_left == window_left
|
| 1051 |
+
assert decode_meta.decode_wrapper._logits_soft_cap == (
|
| 1052 |
+
logits_soft_cap or 0.0)
|
| 1053 |
+
assert decode_meta.decode_wrapper._sm_scale == softmax_scale
|
| 1054 |
+
# TODO: @pavanimajety Remove this once the switch happens
|
| 1055 |
+
# inside flashinfer.
|
| 1056 |
+
if not use_trtllm_attention(
|
| 1057 |
+
num_decode_tokens, attn_metadata.max_decode_seq_len,
|
| 1058 |
+
kv_cache_dtype, attn_metadata.num_qo_heads,
|
| 1059 |
+
attn_metadata.num_kv_heads, attn_metadata.head_dim):
|
| 1060 |
+
decode_meta.decode_wrapper.run(
|
| 1061 |
+
decode_query,
|
| 1062 |
+
kv_cache.permute(*stride_order),
|
| 1063 |
+
k_scale=layer._k_scale_float,
|
| 1064 |
+
v_scale=layer._v_scale_float,
|
| 1065 |
+
out=decode_output,
|
| 1066 |
+
)
|
| 1067 |
+
else:
|
| 1068 |
+
workspace_buffer = (
|
| 1069 |
+
decode_meta.decode_wrapper._float_workspace_buffer)
|
| 1070 |
+
assert FlashInferState.get_kv_cache_layout() == "HND"
|
| 1071 |
+
trtllm_batch_decode_with_kv_cache(
|
| 1072 |
+
query=decode_query,
|
| 1073 |
+
kv_cache=kv_cache.permute(*stride_order),
|
| 1074 |
+
workspace_buffer=workspace_buffer,
|
| 1075 |
+
block_tables=attn_metadata.block_tables,
|
| 1076 |
+
seq_lens=decode_meta.seq_lens_tensor,
|
| 1077 |
+
max_seq_len=attn_metadata.max_decode_seq_len,
|
| 1078 |
+
bmm1_scale=layer._k_scale_float * softmax_scale,
|
| 1079 |
+
bmm2_scale=layer._v_scale_float,
|
| 1080 |
+
out=decode_output,
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
if prefill_output is None and decode_output is not None:
|
| 1084 |
+
# Decode only batch.
|
| 1085 |
+
output, num_tokens = decode_output, num_decode_tokens
|
| 1086 |
+
elif decode_output is None and prefill_output is not None:
|
| 1087 |
+
# Prefill only batch.
|
| 1088 |
+
output, num_tokens = prefill_output, num_prefill_tokens
|
| 1089 |
+
else:
|
| 1090 |
+
# Chunked prefill batch does not work with speculative decoding in
|
| 1091 |
+
# FlashInfer backend, so the query length for decode should be 1.
|
| 1092 |
+
assert prefill_output is not None
|
| 1093 |
+
assert decode_output is not None
|
| 1094 |
+
assert decode_meta is not None
|
| 1095 |
+
assert decode_meta.decode_query_len == 1
|
| 1096 |
+
decode_output = decode_output.squeeze(1)
|
| 1097 |
+
output = torch.cat([prefill_output, decode_output], dim=0)
|
| 1098 |
+
return output.view(num_tokens, hidden_size)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/flashmla.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import List, Optional, Tuple, Type
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from vllm.attention.backends.abstract import (AttentionType,
|
| 11 |
+
is_quantized_kv_cache)
|
| 12 |
+
from vllm.attention.backends.mla.common import (MLACommonBackend,
|
| 13 |
+
MLACommonImpl,
|
| 14 |
+
MLACommonMetadata,
|
| 15 |
+
MLACommonMetadataBuilder,
|
| 16 |
+
MLACommonState)
|
| 17 |
+
from vllm.attention.ops.flashmla import (flash_mla_with_kvcache,
|
| 18 |
+
get_mla_metadata,
|
| 19 |
+
is_flashmla_supported)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FlashMLABackend(MLACommonBackend):
|
| 23 |
+
|
| 24 |
+
@staticmethod
|
| 25 |
+
def get_name() -> str:
|
| 26 |
+
return "FLASHMLA"
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def get_impl_cls() -> Type["FlashMLAImpl"]:
|
| 30 |
+
return FlashMLAImpl
|
| 31 |
+
|
| 32 |
+
@staticmethod
|
| 33 |
+
def get_metadata_cls() -> Type["FlashMLAMetadata"]:
|
| 34 |
+
return FlashMLAMetadata
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def get_builder_cls() -> Type["FlashMLAMetadataBuilder"]:
|
| 38 |
+
return FlashMLAMetadataBuilder
|
| 39 |
+
|
| 40 |
+
@staticmethod
|
| 41 |
+
def get_state_cls() -> Type["FlashMLAState"]:
|
| 42 |
+
return FlashMLAState
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class FlashMLAMetadata(MLACommonMetadata):
|
| 47 |
+
decode_tile_scheduler_metadata: Optional[Tuple[torch.Tensor,
|
| 48 |
+
torch.Tensor]] = None
|
| 49 |
+
decode_num_splits: Optional[torch.Tensor] = None
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def decode_metadata(self):
|
| 53 |
+
decode_metadata = super().decode_metadata
|
| 54 |
+
# TODO: cache assignment?
|
| 55 |
+
if decode_metadata is not None:
|
| 56 |
+
decode_metadata.decode_tile_scheduler_metadata=\
|
| 57 |
+
self.decode_tile_scheduler_metadata
|
| 58 |
+
decode_metadata.decode_num_splits=\
|
| 59 |
+
self.decode_num_splits
|
| 60 |
+
return decode_metadata
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class FlashMLAMetadataBuilder(MLACommonMetadataBuilder[FlashMLAMetadata]):
|
| 64 |
+
|
| 65 |
+
def __init__(self, *args, **kwargs):
|
| 66 |
+
super().__init__(*args, **kwargs)
|
| 67 |
+
|
| 68 |
+
self.num_q_heads = self.runner.model_config.get_num_attention_heads(
|
| 69 |
+
self.runner.parallel_config)
|
| 70 |
+
|
| 71 |
+
def build(self, seq_lens: List[int], query_lens: List[int],
|
| 72 |
+
cuda_graph_pad_size: int, batch_size: int):
|
| 73 |
+
m = super().build(seq_lens, query_lens, cuda_graph_pad_size,
|
| 74 |
+
batch_size)
|
| 75 |
+
|
| 76 |
+
if m.num_decode_tokens > 0:
|
| 77 |
+
m.decode_tile_scheduler_metadata, m.decode_num_splits = \
|
| 78 |
+
get_mla_metadata(
|
| 79 |
+
m.seq_lens_tensor[m.num_prefills:],
|
| 80 |
+
self.num_q_heads,
|
| 81 |
+
1, # MQA for the decode path
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
return m
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class FlashMLAState(MLACommonState[FlashMLAMetadata]):
|
| 88 |
+
|
| 89 |
+
def __init__(self, *args, **kwds):
|
| 90 |
+
super().__init__(*args, **kwds)
|
| 91 |
+
|
| 92 |
+
self.num_q_heads = self.runner.model_config.get_num_attention_heads(
|
| 93 |
+
self.runner.parallel_config)
|
| 94 |
+
|
| 95 |
+
@contextmanager
|
| 96 |
+
def graph_capture(self, max_batch_size: int):
|
| 97 |
+
# Run a dummy `get_mla_metadata` so we can get the right shapes
|
| 98 |
+
self._graph_decoder_tile_scheduler_metadata, \
|
| 99 |
+
self._graph_decode_num_splits = get_mla_metadata(
|
| 100 |
+
torch.ones(
|
| 101 |
+
max_batch_size, dtype=torch.int32, device=self.runner.device),
|
| 102 |
+
self.num_q_heads,
|
| 103 |
+
1, # MQA for the decode path
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
with super().graph_capture(max_batch_size):
|
| 107 |
+
yield
|
| 108 |
+
|
| 109 |
+
del self._graph_decoder_tile_scheduler_metadata
|
| 110 |
+
del self._graph_decode_num_splits
|
| 111 |
+
|
| 112 |
+
def graph_capture_get_metadata_for_batch(
|
| 113 |
+
self, batch_size: int, is_encoder_decoder_model: bool = False):
|
| 114 |
+
metadata = super().graph_capture_get_metadata_for_batch(
|
| 115 |
+
batch_size, is_encoder_decoder_model)
|
| 116 |
+
assert metadata.num_decode_tokens > 0
|
| 117 |
+
|
| 118 |
+
decoder_tile_scheduler_metadata, decode_num_splits = get_mla_metadata(
|
| 119 |
+
self._graph_seq_lens[:batch_size],
|
| 120 |
+
self.num_q_heads,
|
| 121 |
+
1, # MQA for the decode path
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
self._graph_decoder_tile_scheduler_metadata.copy_(
|
| 125 |
+
decoder_tile_scheduler_metadata)
|
| 126 |
+
self._graph_decode_num_splits[:batch_size + 1].copy_(decode_num_splits)
|
| 127 |
+
|
| 128 |
+
metadata.decode_tile_scheduler_metadata=\
|
| 129 |
+
self._graph_decoder_tile_scheduler_metadata
|
| 130 |
+
metadata.decode_num_splits=\
|
| 131 |
+
self._graph_decode_num_splits[:batch_size + 1]
|
| 132 |
+
|
| 133 |
+
return metadata
|
| 134 |
+
|
| 135 |
+
def get_graph_input_buffers(self,
|
| 136 |
+
attn_metadata,
|
| 137 |
+
is_encoder_decoder_model: bool = False):
|
| 138 |
+
input_buffers = super().get_graph_input_buffers(
|
| 139 |
+
attn_metadata, is_encoder_decoder_model)
|
| 140 |
+
input_buffers["decode_tile_scheduler_metadata"] = \
|
| 141 |
+
attn_metadata.decode_metadata.decode_tile_scheduler_metadata
|
| 142 |
+
input_buffers["decode_num_splits"] = \
|
| 143 |
+
attn_metadata.decode_metadata.decode_num_splits
|
| 144 |
+
|
| 145 |
+
return input_buffers
|
| 146 |
+
|
| 147 |
+
def prepare_graph_input_buffers(self,
|
| 148 |
+
input_buffers,
|
| 149 |
+
attn_metadata,
|
| 150 |
+
is_encoder_decoder_model: bool = False):
|
| 151 |
+
super().prepare_graph_input_buffers(input_buffers, attn_metadata,
|
| 152 |
+
is_encoder_decoder_model)
|
| 153 |
+
|
| 154 |
+
input_buffers["decode_tile_scheduler_metadata"].copy_(
|
| 155 |
+
attn_metadata.decode_metadata.decode_tile_scheduler_metadata)
|
| 156 |
+
input_buffers["decode_num_splits"].copy_(
|
| 157 |
+
attn_metadata.decode_metadata.decode_num_splits)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class FlashMLAImpl(MLACommonImpl[FlashMLAMetadata]):
|
| 161 |
+
|
| 162 |
+
def __init__(
|
| 163 |
+
self,
|
| 164 |
+
num_heads: int,
|
| 165 |
+
head_size: int,
|
| 166 |
+
scale: float,
|
| 167 |
+
num_kv_heads: int,
|
| 168 |
+
alibi_slopes: Optional[List[float]],
|
| 169 |
+
sliding_window: Optional[int],
|
| 170 |
+
kv_cache_dtype: str,
|
| 171 |
+
logits_soft_cap: Optional[float],
|
| 172 |
+
attn_type: str,
|
| 173 |
+
kv_sharing_target_layer_name: Optional[str] = None,
|
| 174 |
+
# MLA Specific Arguments
|
| 175 |
+
**mla_args) -> None:
|
| 176 |
+
super().__init__(num_heads, head_size, scale, num_kv_heads,
|
| 177 |
+
alibi_slopes, sliding_window, kv_cache_dtype,
|
| 178 |
+
logits_soft_cap, attn_type,
|
| 179 |
+
kv_sharing_target_layer_name, **mla_args)
|
| 180 |
+
|
| 181 |
+
assert is_flashmla_supported(), \
|
| 182 |
+
"FlashMLA is not supported on this device"
|
| 183 |
+
|
| 184 |
+
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
|
| 185 |
+
if any(unsupported_features):
|
| 186 |
+
raise NotImplementedError(
|
| 187 |
+
"FlashMLAImpl does not support one of the following: "
|
| 188 |
+
"alibi_slopes, sliding_window, logits_soft_cap")
|
| 189 |
+
|
| 190 |
+
if attn_type != AttentionType.DECODER:
|
| 191 |
+
raise NotImplementedError("Encoder self-attention and "
|
| 192 |
+
"encoder/decoder cross-attention "
|
| 193 |
+
"are not implemented for "
|
| 194 |
+
"FlashMLAImpl")
|
| 195 |
+
|
| 196 |
+
if is_quantized_kv_cache(self.kv_cache_dtype):
|
| 197 |
+
raise NotImplementedError(
|
| 198 |
+
"FlashMLA with FP8 KV cache not yet supported")
|
| 199 |
+
|
| 200 |
+
def _forward_decode(
|
| 201 |
+
self,
|
| 202 |
+
q_nope: torch.Tensor,
|
| 203 |
+
q_pe: torch.Tensor,
|
| 204 |
+
kv_c_and_k_pe_cache: torch.Tensor,
|
| 205 |
+
attn_metadata: FlashMLAMetadata,
|
| 206 |
+
) -> torch.Tensor:
|
| 207 |
+
assert kv_c_and_k_pe_cache.numel() > 0
|
| 208 |
+
|
| 209 |
+
decode_meta = attn_metadata.decode_metadata
|
| 210 |
+
assert decode_meta is not None
|
| 211 |
+
|
| 212 |
+
q = torch.cat([q_nope, q_pe], dim=-1)\
|
| 213 |
+
.unsqueeze(1) # Add seqlen dim of 1 (decode)
|
| 214 |
+
|
| 215 |
+
o, _ = flash_mla_with_kvcache(
|
| 216 |
+
q=q,
|
| 217 |
+
k_cache=kv_c_and_k_pe_cache.unsqueeze(-2), # Add head dim of 1
|
| 218 |
+
block_table=decode_meta.block_tables,
|
| 219 |
+
cache_seqlens=decode_meta.seq_lens_tensor,
|
| 220 |
+
head_dim_v=self.kv_lora_rank,
|
| 221 |
+
tile_scheduler_metadata=decode_meta.decode_tile_scheduler_metadata,
|
| 222 |
+
num_splits=decode_meta.decode_num_splits,
|
| 223 |
+
softmax_scale=self.scale,
|
| 224 |
+
causal=True,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
return self._v_up_proj(o)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/mla/common.py
ADDED
|
@@ -0,0 +1,1305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
"""
|
| 4 |
+
# MLA Common Components
|
| 5 |
+
|
| 6 |
+
This file implements common components for MLA implementations.
|
| 7 |
+
|
| 8 |
+
First we define:
|
| 9 |
+
|
| 10 |
+
Sq as Q sequence length
|
| 11 |
+
Skv as KV sequence length
|
| 12 |
+
|
| 13 |
+
MLA has two possible ways of computing, a data-movement friendly approach and a
|
| 14 |
+
compute friendly approach, we generally want to use the compute friendly
|
| 15 |
+
approach for "prefill" (i.e. the ratio Sq / Skv is "small", is near 1)
|
| 16 |
+
and the data-movement friendly approach for "decode" (i.e. the ratio
|
| 17 |
+
Sq / Skv is "large").
|
| 18 |
+
|
| 19 |
+
NOTE what we deem small and large is currently determined by if its labelled
|
| 20 |
+
prefill or decode by the scheduler, but this is something we should probably
|
| 21 |
+
tune.
|
| 22 |
+
|
| 23 |
+
Main reference: DeepseekV2 paper, and FlashInfer Implementation
|
| 24 |
+
(https://arxiv.org/abs/2405.04434 and https://github.com/flashinfer-ai/flashinfer/pull/551).
|
| 25 |
+
|
| 26 |
+
Deepseek's MLA attention works the following way:
|
| 27 |
+
* Use a single latent vector to represent the per-token entry of the KV cache.
|
| 28 |
+
* For decode (i.e. the memory friendly approach) the attention "simulates" a
|
| 29 |
+
multi-head attention, while the compute is similar to multi-query attention.
|
| 30 |
+
|
| 31 |
+
Below is example of both paths assuming batchsize = 1
|
| 32 |
+
|
| 33 |
+
## More Extent Definitions:
|
| 34 |
+
|
| 35 |
+
C Context length, `Skv - Sq`
|
| 36 |
+
H hidden size
|
| 37 |
+
N number of attention heads
|
| 38 |
+
Lq latent dimension for Q 1536 in DSV3
|
| 39 |
+
Lkv latent dimension for K/V 512 in DSV3
|
| 40 |
+
P nope dimension, no rope. 128 in DSV3
|
| 41 |
+
R rope dimension, goes through rope. 64 in DSV3
|
| 42 |
+
V V head dim. 128 in DSV3
|
| 43 |
+
|
| 44 |
+
## Vector/Matrix Definitions
|
| 45 |
+
|
| 46 |
+
h_t hidden states (input to attention) shape [Sq, H]
|
| 47 |
+
q_c latent/compressed Q shape [Sq, Lq]
|
| 48 |
+
q_nope uncompressed Q (no-rope) shape [Sq, N, P]
|
| 49 |
+
q_pe uncompressed Q (rope) shape [Sq, N, R]
|
| 50 |
+
kv_c latent/compressed KV shape [Skv, Lkv]
|
| 51 |
+
k_pe decoupled k position embeddings shape [Skv, R]
|
| 52 |
+
new_kv_c new kv_c from current iter shape [Sq, Lkv]
|
| 53 |
+
new_k_pe new k_pe from current iter shape [Sq, R]
|
| 54 |
+
cache_kv_c cached k_c from previous iters shape [C, Lkv]
|
| 55 |
+
cache_k_pe cached k_pe from previous iters shape [C, R]
|
| 56 |
+
W_DQ project h_t to q_c shape [H, Lq]
|
| 57 |
+
W_UQ project q_c to q_nope shape [Lq, N * P]
|
| 58 |
+
W_QR project q_c to q_pe shape [Lq, N * R]
|
| 59 |
+
W_DKV project h_t to kv_c shape [H, Lkv]
|
| 60 |
+
W_UK project kv_c to k_nope shape [Lkv, N, P]
|
| 61 |
+
W_KR project h_t to k_pe shape [H, R]
|
| 62 |
+
W_UV project kv_c to v shape [Lkv, N, V]
|
| 63 |
+
W_O project v to h_t shape [N * V, H]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
## Compute Friendly Approach (i.e. "_forward_prefill"):
|
| 67 |
+
|
| 68 |
+
q_c = h_t @ W_DQ
|
| 69 |
+
q_nope = (q_c @ W_UQ).view(Sq, N, P)
|
| 70 |
+
q_pe = RoPE(q_c @ W_QR).view(Sq, N, R)
|
| 71 |
+
new_kv_c = h_t @ W_DKV
|
| 72 |
+
new_k_pe = RoPE(h_t @ W_KR)
|
| 73 |
+
kv_c = torch.cat([new_kv_c, cache_kv_c], dim=0)
|
| 74 |
+
k_pe = torch.cat([new_k_pe, cache_k_pe], dim=0)
|
| 75 |
+
k_nope = (kv_c @ W_UK.view(Lkv, N * P)).view(Skv, N, P)
|
| 76 |
+
v = (kv_c @ W_UV.view(Lkv, N * V)).view(Skv, N, V)
|
| 77 |
+
|
| 78 |
+
// MHA with QK headdim = P + R
|
| 79 |
+
// V headdim = V
|
| 80 |
+
// spda_o shape [Sq, N, V]
|
| 81 |
+
spda_o = scaled_dot_product_attention(
|
| 82 |
+
torch.cat([q_nope, q_pe], dim=-1),
|
| 83 |
+
torch.cat([k_nope, k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1),
|
| 84 |
+
v
|
| 85 |
+
)
|
| 86 |
+
return spda_o @ W_O
|
| 87 |
+
|
| 88 |
+
NOTE: in the actual code,
|
| 89 |
+
`kv_b_proj` is [W_UK; W_UV] concatenated per head
|
| 90 |
+
`q_b_proj` is [W_UQ; W_QR] concatenated per head
|
| 91 |
+
`out_proj` is W_O
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
## Data-Movement Friendly Approach (i.e. "_forward_decode"):
|
| 95 |
+
|
| 96 |
+
Runtime
|
| 97 |
+
q_c = h_t @ W_DQ
|
| 98 |
+
q_nope = (q_c @ W_UQ).view(-1, N, P)
|
| 99 |
+
ql_nope = einsum("snh,lnh->snl", q, W_UK)
|
| 100 |
+
q_pe = RoPE(q_c @ W_QR).view(Sq, N, R)
|
| 101 |
+
new_kv_c = h_t @ W_DKV
|
| 102 |
+
new_k_pe = RoPE(h_t @ W_KR)
|
| 103 |
+
kv_c = torch.cat([new_kv_c, cache_kv_c], dim=0)
|
| 104 |
+
k_pe = torch.cat([new_k_pe, cache_k_pe], dim=0)
|
| 105 |
+
|
| 106 |
+
// MQA with QK headdim = Lkv + R
|
| 107 |
+
// V headdim = Lkv
|
| 108 |
+
// spda_o shape [Sq, N, Lkv]
|
| 109 |
+
// NOTE: this is less compute-friendly since Lkv > P
|
| 110 |
+
// but is more data-movement friendly since its MQA vs MHA
|
| 111 |
+
spda_o = scaled_dot_product_attention(
|
| 112 |
+
torch.cat([ql_nope, q_pe], dim=-1),
|
| 113 |
+
torch.cat([kv_c, k_pe], dim=-1),
|
| 114 |
+
kv_c
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
o = einsum("snl,lnv->snv", spda_o.reshape(-1, N, Lkv), W_UV)
|
| 118 |
+
return o.view(-1, N * V) @ self.num_heads @ W_O
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
## Chunked Prefill
|
| 122 |
+
|
| 123 |
+
For chunked prefill we want to use the compute friendly algorithm. We are
|
| 124 |
+
assuming sufficiently large Sq / Skv ratio, in the future may want to switch to
|
| 125 |
+
the data-movement friendly approach if the chunk (i.e. `Sq`) is small.
|
| 126 |
+
|
| 127 |
+
However, the compute-friendly approach can potentially run out of memory if Skv
|
| 128 |
+
is large due to: `k_nope = (kv_c @ W_UK).view(Skv, N, P)`
|
| 129 |
+
|
| 130 |
+
To mitigate this, we chunk the computation of attention with respect to the
|
| 131 |
+
current context (i.e. `cache_kv_c` and `cache_k_pe`) so that we can used a
|
| 132 |
+
fixed workspace size.
|
| 133 |
+
|
| 134 |
+
The chunked prefill approach is as follows:
|
| 135 |
+
|
| 136 |
+
MCC Max chunk of context to process per iter, computed dynamically,
|
| 137 |
+
used to bound the memory usage
|
| 138 |
+
|
| 139 |
+
q_c = h_t @ W_DQ
|
| 140 |
+
q_nope = (q_c @ W_UQ).view(Sq, N, P)
|
| 141 |
+
q_pe = RoPE(q_c @ W_QR).view(Sq, N, R)
|
| 142 |
+
new_kv_c = h_t @ W_DKV
|
| 143 |
+
new_k_pe = RoPE(h_t @ W_KR)
|
| 144 |
+
new_k_nope = (new_kv_c @ W_UK.view(Lkv, N * P)).view(Sq, N, P)
|
| 145 |
+
new_v = (new_kv_c @ W_UV.view(Lkv, N * V)).view(Sq, N, V)
|
| 146 |
+
|
| 147 |
+
// MHA between queries and new KV
|
| 148 |
+
// with QK headdim = P + R
|
| 149 |
+
// V headdim = V
|
| 150 |
+
// curr_o shape [Sq, N, V]
|
| 151 |
+
// curr_lse shape [N, Sq], this is just order FA returns
|
| 152 |
+
curr_o, curr_lse = scaled_dot_product_attention(
|
| 153 |
+
torch.cat([q_nope, q_pe], dim=-1),
|
| 154 |
+
torch.cat([new_k_nope, new_k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1),
|
| 155 |
+
new_v,
|
| 156 |
+
casual=True,
|
| 157 |
+
return_softmax_lse=True
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
// Compute attention with the already existing context
|
| 161 |
+
for chunk_idx in range(cdiv(C, MCC)):
|
| 162 |
+
chunk_start = chunk_idx * MCC
|
| 163 |
+
chunk_end = min(chunk_start + MCC, C)
|
| 164 |
+
Sc = chunk_end - chunk_start
|
| 165 |
+
cache_kv_c_chunk = cache_kv_c[chunk_start:chunk_end]
|
| 166 |
+
cache_k_pe_chunk = cache_k_pe[chunk_start:chunk_end]
|
| 167 |
+
cache_k_nope_chunk = (cache_kv_c_chunk @ W_UK).view(-1, N, P)
|
| 168 |
+
cache_v_chunk = (cache_kv_c_chunk @ W_UV).view(-1, N, V)
|
| 169 |
+
|
| 170 |
+
chunk_o, chunk_lse = scaled_dot_product_attention(
|
| 171 |
+
torch.cat([q_nope, q_pe], dim=-1),
|
| 172 |
+
torch.cat([cache_k_nope_chunk,
|
| 173 |
+
cache_k_pe_chunk.unsqueeze(1).expand(-1, N, -1)],
|
| 174 |
+
dim=-1),
|
| 175 |
+
cache_v_chunk,
|
| 176 |
+
casual=False,
|
| 177 |
+
return_softmax_lse=True
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
curr_o, curr_lse = merge_attn_states(
|
| 181 |
+
suffix_output=curr_o,
|
| 182 |
+
suffix_lse=curr_lse,
|
| 183 |
+
prefix_output=chunk_o,
|
| 184 |
+
prefix_lse=chunk_lse,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
return curr_o @ W_O
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
import functools
|
| 191 |
+
from abc import abstractmethod
|
| 192 |
+
from collections import defaultdict
|
| 193 |
+
from contextlib import contextmanager
|
| 194 |
+
from dataclasses import dataclass
|
| 195 |
+
from itertools import accumulate
|
| 196 |
+
from typing import (TYPE_CHECKING, Any, Dict, Generic, List, Optional, Tuple,
|
| 197 |
+
Type, TypeVar)
|
| 198 |
+
|
| 199 |
+
import torch
|
| 200 |
+
|
| 201 |
+
from vllm import _custom_ops as ops
|
| 202 |
+
from vllm import envs
|
| 203 |
+
from vllm.attention.backends.abstract import (AttentionBackend, AttentionLayer,
|
| 204 |
+
AttentionMetadata,
|
| 205 |
+
AttentionMetadataBuilder,
|
| 206 |
+
AttentionState, MLAAttentionImpl)
|
| 207 |
+
from vllm.attention.backends.utils import (PAD_SLOT_ID, compute_slot_mapping,
|
| 208 |
+
compute_slot_mapping_start_idx,
|
| 209 |
+
is_block_tables_empty)
|
| 210 |
+
from vllm.attention.ops.merge_attn_states import merge_attn_states
|
| 211 |
+
from vllm.attention.utils.fa_utils import get_flash_attn_version
|
| 212 |
+
from vllm.model_executor.layers.linear import (ColumnParallelLinear,
|
| 213 |
+
LinearBase,
|
| 214 |
+
UnquantizedLinearMethod)
|
| 215 |
+
from vllm.multimodal import MultiModalPlaceholderMap
|
| 216 |
+
from vllm.platforms import current_platform
|
| 217 |
+
from vllm.triton_utils import HAS_TRITON
|
| 218 |
+
from vllm.utils import async_tensor_h2d, cdiv, make_tensor_with_pad, round_down
|
| 219 |
+
|
| 220 |
+
if HAS_TRITON:
|
| 221 |
+
from vllm.attention.ops.triton_flash_attention import triton_attention
|
| 222 |
+
else:
|
| 223 |
+
triton_attention = None
|
| 224 |
+
|
| 225 |
+
try:
|
| 226 |
+
from vllm.vllm_flash_attn import flash_attn_varlen_func
|
| 227 |
+
is_vllm_fa = True
|
| 228 |
+
except ImportError:
|
| 229 |
+
is_vllm_fa = False
|
| 230 |
+
try:
|
| 231 |
+
# For rocm use upstream flash attention
|
| 232 |
+
from flash_attn import flash_attn_varlen_func
|
| 233 |
+
except ImportError:
|
| 234 |
+
flash_attn_varlen_func = None
|
| 235 |
+
|
| 236 |
+
if TYPE_CHECKING:
|
| 237 |
+
from vllm.worker.model_runner import ModelInputForGPUBuilder
|
| 238 |
+
|
| 239 |
+
is_hip = current_platform.is_rocm()
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class MLACommonBackend(AttentionBackend):
|
| 243 |
+
|
| 244 |
+
@staticmethod
|
| 245 |
+
def get_name() -> str:
|
| 246 |
+
return "TRITON_MLA"
|
| 247 |
+
|
| 248 |
+
@staticmethod
|
| 249 |
+
def get_metadata_cls() -> Type["AttentionMetadata"]:
|
| 250 |
+
return MLACommonMetadata
|
| 251 |
+
|
| 252 |
+
@staticmethod
|
| 253 |
+
def get_builder_cls() -> Type["MLACommonMetadataBuilder"]:
|
| 254 |
+
return MLACommonMetadataBuilder
|
| 255 |
+
|
| 256 |
+
@staticmethod
|
| 257 |
+
def get_state_cls() -> Type["MLACommonState"]:
|
| 258 |
+
return MLACommonState
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def get_kv_cache_shape(
|
| 262 |
+
num_blocks: int,
|
| 263 |
+
block_size: int,
|
| 264 |
+
num_kv_heads: int, # assumed to be 1 for MLA
|
| 265 |
+
head_size: int,
|
| 266 |
+
) -> Tuple[int, ...]:
|
| 267 |
+
return (num_blocks, block_size, head_size)
|
| 268 |
+
|
| 269 |
+
@staticmethod
|
| 270 |
+
def swap_blocks(
|
| 271 |
+
src_kv_cache: torch.Tensor,
|
| 272 |
+
dst_kv_cache: torch.Tensor,
|
| 273 |
+
src_to_dst: torch.Tensor,
|
| 274 |
+
) -> None:
|
| 275 |
+
ops.swap_blocks(src_kv_cache, dst_kv_cache, src_to_dst)
|
| 276 |
+
|
| 277 |
+
@staticmethod
|
| 278 |
+
def copy_blocks(
|
| 279 |
+
kv_caches: List[torch.Tensor],
|
| 280 |
+
src_to_dists: torch.Tensor,
|
| 281 |
+
) -> None:
|
| 282 |
+
ops.copy_blocks_mla(kv_caches, src_to_dists)
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def get_supported_head_sizes() -> List[int]:
|
| 286 |
+
return [576]
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
T = TypeVar("T", bound="MLACommonMetadata")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class MLACommonState(AttentionState, Generic[T]):
|
| 293 |
+
|
| 294 |
+
def __init__(self, runner):
|
| 295 |
+
self.runner = runner
|
| 296 |
+
self._is_graph_capturing = False
|
| 297 |
+
|
| 298 |
+
scheduler_config = runner.scheduler_config
|
| 299 |
+
self.model_config = runner.model_config
|
| 300 |
+
cache_config = runner.cache_config
|
| 301 |
+
|
| 302 |
+
self.chunked_prefill_enabled = scheduler_config.chunked_prefill_enabled
|
| 303 |
+
self.enable_prefix_caching = cache_config.enable_prefix_caching
|
| 304 |
+
|
| 305 |
+
if self.chunked_prefill_enabled or self.enable_prefix_caching:
|
| 306 |
+
self.context_chunk_workspace_size = min(
|
| 307 |
+
# Max sure there is enough for 8 full length request or at least
|
| 308 |
+
# 4 pages of cache per request
|
| 309 |
+
max(
|
| 310 |
+
8 * self.model_config.max_model_len, 4 *
|
| 311 |
+
scheduler_config.max_num_seqs * cache_config.block_size),
|
| 312 |
+
# For long-context models try not to over-allocate limiting
|
| 313 |
+
# kv-cache space, limiting it to 64k tokens,
|
| 314 |
+
# which would result in the workspace being:
|
| 315 |
+
# 2*(576)*(64*1024) = 144mb
|
| 316 |
+
# (assuming 576 MLA head dim, and fp16)
|
| 317 |
+
# which would result in up-projected context being
|
| 318 |
+
# 2*(192*128)*(64*1024) = 3gb
|
| 319 |
+
# (assuming 192 QK head dim, 128 heads, and fp16)
|
| 320 |
+
128 * 1024)
|
| 321 |
+
assert self.context_chunk_workspace_size >= \
|
| 322 |
+
scheduler_config.max_num_seqs * cache_config.block_size
|
| 323 |
+
|
| 324 |
+
@contextmanager
|
| 325 |
+
def graph_capture(self, max_batch_size: int):
|
| 326 |
+
self._is_graph_capturing = True
|
| 327 |
+
|
| 328 |
+
self._graph_slot_mapping = torch.full((max_batch_size, ),
|
| 329 |
+
PAD_SLOT_ID,
|
| 330 |
+
dtype=torch.long,
|
| 331 |
+
device=self.runner.device)
|
| 332 |
+
self._graph_seq_lens = torch.ones(max_batch_size,
|
| 333 |
+
dtype=torch.int32,
|
| 334 |
+
device=self.runner.device)
|
| 335 |
+
self._graph_block_tables = torch.from_numpy(
|
| 336 |
+
self.runner.graph_block_tables).to(device=self.runner.device)
|
| 337 |
+
|
| 338 |
+
self._positions = torch.zeros((max_batch_size, ),
|
| 339 |
+
dtype=torch.long,
|
| 340 |
+
device=self.runner.device)
|
| 341 |
+
|
| 342 |
+
yield
|
| 343 |
+
|
| 344 |
+
self._is_graph_capturing = False
|
| 345 |
+
del self._graph_slot_mapping
|
| 346 |
+
del self._graph_seq_lens
|
| 347 |
+
del self._graph_block_tables
|
| 348 |
+
del self._positions
|
| 349 |
+
|
| 350 |
+
def graph_clone(self, batch_size: int):
|
| 351 |
+
assert self._is_graph_capturing
|
| 352 |
+
return self.__class__(self.runner)
|
| 353 |
+
|
| 354 |
+
def graph_capture_get_metadata_for_batch(
|
| 355 |
+
self,
|
| 356 |
+
batch_size: int,
|
| 357 |
+
is_encoder_decoder_model: bool = False) -> T:
|
| 358 |
+
assert self._is_graph_capturing
|
| 359 |
+
|
| 360 |
+
attn_metadata = self.runner.attn_backend.make_metadata(
|
| 361 |
+
multi_modal_placeholder_index_maps=None,
|
| 362 |
+
enable_kv_scales_calculation=False,
|
| 363 |
+
use_cuda_graph=True,
|
| 364 |
+
num_prefills=0,
|
| 365 |
+
num_prefill_tokens=0,
|
| 366 |
+
num_decode_tokens=batch_size,
|
| 367 |
+
slot_mapping=self._graph_slot_mapping[:batch_size],
|
| 368 |
+
seq_lens=None,
|
| 369 |
+
seq_lens_tensor=self._graph_seq_lens[:batch_size],
|
| 370 |
+
max_query_len=1,
|
| 371 |
+
max_decode_query_len=1,
|
| 372 |
+
max_prefill_seq_len=0,
|
| 373 |
+
max_decode_seq_len=self.runner.max_seq_len_to_capture,
|
| 374 |
+
query_start_loc=None,
|
| 375 |
+
seq_start_loc=None,
|
| 376 |
+
context_lens_tensor=None,
|
| 377 |
+
block_tables=self._graph_block_tables[:batch_size],
|
| 378 |
+
head_dim=self.runner.model_config.get_head_size())
|
| 379 |
+
|
| 380 |
+
if is_encoder_decoder_model:
|
| 381 |
+
raise NotImplementedError(
|
| 382 |
+
"MLACommonState does not support encoder/decoder yet")
|
| 383 |
+
|
| 384 |
+
return attn_metadata
|
| 385 |
+
|
| 386 |
+
def get_graph_input_buffers(self,
|
| 387 |
+
attn_metadata,
|
| 388 |
+
is_encoder_decoder_model: bool = False):
|
| 389 |
+
input_buffers = {
|
| 390 |
+
"slot_mapping": attn_metadata.slot_mapping,
|
| 391 |
+
"seq_lens_tensor": attn_metadata.decode_metadata.seq_lens_tensor,
|
| 392 |
+
"block_tables": attn_metadata.decode_metadata.block_tables,
|
| 393 |
+
}
|
| 394 |
+
if is_encoder_decoder_model:
|
| 395 |
+
raise NotImplementedError(
|
| 396 |
+
"MLACommonState does not support encoder/decoder yet")
|
| 397 |
+
|
| 398 |
+
return input_buffers
|
| 399 |
+
|
| 400 |
+
def prepare_graph_input_buffers(self,
|
| 401 |
+
input_buffers,
|
| 402 |
+
attn_metadata,
|
| 403 |
+
is_encoder_decoder_model: bool = False):
|
| 404 |
+
input_buffers["seq_lens_tensor"].copy_(
|
| 405 |
+
attn_metadata.decode_metadata.seq_lens_tensor, non_blocking=True)
|
| 406 |
+
input_buffers["block_tables"].copy_(
|
| 407 |
+
attn_metadata.decode_metadata.block_tables, non_blocking=True)
|
| 408 |
+
if is_encoder_decoder_model:
|
| 409 |
+
raise NotImplementedError(
|
| 410 |
+
"TritonMLAState does not support encoder/decoder yet")
|
| 411 |
+
|
| 412 |
+
def begin_forward(self, model_input):
|
| 413 |
+
if self.chunked_prefill_enabled or self.enable_prefix_caching:
|
| 414 |
+
if not hasattr(self, "context_chunk_workspace"):
|
| 415 |
+
# not self.runner.device does not return the correct device
|
| 416 |
+
# for this process, (init_device sets the correct device but
|
| 417 |
+
# only on the Worker). The only way Ive figured out to get the
|
| 418 |
+
# correct device is to allocate the workspace on the first call
|
| 419 |
+
# to begin_forward and use the device of the input tokens
|
| 420 |
+
assert model_input.input_tokens is not None
|
| 421 |
+
self.context_chunk_workspace = torch.empty(
|
| 422 |
+
(self.context_chunk_workspace_size,
|
| 423 |
+
self.model_config.get_head_size()),
|
| 424 |
+
dtype=self.model_config.dtype,
|
| 425 |
+
device=model_input.input_tokens.device,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
model_input.attn_metadata.context_chunk_workspace = \
|
| 429 |
+
self.context_chunk_workspace
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
@dataclass
|
| 433 |
+
class MLACommonMetadata(AttentionMetadata):
|
| 434 |
+
"""Metadata for MLACommon.
|
| 435 |
+
|
| 436 |
+
NOTE: Please read the comment at the top of the file before trying to
|
| 437 |
+
understand this class
|
| 438 |
+
|
| 439 |
+
NOTE: Any python object stored here is not updated when it is
|
| 440 |
+
cuda-graph replayed. If you have values that need to be changed
|
| 441 |
+
dynamically, it should be stored in tensor. The tensor has to be
|
| 442 |
+
updated from `CUDAGraphRunner.forward` API.
|
| 443 |
+
"""
|
| 444 |
+
# Whether or not if cuda graph is enabled.
|
| 445 |
+
# Cuda-graph is currently enabled for decoding only.
|
| 446 |
+
# TODO(woosuk): Move `use_cuda_graph` out since it's unrelated to attention.
|
| 447 |
+
use_cuda_graph: bool
|
| 448 |
+
|
| 449 |
+
# NOTE(sang): Definition of context_len, query_len, and seq_len.
|
| 450 |
+
# |---------- N-1 iteration --------|
|
| 451 |
+
# |---------------- N iteration ---------------------|
|
| 452 |
+
# |- tokenA -|......................|-- newTokens ---|
|
| 453 |
+
# |---------- context_len ----------|
|
| 454 |
+
# |-------------------- seq_len ---------------------|
|
| 455 |
+
# |-- query_len ---|
|
| 456 |
+
|
| 457 |
+
# (batch_size,). The sequence length per sequence. Sequence length means
|
| 458 |
+
# the computed tokens + new tokens None if it is a decoding.
|
| 459 |
+
seq_lens: Optional[List[int]]
|
| 460 |
+
# seq_lens stored as a tensor.
|
| 461 |
+
seq_lens_tensor: Optional[torch.Tensor]
|
| 462 |
+
|
| 463 |
+
# Maximum sequence length among prefill batch. 0 if there are decoding
|
| 464 |
+
# requests only.
|
| 465 |
+
max_prefill_seq_len: int
|
| 466 |
+
# Maximum sequence length among decode batch. 0 if there are prefill
|
| 467 |
+
# requests only.
|
| 468 |
+
max_decode_seq_len: int
|
| 469 |
+
# (batch_size,) A tensor of context lengths (tokens that are computed
|
| 470 |
+
# so far).
|
| 471 |
+
context_lens_tensor: Optional[torch.Tensor]
|
| 472 |
+
|
| 473 |
+
# (batch_size, max_blocks_per_seq).
|
| 474 |
+
# Block addresses per sequence. (Seq id -> list of physical block)
|
| 475 |
+
# E.g., [0, 1, 2] means tokens are stored in 0th, 1st, and 2nd blocks
|
| 476 |
+
# in the kv cache. Each block can contain up to block_size tokens.
|
| 477 |
+
# 2nd dimensions are padded up to max_blocks_per_seq if it is cuda-graph
|
| 478 |
+
# captured.
|
| 479 |
+
block_tables: Optional[torch.Tensor]
|
| 480 |
+
|
| 481 |
+
# Maximum query length in the batch.
|
| 482 |
+
max_query_len: Optional[int] = None
|
| 483 |
+
|
| 484 |
+
# Max number of query tokens among request in the batch.
|
| 485 |
+
max_decode_query_len: Optional[int] = None
|
| 486 |
+
|
| 487 |
+
# (batch_size + 1,). The cumulative subquery lengths of the sequences in
|
| 488 |
+
# the batch, used to index into subquery. E.g., if the subquery length
|
| 489 |
+
# is [4, 6], it is [0, 4, 10].
|
| 490 |
+
query_start_loc: Optional[torch.Tensor] = None
|
| 491 |
+
# (batch_size + 1,). The cumulative sequence lengths of the sequences in
|
| 492 |
+
# the batch, used to index into sequence. E.g., if the sequence length is
|
| 493 |
+
# [4, 6], it is [0, 4, 10].
|
| 494 |
+
seq_start_loc: Optional[torch.Tensor] = None
|
| 495 |
+
|
| 496 |
+
_cached_prefill_metadata: Optional[Any] = None
|
| 497 |
+
_cached_decode_metadata: Optional[Any] = None
|
| 498 |
+
|
| 499 |
+
num_prefill_tokens: int
|
| 500 |
+
|
| 501 |
+
# The dimension of the attention heads
|
| 502 |
+
head_dim: Optional[int] = None
|
| 503 |
+
|
| 504 |
+
# Used when chunked prefill is enabled to simulate worst case workspace
|
| 505 |
+
# allocations, hopefully to avoid going OOM
|
| 506 |
+
is_profile_run: bool = False
|
| 507 |
+
|
| 508 |
+
# New for MLA (compared to FlashAttention)
|
| 509 |
+
# For chunked prefill
|
| 510 |
+
context_chunk_cu_seq_lens: Optional[torch.Tensor] = None
|
| 511 |
+
context_chunk_starts: Optional[torch.Tensor] = None
|
| 512 |
+
context_chunk_seq_tot: Optional[List[int]] = None
|
| 513 |
+
context_chunk_max_seq_lens: Optional[List[int]] = None
|
| 514 |
+
# Set by MLAAttentionState in `begin_forward` so it doesn't get broadcasted
|
| 515 |
+
context_chunk_workspace: Optional[torch.Tensor] = None
|
| 516 |
+
|
| 517 |
+
def __post_init__(self):
|
| 518 |
+
supported_head_sizes = MLACommonBackend.get_supported_head_sizes()
|
| 519 |
+
if self.head_dim is not None and self.head_dim \
|
| 520 |
+
not in supported_head_sizes:
|
| 521 |
+
raise ValueError(
|
| 522 |
+
f"Only {supported_head_sizes} are supported for head_dim,",
|
| 523 |
+
f" received {self.head_dim}.")
|
| 524 |
+
|
| 525 |
+
@property
|
| 526 |
+
def prefill_metadata(self):
|
| 527 |
+
if self.num_prefills == 0:
|
| 528 |
+
return None
|
| 529 |
+
|
| 530 |
+
if self._cached_prefill_metadata is not None:
|
| 531 |
+
return self._cached_prefill_metadata
|
| 532 |
+
|
| 533 |
+
assert self.seq_lens is not None
|
| 534 |
+
assert self.seq_lens_tensor is not None
|
| 535 |
+
|
| 536 |
+
# Compute some attn_metadata fields which default to None
|
| 537 |
+
query_start_loc = (None if self.query_start_loc is None else
|
| 538 |
+
self.query_start_loc[:self.num_prefills + 1])
|
| 539 |
+
slot_mapping = (None if self.slot_mapping is None else
|
| 540 |
+
self.slot_mapping[:self.num_prefill_tokens])
|
| 541 |
+
seq_lens = (None if self.seq_lens is None else
|
| 542 |
+
self.seq_lens[:self.num_prefills])
|
| 543 |
+
seq_lens_tensor = (None if self.seq_lens_tensor is None else
|
| 544 |
+
self.seq_lens_tensor[:self.num_prefills])
|
| 545 |
+
seq_start_loc = (None if self.seq_start_loc is None else
|
| 546 |
+
self.seq_start_loc[:self.num_prefills + 1])
|
| 547 |
+
context_lens_tensor = (None if self.context_lens_tensor is None else
|
| 548 |
+
self.context_lens_tensor[:self.num_prefills])
|
| 549 |
+
block_tables = (None if self.block_tables is None else
|
| 550 |
+
self.block_tables[:self.num_prefills])
|
| 551 |
+
|
| 552 |
+
self._cached_prefill_metadata = self.__class__(
|
| 553 |
+
# Required by ModelRunner
|
| 554 |
+
use_cuda_graph=False, # Not Attention Related
|
| 555 |
+
# Required by Attention Metadata
|
| 556 |
+
num_prefills=self.num_prefills,
|
| 557 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 558 |
+
num_decode_tokens=0,
|
| 559 |
+
slot_mapping=slot_mapping,
|
| 560 |
+
# Required by Attention Metadata (not used)
|
| 561 |
+
multi_modal_placeholder_index_maps=None,
|
| 562 |
+
enable_kv_scales_calculation=False,
|
| 563 |
+
# MLACommonMetadata
|
| 564 |
+
seq_lens=seq_lens,
|
| 565 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 566 |
+
max_query_len=self.max_query_len,
|
| 567 |
+
max_prefill_seq_len=self.max_prefill_seq_len,
|
| 568 |
+
max_decode_query_len=0,
|
| 569 |
+
max_decode_seq_len=0,
|
| 570 |
+
query_start_loc=query_start_loc,
|
| 571 |
+
seq_start_loc=seq_start_loc,
|
| 572 |
+
context_lens_tensor=context_lens_tensor,
|
| 573 |
+
block_tables=block_tables,
|
| 574 |
+
head_dim=self.head_dim,
|
| 575 |
+
is_profile_run=self.is_profile_run,
|
| 576 |
+
# MLACommonMetadata Chunk prefill specific
|
| 577 |
+
context_chunk_cu_seq_lens=self.context_chunk_cu_seq_lens,
|
| 578 |
+
context_chunk_starts=self.context_chunk_starts,
|
| 579 |
+
context_chunk_seq_tot=self.context_chunk_seq_tot,
|
| 580 |
+
context_chunk_max_seq_lens=self.context_chunk_max_seq_lens,
|
| 581 |
+
)
|
| 582 |
+
return self._cached_prefill_metadata
|
| 583 |
+
|
| 584 |
+
@property
|
| 585 |
+
def decode_metadata(self):
|
| 586 |
+
if self.num_decode_tokens == 0:
|
| 587 |
+
return None
|
| 588 |
+
|
| 589 |
+
if self._cached_decode_metadata is not None:
|
| 590 |
+
return self._cached_decode_metadata
|
| 591 |
+
assert self.seq_lens_tensor is not None
|
| 592 |
+
|
| 593 |
+
# Compute some attn_metadata fields which default to None
|
| 594 |
+
slot_mapping = (None if self.slot_mapping is None else
|
| 595 |
+
self.slot_mapping[self.num_prefill_tokens:])
|
| 596 |
+
seq_lens_tensor = (None if self.seq_lens_tensor is None else
|
| 597 |
+
self.seq_lens_tensor[self.num_prefills:])
|
| 598 |
+
block_tables = (None if self.block_tables is None else
|
| 599 |
+
self.block_tables[self.num_prefills:])
|
| 600 |
+
|
| 601 |
+
self._cached_decode_metadata = self.__class__(
|
| 602 |
+
# Required by ModelRunner
|
| 603 |
+
use_cuda_graph=self.use_cuda_graph, # Not Attention Related
|
| 604 |
+
# Required by Attention Metadata
|
| 605 |
+
num_prefills=0,
|
| 606 |
+
num_prefill_tokens=0,
|
| 607 |
+
num_decode_tokens=self.num_decode_tokens,
|
| 608 |
+
slot_mapping=slot_mapping,
|
| 609 |
+
# Required by Attention Metadata (not used)
|
| 610 |
+
multi_modal_placeholder_index_maps=None,
|
| 611 |
+
enable_kv_scales_calculation=False,
|
| 612 |
+
# MLACommonMetadata
|
| 613 |
+
seq_lens=None,
|
| 614 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 615 |
+
max_decode_query_len=self.max_decode_query_len,
|
| 616 |
+
max_query_len=self.max_query_len,
|
| 617 |
+
max_prefill_seq_len=0,
|
| 618 |
+
max_decode_seq_len=self.max_decode_seq_len,
|
| 619 |
+
# Batch may be composed of prefill|decodes, adjust query start
|
| 620 |
+
# indices to refer to the start of decodes. E.g.
|
| 621 |
+
# in tokens:[3 prefills|6 decodes], query_start_loc=[3,9] => [0,6].
|
| 622 |
+
query_start_loc=(self.query_start_loc[self.num_prefills:] -
|
| 623 |
+
self.query_start_loc[self.num_prefills])
|
| 624 |
+
if self.query_start_loc is not None else None,
|
| 625 |
+
seq_start_loc=self.seq_start_loc[self.num_prefills:]
|
| 626 |
+
if self.seq_start_loc is not None else None,
|
| 627 |
+
context_lens_tensor=None,
|
| 628 |
+
block_tables=block_tables,
|
| 629 |
+
head_dim=self.head_dim,
|
| 630 |
+
is_profile_run=self.is_profile_run)
|
| 631 |
+
return self._cached_decode_metadata
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class MLACommonMetadataBuilder(AttentionMetadataBuilder[T], Generic[T]):
|
| 635 |
+
"""
|
| 636 |
+
NOTE: Please read the comment at the top of the file before trying to
|
| 637 |
+
understand this class
|
| 638 |
+
"""
|
| 639 |
+
BLOCK_TABLE_EXTENDER: list[list[int]] = []
|
| 640 |
+
|
| 641 |
+
def __init__(self, input_builder: "ModelInputForGPUBuilder"):
|
| 642 |
+
self.input_builder = input_builder
|
| 643 |
+
self.runner = input_builder.runner
|
| 644 |
+
self.sliding_window = input_builder.sliding_window
|
| 645 |
+
self.block_size = input_builder.block_size
|
| 646 |
+
self.chunked_prefill_enabled = \
|
| 647 |
+
self.runner.scheduler_config.chunked_prefill_enabled
|
| 648 |
+
self.enable_prefix_caching = \
|
| 649 |
+
self.runner.cache_config.enable_prefix_caching
|
| 650 |
+
|
| 651 |
+
if self.chunked_prefill_enabled or self.enable_prefix_caching:
|
| 652 |
+
attn_state = self.input_builder.runner.attn_state
|
| 653 |
+
self.context_chunk_workspace_size = \
|
| 654 |
+
attn_state.context_chunk_workspace_size
|
| 655 |
+
self.page_size = self.runner.block_size
|
| 656 |
+
|
| 657 |
+
def prepare(self):
|
| 658 |
+
self.slot_mapping: List[int] = []
|
| 659 |
+
self.prefill_seq_lens: List[int] = []
|
| 660 |
+
self.context_lens: List[int] = []
|
| 661 |
+
self.block_tables: List[List[int]] = []
|
| 662 |
+
self.curr_seq_lens: List[int] = []
|
| 663 |
+
self.multimodal_placeholder_maps: Dict[
|
| 664 |
+
str,
|
| 665 |
+
MultiModalPlaceholderMap] = defaultdict(MultiModalPlaceholderMap)
|
| 666 |
+
self.num_prefills = 0
|
| 667 |
+
self.num_prefill_tokens = 0
|
| 668 |
+
self.num_decode_tokens = 0
|
| 669 |
+
self.has_prefix_cache_hit = False
|
| 670 |
+
|
| 671 |
+
def _add_seq_group(
|
| 672 |
+
self, inter_data: "ModelInputForGPUBuilder.InterDataForSeqGroup",
|
| 673 |
+
chunked_prefill_enabled: bool, prefix_cache_hit: bool):
|
| 674 |
+
"""Add a sequence group to the metadata. Specifically update/append
|
| 675 |
+
1. context length.
|
| 676 |
+
2. block table.
|
| 677 |
+
3. slot mapping.
|
| 678 |
+
"""
|
| 679 |
+
is_prompt = inter_data.is_prompt
|
| 680 |
+
block_tables = inter_data.block_tables
|
| 681 |
+
|
| 682 |
+
for (seq_id, token_len, seq_len, curr_seq_len, query_len, context_len,
|
| 683 |
+
curr_sliding_window_block) in zip(
|
| 684 |
+
inter_data.seq_ids, [len(t) for t in inter_data.input_tokens],
|
| 685 |
+
inter_data.orig_seq_lens, inter_data.seq_lens,
|
| 686 |
+
inter_data.query_lens, inter_data.context_lens,
|
| 687 |
+
inter_data.curr_sliding_window_blocks):
|
| 688 |
+
self.context_lens.append(context_len)
|
| 689 |
+
if is_prompt:
|
| 690 |
+
self.num_prefills += 1
|
| 691 |
+
self.num_prefill_tokens += token_len
|
| 692 |
+
self.prefill_seq_lens.append(seq_len)
|
| 693 |
+
else:
|
| 694 |
+
self.num_decode_tokens += query_len
|
| 695 |
+
self.curr_seq_lens.append(curr_seq_len)
|
| 696 |
+
|
| 697 |
+
# Compute block table.
|
| 698 |
+
# TODO(sang): Combine chunked prefill and prefix caching by
|
| 699 |
+
# only allowing multiple of block_size chunk size.
|
| 700 |
+
# NOTE: This only works for oooooooxxx style attention.
|
| 701 |
+
block_table = []
|
| 702 |
+
if prefix_cache_hit:
|
| 703 |
+
# NOTE(woosuk): For flash-attn, the block table should
|
| 704 |
+
# include the entries for the incoming prefill tokens.
|
| 705 |
+
block_table = block_tables[seq_id]
|
| 706 |
+
elif ((chunked_prefill_enabled or not is_prompt)
|
| 707 |
+
and block_tables is not None):
|
| 708 |
+
if curr_sliding_window_block == 0:
|
| 709 |
+
block_table = block_tables[seq_id]
|
| 710 |
+
else:
|
| 711 |
+
block_table = block_tables[seq_id][
|
| 712 |
+
-curr_sliding_window_block:]
|
| 713 |
+
self.block_tables.append(block_table)
|
| 714 |
+
|
| 715 |
+
# Compute slot mapping.
|
| 716 |
+
is_profile_run = is_block_tables_empty(block_tables)
|
| 717 |
+
start_idx = compute_slot_mapping_start_idx(is_prompt, query_len,
|
| 718 |
+
context_len,
|
| 719 |
+
self.sliding_window)
|
| 720 |
+
compute_slot_mapping(is_profile_run, self.slot_mapping, seq_id,
|
| 721 |
+
seq_len, context_len, start_idx,
|
| 722 |
+
self.block_size, inter_data.block_tables)
|
| 723 |
+
|
| 724 |
+
def _get_graph_runner_block_tables(
|
| 725 |
+
self, num_seqs: int,
|
| 726 |
+
block_tables: List[List[int]]) -> torch.Tensor:
|
| 727 |
+
# The shape of graph_block_tables is
|
| 728 |
+
# [max batch size, max context len // block size].
|
| 729 |
+
max_batch_size, max_blocks = self.runner.graph_block_tables.shape
|
| 730 |
+
assert max_batch_size >= num_seqs
|
| 731 |
+
|
| 732 |
+
graph_block_tables = self.runner.graph_block_tables[:num_seqs]
|
| 733 |
+
for i, block_table in enumerate(block_tables):
|
| 734 |
+
if block_table:
|
| 735 |
+
num_blocks = len(block_table)
|
| 736 |
+
if num_blocks <= max_blocks:
|
| 737 |
+
graph_block_tables[i, :num_blocks] = block_table
|
| 738 |
+
else:
|
| 739 |
+
# It may be possible to have more blocks allocated due
|
| 740 |
+
# to lookahead slots of multi-step, however, they are
|
| 741 |
+
# not used anyway, so can be safely ignored.
|
| 742 |
+
graph_block_tables[
|
| 743 |
+
i, :max_blocks] = block_table[:max_blocks]
|
| 744 |
+
|
| 745 |
+
return torch.from_numpy(graph_block_tables).to(
|
| 746 |
+
device=self.runner.device, non_blocking=True)
|
| 747 |
+
|
| 748 |
+
def build(self, seq_lens: List[int], query_lens: List[int],
|
| 749 |
+
cuda_graph_pad_size: int, batch_size: int):
|
| 750 |
+
"""Build attention metadata with on-device tensors.
|
| 751 |
+
|
| 752 |
+
Args:
|
| 753 |
+
seq_lens: The maybe padded sequence lengths of the input sequences.
|
| 754 |
+
query_lens: The query lengths of the input sequences.
|
| 755 |
+
cuda_graph_pad_size: The padding size for cuda graph.
|
| 756 |
+
-1 if cuda graph is not used.
|
| 757 |
+
batch_size: The maybe padded batch size.
|
| 758 |
+
"""
|
| 759 |
+
prefix_cache_hit = any([
|
| 760 |
+
inter_data.prefix_cache_hit
|
| 761 |
+
for inter_data in self.input_builder.inter_data_list
|
| 762 |
+
])
|
| 763 |
+
|
| 764 |
+
for inter_data in self.input_builder.inter_data_list:
|
| 765 |
+
self._add_seq_group(inter_data,
|
| 766 |
+
self.input_builder.chunked_prefill_enabled,
|
| 767 |
+
prefix_cache_hit)
|
| 768 |
+
|
| 769 |
+
device = self.runner.device
|
| 770 |
+
use_captured_graph = cuda_graph_pad_size != -1
|
| 771 |
+
|
| 772 |
+
max_query_len = max(query_lens)
|
| 773 |
+
decode_query_lens = query_lens[self.num_prefills:]
|
| 774 |
+
if len(decode_query_lens) > 0:
|
| 775 |
+
max_decode_query_len = max(decode_query_lens)
|
| 776 |
+
else:
|
| 777 |
+
max_decode_query_len = 1
|
| 778 |
+
max_prefill_seq_len = max(self.prefill_seq_lens, default=0)
|
| 779 |
+
max_decode_seq_len = max(self.curr_seq_lens, default=0)
|
| 780 |
+
num_decode_tokens = self.num_decode_tokens
|
| 781 |
+
query_start_loc = list(accumulate(query_lens, initial=0))
|
| 782 |
+
seq_start_loc = list(accumulate(seq_lens, initial=0))
|
| 783 |
+
|
| 784 |
+
num_seqs = len(seq_lens)
|
| 785 |
+
if use_captured_graph:
|
| 786 |
+
self.slot_mapping.extend([PAD_SLOT_ID] * cuda_graph_pad_size)
|
| 787 |
+
self.block_tables.extend(self.__class__.BLOCK_TABLE_EXTENDER *
|
| 788 |
+
cuda_graph_pad_size)
|
| 789 |
+
num_decode_tokens = batch_size - self.num_prefill_tokens
|
| 790 |
+
|
| 791 |
+
block_tables = self._get_graph_runner_block_tables(
|
| 792 |
+
num_seqs, self.block_tables)
|
| 793 |
+
else:
|
| 794 |
+
block_tables = make_tensor_with_pad(
|
| 795 |
+
self.block_tables,
|
| 796 |
+
pad=0,
|
| 797 |
+
dtype=torch.int,
|
| 798 |
+
device=device,
|
| 799 |
+
)
|
| 800 |
+
assert max_query_len > 0, ("query_lens: {}".format(query_lens))
|
| 801 |
+
|
| 802 |
+
assert device is not None
|
| 803 |
+
context_lens_tensor = async_tensor_h2d(self.context_lens, torch.int,
|
| 804 |
+
device, self.runner.pin_memory)
|
| 805 |
+
seq_lens_tensor = async_tensor_h2d(seq_lens, torch.int, device,
|
| 806 |
+
self.runner.pin_memory)
|
| 807 |
+
slot_mapping_tensor = async_tensor_h2d(self.slot_mapping, torch.long,
|
| 808 |
+
device, self.runner.pin_memory)
|
| 809 |
+
query_start_loc_tensor = async_tensor_h2d(query_start_loc, torch.int32,
|
| 810 |
+
device,
|
| 811 |
+
self.runner.pin_memory)
|
| 812 |
+
seq_start_loc_tensor = async_tensor_h2d(seq_start_loc, torch.int32,
|
| 813 |
+
device, self.runner.pin_memory)
|
| 814 |
+
|
| 815 |
+
context_chunk_cu_seq_lens = None
|
| 816 |
+
context_chunk_starts = None
|
| 817 |
+
context_chunk_seq_tot = None
|
| 818 |
+
context_chunk_max_seq_lens = None
|
| 819 |
+
|
| 820 |
+
if (self.chunked_prefill_enabled or self.enable_prefix_caching) \
|
| 821 |
+
and self.num_prefills > 0 \
|
| 822 |
+
and context_lens_tensor is not None \
|
| 823 |
+
and context_lens_tensor[:self.num_prefills].max() > 0:
|
| 824 |
+
|
| 825 |
+
# NOTE: it is recommend you read the `Chunked Prefill` section in
|
| 826 |
+
# the comment at the top of the file before trying to understand
|
| 827 |
+
# the following code
|
| 828 |
+
|
| 829 |
+
num_prefills_with_context = \
|
| 830 |
+
(context_lens_tensor[:self.num_prefills] > 0).sum().item()
|
| 831 |
+
|
| 832 |
+
# currently we allocate an equal amount of workspace for each
|
| 833 |
+
# prefill in the batch, we could probably use a more advanced
|
| 834 |
+
# algorithm here and allocate more workspace to prefills with
|
| 835 |
+
# longer context lengths
|
| 836 |
+
max_context_chunk = \
|
| 837 |
+
self.context_chunk_workspace_size // num_prefills_with_context
|
| 838 |
+
|
| 839 |
+
# align max_context_chunk to page_size by rounding down,
|
| 840 |
+
# currently the `gather_cache` kernel cannot handle
|
| 841 |
+
# `context_chunk_starts` that are not aligned to page_size
|
| 842 |
+
max_context_chunk = round_down(max_context_chunk, self.page_size)
|
| 843 |
+
assert max_context_chunk > 0
|
| 844 |
+
num_chunks = cdiv(context_lens_tensor.max(), max_context_chunk)
|
| 845 |
+
|
| 846 |
+
# if `max_context_chunk = 256`, `num_chunks = 3`, and
|
| 847 |
+
# `num_prefills_with_context = 4`, create a tensor that looks like
|
| 848 |
+
# [[0, 0, 0, 0], [256, 256, 256, 256], [512, 512, 512, 512]]
|
| 849 |
+
context_chunk_starts = \
|
| 850 |
+
torch.arange(num_chunks, device=device, dtype=torch.int32)\
|
| 851 |
+
.unsqueeze(1).expand(-1, self.num_prefills)\
|
| 852 |
+
* max_context_chunk
|
| 853 |
+
chunk_ends = torch.min(context_lens_tensor[:self.num_prefills]\
|
| 854 |
+
.unsqueeze(0), context_chunk_starts + max_context_chunk)
|
| 855 |
+
chunk_seq_lens = (chunk_ends - context_chunk_starts).clamp(min=0)
|
| 856 |
+
_context_chunk_cu_seq_lens = chunk_seq_lens.cumsum(dim=1).to(
|
| 857 |
+
torch.int32)
|
| 858 |
+
zero = torch.zeros(num_chunks, dtype=torch.int32, device=device)\
|
| 859 |
+
.unsqueeze(-1)
|
| 860 |
+
context_chunk_cu_seq_lens = \
|
| 861 |
+
torch.cat([zero, _context_chunk_cu_seq_lens], dim=1)
|
| 862 |
+
context_chunk_max_seq_lens = \
|
| 863 |
+
chunk_seq_lens.max(dim=1).values.tolist()
|
| 864 |
+
context_chunk_seq_tot = chunk_seq_lens.sum(dim=1).tolist()
|
| 865 |
+
assert max(context_chunk_seq_tot) <= \
|
| 866 |
+
self.context_chunk_workspace_size
|
| 867 |
+
|
| 868 |
+
return self.runner.attn_backend.make_metadata(
|
| 869 |
+
# Required by ModelRunner
|
| 870 |
+
use_cuda_graph=use_captured_graph, # Not Attention Related
|
| 871 |
+
# Required by Attention Metadata
|
| 872 |
+
num_prefills=self.num_prefills,
|
| 873 |
+
slot_mapping=slot_mapping_tensor,
|
| 874 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 875 |
+
num_decode_tokens=num_decode_tokens,
|
| 876 |
+
# Required by Attention Metadata (not used)
|
| 877 |
+
multi_modal_placeholder_index_maps=None, # Not Attention Related
|
| 878 |
+
enable_kv_scales_calculation=False,
|
| 879 |
+
# MLACommonMetadata
|
| 880 |
+
seq_lens=seq_lens,
|
| 881 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 882 |
+
max_query_len=max_query_len,
|
| 883 |
+
max_decode_query_len=max_decode_query_len,
|
| 884 |
+
max_prefill_seq_len=max_prefill_seq_len,
|
| 885 |
+
max_decode_seq_len=max_decode_seq_len,
|
| 886 |
+
query_start_loc=query_start_loc_tensor,
|
| 887 |
+
seq_start_loc=seq_start_loc_tensor,
|
| 888 |
+
context_lens_tensor=context_lens_tensor,
|
| 889 |
+
block_tables=block_tables,
|
| 890 |
+
head_dim=self.runner.model_config.get_head_size(),
|
| 891 |
+
is_profile_run=self.runner.in_profile_run,
|
| 892 |
+
# MLACommonMetadata Chunk prefill specific
|
| 893 |
+
context_chunk_cu_seq_lens=context_chunk_cu_seq_lens,
|
| 894 |
+
context_chunk_starts=context_chunk_starts,
|
| 895 |
+
context_chunk_seq_tot=context_chunk_seq_tot,
|
| 896 |
+
context_chunk_max_seq_lens=context_chunk_max_seq_lens,
|
| 897 |
+
)
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
class MLACommonImpl(MLAAttentionImpl[T], Generic[T]):
|
| 901 |
+
"""
|
| 902 |
+
NOTE: Please read the comment at the top of the file before trying to
|
| 903 |
+
understand this class
|
| 904 |
+
"""
|
| 905 |
+
|
| 906 |
+
def __init__(
|
| 907 |
+
self,
|
| 908 |
+
num_heads: int,
|
| 909 |
+
head_size: int,
|
| 910 |
+
scale: float,
|
| 911 |
+
num_kv_heads: int,
|
| 912 |
+
alibi_slopes: Optional[List[float]],
|
| 913 |
+
sliding_window: Optional[int],
|
| 914 |
+
kv_cache_dtype: str,
|
| 915 |
+
logits_soft_cap: Optional[float],
|
| 916 |
+
attn_type: str,
|
| 917 |
+
kv_sharing_target_layer_name: Optional[str],
|
| 918 |
+
# MLA Specific Arguments
|
| 919 |
+
q_lora_rank: Optional[int],
|
| 920 |
+
kv_lora_rank: int,
|
| 921 |
+
qk_nope_head_dim: int,
|
| 922 |
+
qk_rope_head_dim: int,
|
| 923 |
+
qk_head_dim: int,
|
| 924 |
+
v_head_dim: int,
|
| 925 |
+
kv_b_proj: ColumnParallelLinear,
|
| 926 |
+
) -> None:
|
| 927 |
+
if kv_sharing_target_layer_name is not None:
|
| 928 |
+
raise NotImplementedError("KV sharing not supported in V0.")
|
| 929 |
+
self.num_heads = num_heads
|
| 930 |
+
self.head_size = head_size
|
| 931 |
+
self.scale = float(scale)
|
| 932 |
+
self.num_kv_heads = num_kv_heads
|
| 933 |
+
self.kv_cache_dtype = kv_cache_dtype
|
| 934 |
+
|
| 935 |
+
self.q_lora_rank = q_lora_rank
|
| 936 |
+
self.kv_lora_rank = kv_lora_rank
|
| 937 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
| 938 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
| 939 |
+
self.qk_head_dim = qk_head_dim
|
| 940 |
+
self.v_head_dim = v_head_dim
|
| 941 |
+
self.kv_b_proj = kv_b_proj
|
| 942 |
+
|
| 943 |
+
self.triton_fa_func = triton_attention
|
| 944 |
+
# Handle the differences between the flash_attn_varlen from flash_attn
|
| 945 |
+
# and the one from vllm_flash_attn. The former is used on RoCM and the
|
| 946 |
+
# latter has an additional parameter to control FA2 vs FA3
|
| 947 |
+
self.flash_attn_varlen_func = flash_attn_varlen_func
|
| 948 |
+
self.vllm_flash_attn_version = get_flash_attn_version()
|
| 949 |
+
if self.vllm_flash_attn_version is not None:
|
| 950 |
+
self.flash_attn_varlen_func = \
|
| 951 |
+
functools.partial(flash_attn_varlen_func,
|
| 952 |
+
fa_version=self.vllm_flash_attn_version)
|
| 953 |
+
|
| 954 |
+
# For MLA the v head dim is smaller than qk head dim so we pad out
|
| 955 |
+
# v with 0s to match the qk head dim for attention backends that do
|
| 956 |
+
# not support different headdims
|
| 957 |
+
# We don't need to pad V if we are on a hopper system with FA3
|
| 958 |
+
self._pad_v = self.vllm_flash_attn_version is None or not (
|
| 959 |
+
self.vllm_flash_attn_version == 3
|
| 960 |
+
and current_platform.get_device_capability()[0] == 9)
|
| 961 |
+
|
| 962 |
+
def _flash_attn_varlen_diff_headdims(self, q, k, v, softmax_scale,
|
| 963 |
+
return_softmax_lse, **kwargs):
|
| 964 |
+
maybe_padded_v = v
|
| 965 |
+
if self._pad_v:
|
| 966 |
+
maybe_padded_v = torch.nn.functional.pad(
|
| 967 |
+
v, [0, q.shape[-1] - v.shape[-1]], value=0)
|
| 968 |
+
|
| 969 |
+
if is_hip and envs.VLLM_USE_TRITON_FLASH_ATTN \
|
| 970 |
+
and not return_softmax_lse:
|
| 971 |
+
attn_out = self.triton_fa_func(
|
| 972 |
+
q,
|
| 973 |
+
k,
|
| 974 |
+
maybe_padded_v,
|
| 975 |
+
None, # output
|
| 976 |
+
kwargs["cu_seqlens_q"],
|
| 977 |
+
kwargs["cu_seqlens_k"],
|
| 978 |
+
kwargs["max_seqlen_q"],
|
| 979 |
+
kwargs["max_seqlen_k"],
|
| 980 |
+
kwargs["causal"],
|
| 981 |
+
softmax_scale,
|
| 982 |
+
None, # bias
|
| 983 |
+
)
|
| 984 |
+
elif is_vllm_fa:
|
| 985 |
+
attn_out = self.flash_attn_varlen_func(
|
| 986 |
+
q=q,
|
| 987 |
+
k=k,
|
| 988 |
+
v=maybe_padded_v,
|
| 989 |
+
return_softmax_lse=return_softmax_lse,
|
| 990 |
+
softmax_scale=softmax_scale,
|
| 991 |
+
**kwargs,
|
| 992 |
+
)
|
| 993 |
+
else:
|
| 994 |
+
# Use return_attn_probs instead of return_softmax_lse for RoCM
|
| 995 |
+
attn_out = self.flash_attn_varlen_func(
|
| 996 |
+
q=q,
|
| 997 |
+
k=k,
|
| 998 |
+
v=maybe_padded_v,
|
| 999 |
+
return_attn_probs=return_softmax_lse,
|
| 1000 |
+
softmax_scale=softmax_scale,
|
| 1001 |
+
**kwargs,
|
| 1002 |
+
)
|
| 1003 |
+
|
| 1004 |
+
# Unpack the output if there is multiple results,
|
| 1005 |
+
# triton always returns (output, softmax_lse),
|
| 1006 |
+
# vllm_flash_attn returns (output, softmax_lse) when
|
| 1007 |
+
# `return_softmax_lse = True`
|
| 1008 |
+
# flash_attn (RoCM) returns (output, softmax_lse, ...) when
|
| 1009 |
+
# `return_attn_probs = True`
|
| 1010 |
+
rest = None
|
| 1011 |
+
if isinstance(attn_out, tuple):
|
| 1012 |
+
attn_out, *rest = attn_out
|
| 1013 |
+
|
| 1014 |
+
# Remain consistent with old `flash_attn_varlen_func` where there
|
| 1015 |
+
# is only one output tensor if `return_softmax_lse` is False.
|
| 1016 |
+
if return_softmax_lse:
|
| 1017 |
+
assert rest is not None
|
| 1018 |
+
return attn_out, rest[0]
|
| 1019 |
+
return attn_out
|
| 1020 |
+
|
| 1021 |
+
def _v_up_proj(self, x):
|
| 1022 |
+
# Convert from (B, N, L) to (N, B, L)
|
| 1023 |
+
x = x.view(-1, self.num_heads, self.kv_lora_rank).transpose(0, 1)
|
| 1024 |
+
# Multiply (N, B, L) x (N, L, V) -> (N, B, V)
|
| 1025 |
+
x = torch.bmm(x, self.W_UV)
|
| 1026 |
+
# Convert from (N, B, V) to (B, N * V)
|
| 1027 |
+
return x.transpose(0, 1).reshape(-1, self.num_heads * self.v_head_dim)
|
| 1028 |
+
|
| 1029 |
+
def process_weights_after_loading(self, act_dtype: torch.dtype):
|
| 1030 |
+
|
| 1031 |
+
def get_layer_weight(layer):
|
| 1032 |
+
WEIGHT_NAMES = ("weight", "qweight", "weight_packed")
|
| 1033 |
+
for attr in WEIGHT_NAMES:
|
| 1034 |
+
if hasattr(layer, attr):
|
| 1035 |
+
return getattr(layer, attr)
|
| 1036 |
+
raise AttributeError(
|
| 1037 |
+
f"Layer '{layer}' has no recognized weight attribute:"
|
| 1038 |
+
f" {WEIGHT_NAMES}.")
|
| 1039 |
+
|
| 1040 |
+
def get_and_maybe_dequant_weights(layer: LinearBase):
|
| 1041 |
+
if not isinstance(layer.quant_method, UnquantizedLinearMethod):
|
| 1042 |
+
# NOTE: This should only be used offline, since it's O(N^3)
|
| 1043 |
+
eye = torch.eye(layer.input_size_per_partition,
|
| 1044 |
+
dtype=act_dtype,
|
| 1045 |
+
device=get_layer_weight(layer).device)
|
| 1046 |
+
dequant_weights = layer.quant_method.apply(layer,
|
| 1047 |
+
eye,
|
| 1048 |
+
bias=None)
|
| 1049 |
+
del eye
|
| 1050 |
+
# standardize to (output, input)
|
| 1051 |
+
return dequant_weights.T
|
| 1052 |
+
return layer.weight
|
| 1053 |
+
|
| 1054 |
+
# we currently do not have quantized bmm's which are needed for
|
| 1055 |
+
# `W_UV` and `W_UK_T`, we we just store fp16/bf16 copies and perform
|
| 1056 |
+
# the bmm's in 16-bit, the extra memory overhead of this is fairly low
|
| 1057 |
+
kv_b_proj_weight = get_and_maybe_dequant_weights(self.kv_b_proj).T
|
| 1058 |
+
assert kv_b_proj_weight.shape == (
|
| 1059 |
+
self.kv_lora_rank,
|
| 1060 |
+
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim)), (
|
| 1061 |
+
f"{kv_b_proj_weight.shape=}, "
|
| 1062 |
+
f"{self.kv_lora_rank=}, "
|
| 1063 |
+
f"{self.num_heads=}, "
|
| 1064 |
+
f"{self.qk_nope_head_dim=}, "
|
| 1065 |
+
f"{self.v_head_dim=}")
|
| 1066 |
+
kv_b_proj_weight = kv_b_proj_weight.view(
|
| 1067 |
+
self.kv_lora_rank,
|
| 1068 |
+
self.num_heads,
|
| 1069 |
+
self.qk_nope_head_dim + self.v_head_dim,
|
| 1070 |
+
)
|
| 1071 |
+
|
| 1072 |
+
W_UK, W_UV = kv_b_proj_weight.split(
|
| 1073 |
+
[self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 1074 |
+
|
| 1075 |
+
# Convert from (L, N, V) to (N, L, V)
|
| 1076 |
+
self.W_UV = W_UV.transpose(0, 1)
|
| 1077 |
+
# Convert from (L, N, P) to (N, P, L)
|
| 1078 |
+
self.W_UK_T = W_UK.permute(1, 2, 0)
|
| 1079 |
+
|
| 1080 |
+
def _compute_prefill_context(
|
| 1081 |
+
self,
|
| 1082 |
+
q: torch.Tensor,
|
| 1083 |
+
kv_c_and_k_pe_cache: torch.Tensor,
|
| 1084 |
+
attn_metadata: MLACommonMetadata,
|
| 1085 |
+
):
|
| 1086 |
+
prefill_metadata = attn_metadata.prefill_metadata
|
| 1087 |
+
assert prefill_metadata is not None
|
| 1088 |
+
assert prefill_metadata.context_chunk_seq_tot is not None
|
| 1089 |
+
assert prefill_metadata.context_chunk_cu_seq_lens is not None
|
| 1090 |
+
assert prefill_metadata.context_chunk_starts is not None
|
| 1091 |
+
assert prefill_metadata.context_chunk_max_seq_lens is not None
|
| 1092 |
+
assert prefill_metadata.context_lens_tensor is not None
|
| 1093 |
+
|
| 1094 |
+
output = None
|
| 1095 |
+
iters = len(prefill_metadata.context_chunk_seq_tot)
|
| 1096 |
+
|
| 1097 |
+
# Fetch from attn_metadata directly, since it late bound by
|
| 1098 |
+
# MLAAttentionState, grabbing it directly `attn_metadata` can avoid
|
| 1099 |
+
# any weirdness around prefill_metadata caching
|
| 1100 |
+
assert attn_metadata.context_chunk_workspace is not None
|
| 1101 |
+
workspace = attn_metadata.context_chunk_workspace
|
| 1102 |
+
|
| 1103 |
+
for i in range(iters):
|
| 1104 |
+
toks = prefill_metadata.context_chunk_seq_tot[i]
|
| 1105 |
+
|
| 1106 |
+
ops.gather_cache(
|
| 1107 |
+
src_cache=kv_c_and_k_pe_cache,
|
| 1108 |
+
dst=workspace,
|
| 1109 |
+
block_table=prefill_metadata.block_tables,
|
| 1110 |
+
cu_seq_lens=prefill_metadata.context_chunk_cu_seq_lens[i],
|
| 1111 |
+
batch_size=prefill_metadata.num_prefills,
|
| 1112 |
+
seq_starts=prefill_metadata.context_chunk_starts[i],
|
| 1113 |
+
)
|
| 1114 |
+
|
| 1115 |
+
kv_c_normed = workspace[:toks]\
|
| 1116 |
+
[..., :self.kv_lora_rank]
|
| 1117 |
+
k_pe = workspace[:toks]\
|
| 1118 |
+
[..., self.kv_lora_rank:].unsqueeze(1)
|
| 1119 |
+
|
| 1120 |
+
kv_nope = self.kv_b_proj(kv_c_normed)[0].view( \
|
| 1121 |
+
-1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
|
| 1122 |
+
k_nope, v = kv_nope\
|
| 1123 |
+
.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 1124 |
+
|
| 1125 |
+
k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))),
|
| 1126 |
+
dim=-1)
|
| 1127 |
+
|
| 1128 |
+
attn_output, attn_softmax_lse = \
|
| 1129 |
+
self._flash_attn_varlen_diff_headdims(
|
| 1130 |
+
q=q,
|
| 1131 |
+
k=k,
|
| 1132 |
+
v=v,
|
| 1133 |
+
cu_seqlens_q=prefill_metadata.query_start_loc,
|
| 1134 |
+
cu_seqlens_k=prefill_metadata.context_chunk_cu_seq_lens[i],
|
| 1135 |
+
max_seqlen_q=prefill_metadata.max_query_len,
|
| 1136 |
+
max_seqlen_k=prefill_metadata.context_chunk_max_seq_lens[i],
|
| 1137 |
+
softmax_scale=self.scale,
|
| 1138 |
+
causal=False, # Context is unmasked
|
| 1139 |
+
return_softmax_lse=True,
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
if output is None:
|
| 1143 |
+
output = attn_output
|
| 1144 |
+
output_lse = attn_softmax_lse
|
| 1145 |
+
else:
|
| 1146 |
+
output_tmp = torch.empty_like(output)
|
| 1147 |
+
output_lse_tmp = torch.empty_like(output_lse)
|
| 1148 |
+
merge_attn_states(
|
| 1149 |
+
output=output_tmp,
|
| 1150 |
+
output_lse=output_lse_tmp,
|
| 1151 |
+
prefix_output=output,
|
| 1152 |
+
prefix_lse=output_lse,
|
| 1153 |
+
suffix_output=attn_output,
|
| 1154 |
+
suffix_lse=attn_softmax_lse,
|
| 1155 |
+
)
|
| 1156 |
+
output = output_tmp
|
| 1157 |
+
output_lse = output_lse_tmp
|
| 1158 |
+
|
| 1159 |
+
return output, output_lse
|
| 1160 |
+
|
| 1161 |
+
def _forward_prefill(
|
| 1162 |
+
self,
|
| 1163 |
+
q: torch.Tensor,
|
| 1164 |
+
kv_c_normed: torch.Tensor,
|
| 1165 |
+
k_pe: torch.Tensor,
|
| 1166 |
+
kv_c_and_k_pe_cache: torch.Tensor,
|
| 1167 |
+
attn_metadata: MLACommonMetadata,
|
| 1168 |
+
) -> torch.Tensor:
|
| 1169 |
+
|
| 1170 |
+
prefill_metadata = attn_metadata.prefill_metadata
|
| 1171 |
+
assert prefill_metadata is not None
|
| 1172 |
+
|
| 1173 |
+
has_context = prefill_metadata.context_lens_tensor is not None \
|
| 1174 |
+
and prefill_metadata.context_lens_tensor.max() > 0
|
| 1175 |
+
|
| 1176 |
+
kv_nope = self.kv_b_proj(kv_c_normed)[0].view(\
|
| 1177 |
+
-1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
|
| 1178 |
+
k_nope, v = kv_nope\
|
| 1179 |
+
.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 1180 |
+
|
| 1181 |
+
k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), dim=-1)
|
| 1182 |
+
|
| 1183 |
+
output = self._flash_attn_varlen_diff_headdims(
|
| 1184 |
+
q=q,
|
| 1185 |
+
k=k,
|
| 1186 |
+
v=v,
|
| 1187 |
+
cu_seqlens_q=prefill_metadata.query_start_loc,
|
| 1188 |
+
cu_seqlens_k=prefill_metadata.query_start_loc,
|
| 1189 |
+
max_seqlen_q=prefill_metadata.max_prefill_seq_len,
|
| 1190 |
+
max_seqlen_k=prefill_metadata.max_prefill_seq_len,
|
| 1191 |
+
softmax_scale=self.scale,
|
| 1192 |
+
causal=True,
|
| 1193 |
+
return_softmax_lse=has_context,
|
| 1194 |
+
)
|
| 1195 |
+
|
| 1196 |
+
if has_context:
|
| 1197 |
+
# ROCm flash_attn_varlen_func will return 3 objects instead of 2
|
| 1198 |
+
suffix_output, suffix_lse = output
|
| 1199 |
+
context_output, context_lse = self._compute_prefill_context( \
|
| 1200 |
+
q, kv_c_and_k_pe_cache, attn_metadata)
|
| 1201 |
+
|
| 1202 |
+
output = torch.empty_like(suffix_output)
|
| 1203 |
+
merge_attn_states(
|
| 1204 |
+
output=output,
|
| 1205 |
+
prefix_output=context_output,
|
| 1206 |
+
prefix_lse=context_lse,
|
| 1207 |
+
suffix_output=suffix_output,
|
| 1208 |
+
suffix_lse=suffix_lse,
|
| 1209 |
+
)
|
| 1210 |
+
|
| 1211 |
+
# unpad if necessary
|
| 1212 |
+
if self._pad_v:
|
| 1213 |
+
output = output[..., :v.shape[-1]]
|
| 1214 |
+
|
| 1215 |
+
return output.flatten(start_dim=-2)
|
| 1216 |
+
|
| 1217 |
+
@abstractmethod
|
| 1218 |
+
def _forward_decode(
|
| 1219 |
+
self,
|
| 1220 |
+
ql_nope: torch.Tensor,
|
| 1221 |
+
q_pe: torch.Tensor,
|
| 1222 |
+
kv_c_and_k_pe_cache: torch.Tensor,
|
| 1223 |
+
attn_metadata: T,
|
| 1224 |
+
) -> torch.Tensor:
|
| 1225 |
+
raise NotImplementedError
|
| 1226 |
+
|
| 1227 |
+
def forward(
|
| 1228 |
+
self,
|
| 1229 |
+
layer: AttentionLayer,
|
| 1230 |
+
q: torch.Tensor, # query in unified attn
|
| 1231 |
+
k_c_normed: torch.Tensor, # key in unified attn
|
| 1232 |
+
k_pe: torch.Tensor, # value in unified attn
|
| 1233 |
+
kv_cache: torch.Tensor,
|
| 1234 |
+
attn_metadata: T,
|
| 1235 |
+
output: Optional[torch.Tensor] = None,
|
| 1236 |
+
output_scale: Optional[torch.Tensor] = None,
|
| 1237 |
+
) -> torch.Tensor:
|
| 1238 |
+
if output is not None:
|
| 1239 |
+
raise NotImplementedError(
|
| 1240 |
+
"output is not yet supported for MLAImplBase")
|
| 1241 |
+
|
| 1242 |
+
if output_scale is not None:
|
| 1243 |
+
raise NotImplementedError(
|
| 1244 |
+
"fused output quantization is not yet supported"
|
| 1245 |
+
" for MLAImplBase")
|
| 1246 |
+
|
| 1247 |
+
if attn_metadata.is_profile_run and \
|
| 1248 |
+
attn_metadata.context_chunk_workspace is not None:
|
| 1249 |
+
# During the profile run try to simulate to worse case output size
|
| 1250 |
+
# for `self.kv_b_proj(kv_c_normed)` in `_compute_prefill_context`
|
| 1251 |
+
# since this can be large
|
| 1252 |
+
_ = torch.empty(
|
| 1253 |
+
(attn_metadata.context_chunk_workspace.shape[0],
|
| 1254 |
+
self.num_heads, self.qk_nope_head_dim + self.v_head_dim),
|
| 1255 |
+
device=k_c_normed.device,
|
| 1256 |
+
dtype=k_c_normed.dtype,
|
| 1257 |
+
)
|
| 1258 |
+
|
| 1259 |
+
has_decode = attn_metadata.decode_metadata is not None
|
| 1260 |
+
has_prefill = attn_metadata.prefill_metadata is not None
|
| 1261 |
+
|
| 1262 |
+
num_prefill_tokens: int = attn_metadata.num_prefill_tokens
|
| 1263 |
+
q = q.view(-1, self.num_heads, self.qk_head_dim)
|
| 1264 |
+
|
| 1265 |
+
decode_q = q[num_prefill_tokens:]
|
| 1266 |
+
|
| 1267 |
+
prefill_q = q[:num_prefill_tokens]
|
| 1268 |
+
prefill_k_pe = k_pe[:num_prefill_tokens]
|
| 1269 |
+
prefill_k_c_normed = k_c_normed[:num_prefill_tokens]
|
| 1270 |
+
|
| 1271 |
+
# write the latent and rope to kv cache
|
| 1272 |
+
if kv_cache.numel() > 0:
|
| 1273 |
+
ops.concat_and_cache_mla(
|
| 1274 |
+
k_c_normed,
|
| 1275 |
+
k_pe.squeeze(1),
|
| 1276 |
+
kv_cache,
|
| 1277 |
+
attn_metadata.slot_mapping.flatten(),
|
| 1278 |
+
kv_cache_dtype=self.kv_cache_dtype,
|
| 1279 |
+
scale=layer._k_scale,
|
| 1280 |
+
)
|
| 1281 |
+
|
| 1282 |
+
output = torch.empty(attn_metadata.num_prefill_tokens +
|
| 1283 |
+
attn_metadata.num_decode_tokens,
|
| 1284 |
+
self.v_head_dim * self.num_heads,
|
| 1285 |
+
device=q.device,
|
| 1286 |
+
dtype=q.dtype)
|
| 1287 |
+
if has_prefill:
|
| 1288 |
+
output[:num_prefill_tokens] = self._forward_prefill(
|
| 1289 |
+
prefill_q, prefill_k_c_normed, prefill_k_pe, kv_cache,
|
| 1290 |
+
attn_metadata)
|
| 1291 |
+
|
| 1292 |
+
if has_decode:
|
| 1293 |
+
decode_q_nope, decode_q_pe = decode_q.split(
|
| 1294 |
+
[self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
| 1295 |
+
# Convert from (B, N, P) to (N, B, P)
|
| 1296 |
+
decode_q_nope = decode_q_nope.transpose(0, 1)
|
| 1297 |
+
# Multiply (N, B, P) x (N, P, L) -> (N, B, L)
|
| 1298 |
+
decode_ql_nope = torch.bmm(decode_q_nope, self.W_UK_T)
|
| 1299 |
+
# Convert from (N, B, L) to (B, N, L)
|
| 1300 |
+
decode_ql_nope = decode_ql_nope.transpose(0, 1)
|
| 1301 |
+
|
| 1302 |
+
output[num_prefill_tokens:] = self._forward_decode(
|
| 1303 |
+
decode_ql_nope, decode_q_pe, kv_cache, attn_metadata)
|
| 1304 |
+
|
| 1305 |
+
return output
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/rocm_aiter_mla.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import TYPE_CHECKING, Optional, Type, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
import vllm.envs as envs
|
| 11 |
+
from vllm.attention.backends.mla.common import (MLACommonBackend,
|
| 12 |
+
MLACommonImpl,
|
| 13 |
+
MLACommonMetadata,
|
| 14 |
+
MLACommonMetadataBuilder,
|
| 15 |
+
MLACommonState)
|
| 16 |
+
from vllm.attention.backends.utils import (compute_slot_mapping,
|
| 17 |
+
compute_slot_mapping_start_idx,
|
| 18 |
+
is_block_tables_empty)
|
| 19 |
+
from vllm.attention.ops.rocm_aiter_mla import (aiter_mla_decode_fwd,
|
| 20 |
+
get_aiter_mla_metadata)
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from vllm.worker.model_runner import ModelInputForGPUBuilder
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def is_aiter_mla_enabled() -> bool:
|
| 27 |
+
return envs.VLLM_ROCM_USE_AITER \
|
| 28 |
+
and envs.VLLM_ROCM_USE_AITER_MLA
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class AiterMLABackend(MLACommonBackend):
|
| 32 |
+
|
| 33 |
+
@staticmethod
|
| 34 |
+
def get_name() -> str:
|
| 35 |
+
return "ROCM_AITER_MLA"
|
| 36 |
+
|
| 37 |
+
@staticmethod
|
| 38 |
+
def get_impl_cls() -> Type["AiterMLAImpl"]:
|
| 39 |
+
return AiterMLAImpl
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
def get_metadata_cls() -> Type["AiterMLAMetadata"]:
|
| 43 |
+
return AiterMLAMetadata
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def get_builder_cls() -> Type["AiterMLAMetadataBuilder"]:
|
| 47 |
+
return AiterMLAMetadataBuilder
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def get_state_cls() -> Type["AiterMLAState"]:
|
| 51 |
+
return AiterMLAState
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass
|
| 55 |
+
class AiterMLAMetadata(MLACommonMetadata):
|
| 56 |
+
# The following 5 tensors are for current version of AITER MLA
|
| 57 |
+
block_table_bound: Optional[torch.Tensor] = None
|
| 58 |
+
# The indptr of the paged kv cache, shape: [batch_size + 1]
|
| 59 |
+
paged_kv_indptr: Optional[torch.Tensor] = None
|
| 60 |
+
# The page indices of the paged kv cache
|
| 61 |
+
paged_kv_indices: Optional[torch.Tensor] = None
|
| 62 |
+
# The number of entries in the last page of each request in
|
| 63 |
+
# the paged kv cache, shape: [batch_size]
|
| 64 |
+
paged_kv_last_page_lens: Optional[torch.Tensor] = None
|
| 65 |
+
|
| 66 |
+
# This is just to make new AITER MLA API work
|
| 67 |
+
# -- MTP support is not added yet.
|
| 68 |
+
qo_indptr: Optional[torch.Tensor] = None
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def prefill_metadata(self):
|
| 72 |
+
prefill_metadata = super().prefill_metadata
|
| 73 |
+
self._cached_prefill_metadata = prefill_metadata
|
| 74 |
+
|
| 75 |
+
if prefill_metadata is not None:
|
| 76 |
+
prefill_metadata.paged_kv_indptr = self.paged_kv_indptr
|
| 77 |
+
prefill_metadata.paged_kv_indices = self.paged_kv_indices
|
| 78 |
+
prefill_metadata\
|
| 79 |
+
.paged_kv_last_page_lens = self.paged_kv_last_page_lens
|
| 80 |
+
prefill_metadata.block_table_bound = self.block_table_bound
|
| 81 |
+
prefill_metadata.qo_indptr = self.qo_indptr
|
| 82 |
+
|
| 83 |
+
# update the cache
|
| 84 |
+
self._cached_prefill_metadata = self.__class__(
|
| 85 |
+
**prefill_metadata.__dict__)
|
| 86 |
+
|
| 87 |
+
return self._cached_prefill_metadata
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def decode_metadata(self):
|
| 91 |
+
decode_metadata = super().decode_metadata
|
| 92 |
+
|
| 93 |
+
self._cached_decode_metadata = decode_metadata
|
| 94 |
+
|
| 95 |
+
if decode_metadata is not None:
|
| 96 |
+
decode_metadata.paged_kv_indptr = self.paged_kv_indptr
|
| 97 |
+
decode_metadata.paged_kv_indices = self.paged_kv_indices
|
| 98 |
+
decode_metadata\
|
| 99 |
+
.paged_kv_last_page_lens = self.paged_kv_last_page_lens
|
| 100 |
+
decode_metadata.block_table_bound = self.block_table_bound
|
| 101 |
+
decode_metadata.qo_indptr = self.qo_indptr
|
| 102 |
+
|
| 103 |
+
# update the cache
|
| 104 |
+
self._cached_decode_metadata = self.__class__(
|
| 105 |
+
**decode_metadata.__dict__)
|
| 106 |
+
|
| 107 |
+
return self._cached_decode_metadata
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
| 111 |
+
BLOCK_TABLE_EXTENDER: list[list[int]] = [[]]
|
| 112 |
+
|
| 113 |
+
def __init__(self, input_builder: "ModelInputForGPUBuilder"):
|
| 114 |
+
super().__init__(input_builder)
|
| 115 |
+
assert self.block_size == 1, "AITER MLA requires only block size 1."
|
| 116 |
+
|
| 117 |
+
def prepare(self):
|
| 118 |
+
super().prepare()
|
| 119 |
+
self.paged_kv_indices: list[int] = []
|
| 120 |
+
self.paged_kv_indptr: list[int] = [0]
|
| 121 |
+
self.paged_kv_last_page_lens: list[int] = []
|
| 122 |
+
self.total_blocks = 0
|
| 123 |
+
self.qo_indptr: list[int] = [0]
|
| 124 |
+
|
| 125 |
+
def _add_seq_group(self, inter_data, chunked_prefill_enabled: bool,
|
| 126 |
+
prefix_cache_hit: bool):
|
| 127 |
+
"""Add a sequence group to the metadata. Specifically update/append
|
| 128 |
+
1. context length.
|
| 129 |
+
2. block table.
|
| 130 |
+
3. slot mapping.
|
| 131 |
+
"""
|
| 132 |
+
is_prompt = inter_data.is_prompt
|
| 133 |
+
block_tables = inter_data.block_tables
|
| 134 |
+
|
| 135 |
+
for (seq_id, token_len, seq_len, curr_seq_len, query_len, context_len,
|
| 136 |
+
curr_sliding_window_block) in zip(
|
| 137 |
+
inter_data.seq_ids, [len(t) for t in inter_data.input_tokens],
|
| 138 |
+
inter_data.orig_seq_lens, inter_data.seq_lens,
|
| 139 |
+
inter_data.query_lens, inter_data.context_lens,
|
| 140 |
+
inter_data.curr_sliding_window_blocks):
|
| 141 |
+
self.context_lens.append(context_len)
|
| 142 |
+
if is_prompt:
|
| 143 |
+
self.num_prefills += 1
|
| 144 |
+
self.num_prefill_tokens += token_len
|
| 145 |
+
self.prefill_seq_lens.append(seq_len)
|
| 146 |
+
else:
|
| 147 |
+
self.num_decode_tokens += query_len
|
| 148 |
+
self.curr_seq_lens.append(curr_seq_len)
|
| 149 |
+
|
| 150 |
+
# Compute block table.
|
| 151 |
+
# TODO(sang): Combine chunked prefill and prefix caching by
|
| 152 |
+
# only allowing multiple of block_size chunk size.
|
| 153 |
+
# NOTE: This only works for oooooooxxx style attention.
|
| 154 |
+
block_table = []
|
| 155 |
+
if prefix_cache_hit:
|
| 156 |
+
# NOTE(woosuk): For flash-attn, the block table should
|
| 157 |
+
# include the entries for the incoming prefill tokens.
|
| 158 |
+
block_table = block_tables[seq_id]
|
| 159 |
+
elif ((chunked_prefill_enabled or not is_prompt)
|
| 160 |
+
and block_tables is not None):
|
| 161 |
+
if curr_sliding_window_block == 0:
|
| 162 |
+
block_table = block_tables[seq_id]
|
| 163 |
+
else:
|
| 164 |
+
block_table = block_tables[seq_id][
|
| 165 |
+
-curr_sliding_window_block:]
|
| 166 |
+
self.block_tables.append(block_table)
|
| 167 |
+
|
| 168 |
+
# Compute slot mapping.
|
| 169 |
+
is_profile_run = is_block_tables_empty(block_tables)
|
| 170 |
+
start_idx = compute_slot_mapping_start_idx(is_prompt, query_len,
|
| 171 |
+
context_len,
|
| 172 |
+
self.sliding_window)
|
| 173 |
+
compute_slot_mapping(is_profile_run, self.slot_mapping, seq_id,
|
| 174 |
+
seq_len, context_len, start_idx,
|
| 175 |
+
self.block_size, inter_data.block_tables)
|
| 176 |
+
if is_profile_run:
|
| 177 |
+
return
|
| 178 |
+
|
| 179 |
+
# Update paged_kv_* tensors only for non-profile run
|
| 180 |
+
block_table = block_tables[seq_id]
|
| 181 |
+
self._update_paged_kv_tensors(block_table, seq_len)
|
| 182 |
+
|
| 183 |
+
def _update_paged_kv_tensors(self, block_table: list[int], seq_len: int):
|
| 184 |
+
# Get the number of valid blocks based on sequence length.
|
| 185 |
+
# If seq_len = 16, block_size = 16,
|
| 186 |
+
# block_table_bound is 1 with 1 valid block.
|
| 187 |
+
# If seq_len = 15, block_size = 16,
|
| 188 |
+
# block_table_bound is 0 + 1 with 1 valid block.
|
| 189 |
+
self.total_blocks += len(block_table)
|
| 190 |
+
block_table_bound = seq_len // self.block_size + 1 \
|
| 191 |
+
if seq_len % self.block_size != 0 \
|
| 192 |
+
else seq_len // self.block_size
|
| 193 |
+
self.paged_kv_indices.extend(block_table[:block_table_bound])
|
| 194 |
+
self.paged_kv_indptr.append(self.paged_kv_indptr[-1] +
|
| 195 |
+
block_table_bound)
|
| 196 |
+
self.qo_indptr.append(self.qo_indptr[-1] + 1)
|
| 197 |
+
|
| 198 |
+
last_page_len = seq_len % self.block_size
|
| 199 |
+
if last_page_len == 0:
|
| 200 |
+
last_page_len = self.block_size
|
| 201 |
+
self.paged_kv_last_page_lens.append(last_page_len)
|
| 202 |
+
|
| 203 |
+
def build(self, seq_lens: list[int], query_lens: list[int],
|
| 204 |
+
cuda_graph_pad_size: int, batch_size: int) -> AiterMLAMetadata:
|
| 205 |
+
metadata = super().build(seq_lens, query_lens, cuda_graph_pad_size,
|
| 206 |
+
batch_size)
|
| 207 |
+
device = self.runner.device
|
| 208 |
+
use_captured_graph = cuda_graph_pad_size != -1
|
| 209 |
+
|
| 210 |
+
if use_captured_graph:
|
| 211 |
+
last_paged_kv_indptr = self.paged_kv_indptr[-1]
|
| 212 |
+
self.paged_kv_indptr.extend([last_paged_kv_indptr] *
|
| 213 |
+
cuda_graph_pad_size)
|
| 214 |
+
self.paged_kv_last_page_lens.extend([0] * cuda_graph_pad_size)
|
| 215 |
+
last_qo_indptr = self.qo_indptr[-1]
|
| 216 |
+
self.qo_indptr.extend([last_qo_indptr] * cuda_graph_pad_size)
|
| 217 |
+
|
| 218 |
+
# For current version of AITER MLA
|
| 219 |
+
if len(self.paged_kv_indptr) > 0:
|
| 220 |
+
# extend to the maximum number of blocks as returned by the
|
| 221 |
+
# scheduler
|
| 222 |
+
self.paged_kv_indices.extend(
|
| 223 |
+
[0] * (self.total_blocks - len(self.paged_kv_indices)))
|
| 224 |
+
paged_kv_indices_tensor = torch.tensor(self.paged_kv_indices,
|
| 225 |
+
device=device,
|
| 226 |
+
dtype=torch.int)
|
| 227 |
+
paged_kv_indptr_tensor = torch.tensor(self.paged_kv_indptr,
|
| 228 |
+
device=device,
|
| 229 |
+
dtype=torch.int)
|
| 230 |
+
paged_kv_last_page_lens_tensor = torch.tensor(
|
| 231 |
+
self.paged_kv_last_page_lens, device=device, dtype=torch.int)
|
| 232 |
+
block_table_bound_tensor = torch.zeros(len(self.paged_kv_indptr) -
|
| 233 |
+
1,
|
| 234 |
+
device=device,
|
| 235 |
+
dtype=torch.int)
|
| 236 |
+
|
| 237 |
+
qo_indptr = torch.tensor(self.qo_indptr,
|
| 238 |
+
device=device,
|
| 239 |
+
dtype=torch.int)
|
| 240 |
+
else:
|
| 241 |
+
paged_kv_indices_tensor = None
|
| 242 |
+
paged_kv_indptr_tensor = None
|
| 243 |
+
paged_kv_last_page_lens_tensor = None
|
| 244 |
+
block_table_bound_tensor = None
|
| 245 |
+
qo_indptr = None
|
| 246 |
+
|
| 247 |
+
metadata.paged_kv_indptr = paged_kv_indptr_tensor
|
| 248 |
+
metadata.paged_kv_indices = paged_kv_indices_tensor
|
| 249 |
+
metadata.paged_kv_last_page_lens = paged_kv_last_page_lens_tensor
|
| 250 |
+
metadata.block_table_bound = block_table_bound_tensor
|
| 251 |
+
metadata.qo_indptr = qo_indptr
|
| 252 |
+
|
| 253 |
+
return metadata
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class AiterMLAState(MLACommonState[AiterMLAMetadata]):
|
| 257 |
+
|
| 258 |
+
@contextmanager
|
| 259 |
+
def graph_capture(self, max_batch_size: int):
|
| 260 |
+
kv_indices, kv_indptr, last_page_lens, qo_indptr = \
|
| 261 |
+
get_aiter_mla_metadata(
|
| 262 |
+
max_batch_size=max_batch_size,
|
| 263 |
+
block_size=self.runner.block_size,
|
| 264 |
+
max_block_per_batch=\
|
| 265 |
+
self.runner.get_max_block_per_batch(),
|
| 266 |
+
device=self.runner.device)
|
| 267 |
+
self._paged_kv_indices_tensor = kv_indices
|
| 268 |
+
self._paged_kv_indptr_tensor = kv_indptr
|
| 269 |
+
self._paged_kv_last_page_lens_tensor = last_page_lens
|
| 270 |
+
self._qo_indptr_tensor = qo_indptr
|
| 271 |
+
|
| 272 |
+
with super().graph_capture(max_batch_size):
|
| 273 |
+
yield
|
| 274 |
+
|
| 275 |
+
del self._paged_kv_indices_tensor
|
| 276 |
+
del self._paged_kv_indptr_tensor
|
| 277 |
+
del self._paged_kv_last_page_lens_tensor
|
| 278 |
+
del self._qo_indptr_tensor
|
| 279 |
+
|
| 280 |
+
def graph_capture_get_metadata_for_batch(
|
| 281 |
+
self,
|
| 282 |
+
batch_size: int,
|
| 283 |
+
is_encoder_decoder_model: bool = False) -> AiterMLAMetadata:
|
| 284 |
+
|
| 285 |
+
metadata = super().graph_capture_get_metadata_for_batch(
|
| 286 |
+
batch_size, is_encoder_decoder_model)
|
| 287 |
+
|
| 288 |
+
paged_kv_indptr = self._paged_kv_indptr_tensor[:batch_size + 1]
|
| 289 |
+
paged_kv_indices = self._paged_kv_indices_tensor
|
| 290 |
+
paged_kv_last_page_lens = self._paged_kv_last_page_lens_tensor[:
|
| 291 |
+
batch_size]
|
| 292 |
+
qo_indptr = self._qo_indptr_tensor[:batch_size + 1]
|
| 293 |
+
|
| 294 |
+
metadata.paged_kv_indptr = paged_kv_indptr
|
| 295 |
+
metadata.paged_kv_indices = paged_kv_indices
|
| 296 |
+
metadata.paged_kv_last_page_lens = paged_kv_last_page_lens
|
| 297 |
+
metadata.qo_indptr = qo_indptr
|
| 298 |
+
|
| 299 |
+
return metadata
|
| 300 |
+
|
| 301 |
+
def get_graph_input_buffers(self,
|
| 302 |
+
attn_metadata: AiterMLAMetadata,
|
| 303 |
+
is_encoder_decoder_model: bool = False):
|
| 304 |
+
input_buffers = super().get_graph_input_buffers(
|
| 305 |
+
attn_metadata, is_encoder_decoder_model)
|
| 306 |
+
input_buffers[
|
| 307 |
+
'paged_kv_indptr'] = attn_metadata.decode_metadata.paged_kv_indptr
|
| 308 |
+
input_buffers[
|
| 309 |
+
"paged_kv_indices"] = attn_metadata.\
|
| 310 |
+
decode_metadata.paged_kv_indices
|
| 311 |
+
input_buffers[
|
| 312 |
+
"paged_kv_last_page_lens"] = attn_metadata.\
|
| 313 |
+
decode_metadata.paged_kv_last_page_lens
|
| 314 |
+
input_buffers['qo_indptr'] = attn_metadata.qo_indptr
|
| 315 |
+
|
| 316 |
+
return input_buffers
|
| 317 |
+
|
| 318 |
+
def prepare_graph_input_buffers(self,
|
| 319 |
+
input_buffers,
|
| 320 |
+
attn_metadata: AiterMLAMetadata,
|
| 321 |
+
is_encoder_decoder_model: bool = False):
|
| 322 |
+
super().prepare_graph_input_buffers(input_buffers, attn_metadata,
|
| 323 |
+
is_encoder_decoder_model)
|
| 324 |
+
|
| 325 |
+
num_total_blocks = attn_metadata.decode_metadata.paged_kv_indices.shape[
|
| 326 |
+
0]
|
| 327 |
+
input_buffers["paged_kv_indptr"].copy_(
|
| 328 |
+
attn_metadata.decode_metadata.paged_kv_indptr, non_blocking=True)
|
| 329 |
+
input_buffers["paged_kv_indices"][:num_total_blocks].copy_(
|
| 330 |
+
attn_metadata.decode_metadata.paged_kv_indices, non_blocking=True)
|
| 331 |
+
input_buffers["paged_kv_last_page_lens"].copy_(
|
| 332 |
+
attn_metadata.decode_metadata.paged_kv_last_page_lens,
|
| 333 |
+
non_blocking=True)
|
| 334 |
+
input_buffers["qo_indptr"].copy_(
|
| 335 |
+
attn_metadata.decode_metadata.qo_indptr, non_blocking=True)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
| 339 |
+
|
| 340 |
+
def __init__(
|
| 341 |
+
self,
|
| 342 |
+
num_heads: int,
|
| 343 |
+
head_size: int,
|
| 344 |
+
scale: float,
|
| 345 |
+
num_kv_heads: int,
|
| 346 |
+
alibi_slopes: Optional[list[float]],
|
| 347 |
+
sliding_window: Optional[int],
|
| 348 |
+
kv_cache_dtype: str,
|
| 349 |
+
logits_soft_cap: Optional[float],
|
| 350 |
+
attn_type: str,
|
| 351 |
+
kv_sharing_target_layer_name: Optional[str],
|
| 352 |
+
# MLA Specific Arguments
|
| 353 |
+
**mla_args) -> None:
|
| 354 |
+
super().__init__(num_heads, head_size, scale, num_kv_heads,
|
| 355 |
+
alibi_slopes, sliding_window, kv_cache_dtype,
|
| 356 |
+
logits_soft_cap, attn_type,
|
| 357 |
+
kv_sharing_target_layer_name, **mla_args)
|
| 358 |
+
|
| 359 |
+
unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap]
|
| 360 |
+
if any(unsupported_features):
|
| 361 |
+
raise NotImplementedError(
|
| 362 |
+
"Aiter MLA does not support one of the following: "
|
| 363 |
+
"alibi_slopes, sliding_window, logits_soft_cap")
|
| 364 |
+
|
| 365 |
+
from aiter import flash_attn_varlen_func
|
| 366 |
+
self.flash_attn_varlen_func = flash_attn_varlen_func
|
| 367 |
+
|
| 368 |
+
def _flash_attn_varlen_diff_headdims(
|
| 369 |
+
self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor,
|
| 370 |
+
softmax_scale: float, return_softmax_lse: bool,
|
| 371 |
+
**kwargs) -> Union[tuple[torch.Tensor, ...], torch.Tensor]:
|
| 372 |
+
output = self.flash_attn_varlen_func(
|
| 373 |
+
q,
|
| 374 |
+
k,
|
| 375 |
+
v,
|
| 376 |
+
**kwargs,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
return output
|
| 380 |
+
|
| 381 |
+
def _forward_decode(
|
| 382 |
+
self,
|
| 383 |
+
q_nope: torch.Tensor,
|
| 384 |
+
q_pe: torch.Tensor,
|
| 385 |
+
kv_c_and_k_pe_cache: torch.Tensor,
|
| 386 |
+
attn_metadata: AiterMLAMetadata,
|
| 387 |
+
) -> torch.Tensor:
|
| 388 |
+
assert kv_c_and_k_pe_cache.numel() > 0
|
| 389 |
+
|
| 390 |
+
decode_meta = attn_metadata.decode_metadata
|
| 391 |
+
assert decode_meta is not None
|
| 392 |
+
B = q_nope.shape[0]
|
| 393 |
+
|
| 394 |
+
q = torch.cat([q_nope, q_pe], dim=-1)
|
| 395 |
+
o = torch.empty(B,
|
| 396 |
+
self.num_heads,
|
| 397 |
+
self.kv_lora_rank,
|
| 398 |
+
dtype=q.dtype,
|
| 399 |
+
device=q.device)
|
| 400 |
+
|
| 401 |
+
kv_buffer = kv_c_and_k_pe_cache.unsqueeze(2)
|
| 402 |
+
|
| 403 |
+
aiter_mla_decode_fwd(q, kv_buffer, o, self.scale,
|
| 404 |
+
attn_metadata.qo_indptr,
|
| 405 |
+
attn_metadata.max_query_len,
|
| 406 |
+
attn_metadata.paged_kv_indptr,
|
| 407 |
+
attn_metadata.paged_kv_indices,
|
| 408 |
+
attn_metadata.paged_kv_last_page_lens)
|
| 409 |
+
|
| 410 |
+
return self._v_up_proj(o)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/rocm_flash_attn.py
ADDED
|
@@ -0,0 +1,948 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
"""Attention layer ROCm GPUs."""
|
| 4 |
+
import itertools
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from functools import cache
|
| 7 |
+
from typing import List, Optional, Tuple, Type
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
import vllm.envs as envs
|
| 12 |
+
from vllm import _custom_ops as ops
|
| 13 |
+
from vllm.attention.backends.abstract import (AttentionBackend, AttentionImpl,
|
| 14 |
+
AttentionLayer,
|
| 15 |
+
AttentionMetadata, AttentionType)
|
| 16 |
+
from vllm.attention.backends.utils import (CommonAttentionState,
|
| 17 |
+
CommonMetadataBuilder)
|
| 18 |
+
from vllm.attention.ops.paged_attn import (PagedAttention,
|
| 19 |
+
PagedAttentionMetadata)
|
| 20 |
+
from vllm.config import get_current_vllm_config
|
| 21 |
+
from vllm.logger import init_logger
|
| 22 |
+
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
| 23 |
+
GroupShape)
|
| 24 |
+
from vllm.platforms import current_platform
|
| 25 |
+
|
| 26 |
+
logger = init_logger(__name__)
|
| 27 |
+
_PARTITION_SIZE_ROCM = 256
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@cache
|
| 31 |
+
def is_rocm_aiter_paged_attn_enabled() -> bool:
|
| 32 |
+
return envs.VLLM_ROCM_USE_AITER_PAGED_ATTN \
|
| 33 |
+
and envs.VLLM_ROCM_USE_AITER \
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@cache
|
| 37 |
+
def _get_paged_attn_module() -> PagedAttention:
|
| 38 |
+
"""
|
| 39 |
+
Initializes the appropriate PagedAttention module from `attention/ops`,
|
| 40 |
+
which is used as helper function
|
| 41 |
+
by `ROCmFlashAttentionImpl` and `ROCmFlashAttentionBackend`.
|
| 42 |
+
|
| 43 |
+
The choice of attention module depends on whether
|
| 44 |
+
AITER paged attention is enabled:
|
| 45 |
+
- If enabled, `ROCmFlashAttentionImpl` uses `AITERPagedAttention`.
|
| 46 |
+
- Otherwise, it defaults to using the original `PagedAttention`.
|
| 47 |
+
"""
|
| 48 |
+
if is_rocm_aiter_paged_attn_enabled():
|
| 49 |
+
# Import AITERPagedAttention only when the flag is enabled
|
| 50 |
+
from vllm.attention.ops.rocm_aiter_paged_attn import (
|
| 51 |
+
AITERPagedAttention)
|
| 52 |
+
return AITERPagedAttention()
|
| 53 |
+
return PagedAttention()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ROCmFlashAttentionBackend(AttentionBackend):
|
| 57 |
+
accept_output_buffer: bool = True
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
def get_name() -> str:
|
| 61 |
+
return "ROCM_FLASH"
|
| 62 |
+
|
| 63 |
+
@staticmethod
|
| 64 |
+
def get_impl_cls() -> Type["ROCmFlashAttentionImpl"]:
|
| 65 |
+
return ROCmFlashAttentionImpl
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def get_metadata_cls() -> Type["AttentionMetadata"]:
|
| 69 |
+
return ROCmFlashAttentionMetadata
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def get_builder_cls() -> Type["ROCmFlashAttentionMetadataBuilder"]:
|
| 73 |
+
return ROCmFlashAttentionMetadataBuilder
|
| 74 |
+
|
| 75 |
+
@staticmethod
|
| 76 |
+
def get_state_cls() -> Type["CommonAttentionState"]:
|
| 77 |
+
return CommonAttentionState
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def get_kv_cache_shape(
|
| 81 |
+
num_blocks: int,
|
| 82 |
+
block_size: int,
|
| 83 |
+
num_kv_heads: int,
|
| 84 |
+
head_size: int,
|
| 85 |
+
) -> Tuple[int, ...]:
|
| 86 |
+
paged_attn = _get_paged_attn_module()
|
| 87 |
+
return paged_attn.get_kv_cache_shape(num_blocks, block_size,
|
| 88 |
+
num_kv_heads, head_size)
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def swap_blocks(
|
| 92 |
+
src_kv_cache: torch.Tensor,
|
| 93 |
+
dst_kv_cache: torch.Tensor,
|
| 94 |
+
src_to_dst: torch.Tensor,
|
| 95 |
+
) -> None:
|
| 96 |
+
paged_attn = _get_paged_attn_module()
|
| 97 |
+
paged_attn.swap_blocks(src_kv_cache, dst_kv_cache, src_to_dst)
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
def copy_blocks(
|
| 101 |
+
kv_caches: List[torch.Tensor],
|
| 102 |
+
src_to_dists: torch.Tensor,
|
| 103 |
+
) -> None:
|
| 104 |
+
paged_attn = _get_paged_attn_module()
|
| 105 |
+
paged_attn.copy_blocks(kv_caches, src_to_dists)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@dataclass
|
| 109 |
+
class ROCmFlashAttentionMetadata(AttentionMetadata, PagedAttentionMetadata):
|
| 110 |
+
"""Metadata for FlashAttentionBackend.
|
| 111 |
+
|
| 112 |
+
NOTE: Any python object stored here is not updated when it is
|
| 113 |
+
cuda-graph replayed. If you have values that need to be changed
|
| 114 |
+
dynamically, it should be stored in tensor. The tensor has to be
|
| 115 |
+
updated from `CUDAGraphRunner.forward` API.
|
| 116 |
+
"""
|
| 117 |
+
# (batch_size,). The sequence length per sequence. Sequence length means
|
| 118 |
+
# the computed tokens + new tokens None if it is a decoding.
|
| 119 |
+
seq_lens: Optional[List[int]]
|
| 120 |
+
# seq_lens stored as a tensor.
|
| 121 |
+
seq_lens_tensor: Optional[torch.Tensor]
|
| 122 |
+
# Maximum sequence length among prefill batch. 0 if there are decoding
|
| 123 |
+
# requests only.
|
| 124 |
+
max_prefill_seq_len: int
|
| 125 |
+
# Maximum sequence length among decode batch. 0 if there are prefill
|
| 126 |
+
# requests only.
|
| 127 |
+
max_decode_seq_len: int
|
| 128 |
+
|
| 129 |
+
# Whether or not if cuda graph is enabled.
|
| 130 |
+
# Cuda-graph is currently enabled for decoding only.
|
| 131 |
+
# TODO(woosuk): Move `use_cuda_graph` out since it's unrelated to attention.
|
| 132 |
+
use_cuda_graph: bool
|
| 133 |
+
|
| 134 |
+
# NOTE(sang): Definition of context_len, query_len, and seq_len.
|
| 135 |
+
# |---------- N-1 iteration --------|
|
| 136 |
+
# |---------------- N iteration ---------------------|
|
| 137 |
+
# |- tokenA -|......................|-- newTokens ---|
|
| 138 |
+
# |---------- context_len ----------|
|
| 139 |
+
# |-------------------- seq_len ----------------------|
|
| 140 |
+
# |-- query_len ---|
|
| 141 |
+
|
| 142 |
+
# Maximum query length in the batch. None for decoding.
|
| 143 |
+
max_query_len: Optional[int] = None
|
| 144 |
+
# (batch_size + 1,). The cumulative subquery lengths of the sequences in
|
| 145 |
+
# the batch, used to index into subquery. E.g., if the subquery length
|
| 146 |
+
# is [4, 6], it is [0, 4, 10].
|
| 147 |
+
query_start_loc: Optional[torch.Tensor] = None
|
| 148 |
+
# (batch_size + 1,). The cumulative sequence lengths of the sequences in
|
| 149 |
+
# the batch, used to index into sequence. E.g., if the sequence length is
|
| 150 |
+
# [4, 6], it is [0, 4, 10].
|
| 151 |
+
seq_start_loc: Optional[torch.Tensor] = None
|
| 152 |
+
# (batch_size,) A tensor of context lengths (tokens that are computed
|
| 153 |
+
# so far).
|
| 154 |
+
context_lens_tensor: Optional[torch.Tensor] = None
|
| 155 |
+
|
| 156 |
+
# Max number of query tokens among request in the batch.
|
| 157 |
+
max_decode_query_len: Optional[int] = None
|
| 158 |
+
|
| 159 |
+
_cached_prefill_metadata: Optional["ROCmFlashAttentionMetadata"] = None
|
| 160 |
+
_cached_decode_metadata: Optional["ROCmFlashAttentionMetadata"] = None
|
| 161 |
+
|
| 162 |
+
# Begin encoder attn & enc/dec cross-attn fields...
|
| 163 |
+
|
| 164 |
+
# Encoder sequence lengths representation
|
| 165 |
+
encoder_seq_lens: Optional[List[int]] = None
|
| 166 |
+
encoder_seq_lens_tensor: Optional[torch.Tensor] = None
|
| 167 |
+
|
| 168 |
+
# Maximum sequence length among encoder sequences
|
| 169 |
+
max_encoder_seq_len: Optional[int] = None
|
| 170 |
+
|
| 171 |
+
# Number of tokens input to encoder
|
| 172 |
+
num_encoder_tokens: Optional[int] = None
|
| 173 |
+
|
| 174 |
+
# Cross-attention memory-mapping data structures: slot mapping
|
| 175 |
+
# and block tables
|
| 176 |
+
cross_slot_mapping: Optional[torch.Tensor] = None
|
| 177 |
+
cross_block_tables: Optional[torch.Tensor] = None
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def prefill_metadata(self) -> Optional["ROCmFlashAttentionMetadata"]:
|
| 181 |
+
if self.num_prefills == 0:
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
if self._cached_prefill_metadata is not None:
|
| 185 |
+
return self._cached_prefill_metadata
|
| 186 |
+
|
| 187 |
+
assert self.seq_lens is not None
|
| 188 |
+
assert self.seq_lens_tensor is not None
|
| 189 |
+
assert self.block_tables is not None
|
| 190 |
+
|
| 191 |
+
self._cached_prefill_metadata = ROCmFlashAttentionMetadata(
|
| 192 |
+
num_prefills=self.num_prefills,
|
| 193 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 194 |
+
num_decode_tokens=0,
|
| 195 |
+
slot_mapping=self.slot_mapping[:self.num_prefill_tokens],
|
| 196 |
+
multi_modal_placeholder_index_maps=self.
|
| 197 |
+
multi_modal_placeholder_index_maps,
|
| 198 |
+
enable_kv_scales_calculation=self.enable_kv_scales_calculation,
|
| 199 |
+
seq_lens=self.seq_lens[:self.num_prefills],
|
| 200 |
+
seq_lens_tensor=self.seq_lens_tensor[:self.num_prefills],
|
| 201 |
+
max_query_len=self.max_query_len,
|
| 202 |
+
max_prefill_seq_len=self.max_prefill_seq_len,
|
| 203 |
+
max_decode_seq_len=0,
|
| 204 |
+
query_start_loc=None if self.query_start_loc is None else
|
| 205 |
+
self.query_start_loc[:self.num_prefills + 1],
|
| 206 |
+
seq_start_loc=None if self.seq_start_loc is None else
|
| 207 |
+
self.seq_start_loc[:self.num_prefills + 1],
|
| 208 |
+
context_lens_tensor=None if self.context_lens_tensor is None else
|
| 209 |
+
self.context_lens_tensor[:self.num_prefills],
|
| 210 |
+
block_tables=self.block_tables[:self.num_prefills],
|
| 211 |
+
use_cuda_graph=False,
|
| 212 |
+
# Begin encoder & cross attn fields below...
|
| 213 |
+
encoder_seq_lens=self.encoder_seq_lens,
|
| 214 |
+
encoder_seq_lens_tensor=self.encoder_seq_lens_tensor,
|
| 215 |
+
max_encoder_seq_len=self.max_encoder_seq_len,
|
| 216 |
+
cross_slot_mapping=self.cross_slot_mapping,
|
| 217 |
+
cross_block_tables=self.cross_block_tables)
|
| 218 |
+
return self._cached_prefill_metadata
|
| 219 |
+
|
| 220 |
+
@property
|
| 221 |
+
def decode_metadata(self) -> Optional["ROCmFlashAttentionMetadata"]:
|
| 222 |
+
if self.num_decode_tokens == 0:
|
| 223 |
+
return None
|
| 224 |
+
|
| 225 |
+
if self._cached_decode_metadata is not None:
|
| 226 |
+
return self._cached_decode_metadata
|
| 227 |
+
assert self.block_tables is not None
|
| 228 |
+
assert self.seq_lens_tensor is not None
|
| 229 |
+
|
| 230 |
+
self._cached_decode_metadata = ROCmFlashAttentionMetadata(
|
| 231 |
+
num_prefills=0,
|
| 232 |
+
num_prefill_tokens=0,
|
| 233 |
+
num_decode_tokens=self.num_decode_tokens,
|
| 234 |
+
slot_mapping=self.slot_mapping[self.num_prefill_tokens:],
|
| 235 |
+
multi_modal_placeholder_index_maps=None,
|
| 236 |
+
enable_kv_scales_calculation=True,
|
| 237 |
+
seq_lens=None,
|
| 238 |
+
seq_lens_tensor=self.seq_lens_tensor[self.num_prefills:],
|
| 239 |
+
max_query_len=None,
|
| 240 |
+
max_prefill_seq_len=0,
|
| 241 |
+
max_decode_seq_len=self.max_decode_seq_len,
|
| 242 |
+
query_start_loc=None,
|
| 243 |
+
seq_start_loc=None,
|
| 244 |
+
context_lens_tensor=None,
|
| 245 |
+
block_tables=self.block_tables[self.num_prefills:],
|
| 246 |
+
use_cuda_graph=self.use_cuda_graph,
|
| 247 |
+
# Begin encoder & cross attn fields below...
|
| 248 |
+
encoder_seq_lens=self.encoder_seq_lens,
|
| 249 |
+
encoder_seq_lens_tensor=self.encoder_seq_lens_tensor,
|
| 250 |
+
max_encoder_seq_len=self.max_encoder_seq_len,
|
| 251 |
+
cross_slot_mapping=self.cross_slot_mapping,
|
| 252 |
+
cross_block_tables=self.cross_block_tables)
|
| 253 |
+
# Batch may be composed of prefill|decodes, adjust query start indices
|
| 254 |
+
# to refer to the start of decodes when the two are split apart.
|
| 255 |
+
# E.g. in tokens:[3 prefills|6 decodes], query_start_loc=[3,9] => [0,6].
|
| 256 |
+
if self._cached_decode_metadata.query_start_loc is not None:
|
| 257 |
+
qs = self._cached_decode_metadata.query_start_loc
|
| 258 |
+
self._cached_decode_metadata.query_start_loc = qs - qs[0]
|
| 259 |
+
return self._cached_decode_metadata
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class ROCmFlashAttentionMetadataBuilder(
|
| 263 |
+
CommonMetadataBuilder[ROCmFlashAttentionMetadata]):
|
| 264 |
+
|
| 265 |
+
_metadata_cls = ROCmFlashAttentionMetadata
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _make_alibi_bias(alibi_slopes: torch.Tensor,
|
| 269 |
+
dtype: torch.dtype,
|
| 270 |
+
seq_lens: Optional[List[int]],
|
| 271 |
+
make_attn_mask: bool = True) -> List[torch.Tensor]:
|
| 272 |
+
attn_biases = []
|
| 273 |
+
if seq_lens:
|
| 274 |
+
for seq_len in seq_lens:
|
| 275 |
+
bias = torch.arange(seq_len, dtype=dtype)
|
| 276 |
+
# NOTE(zhuohan): HF uses
|
| 277 |
+
# `bias = bias[None, :].repeat(seq_len, 1)`
|
| 278 |
+
# here. We find that both biases give the same results, but
|
| 279 |
+
# the bias below more accurately follows the original ALiBi
|
| 280 |
+
# paper.
|
| 281 |
+
bias = bias[None, :] - bias[:, None]
|
| 282 |
+
|
| 283 |
+
num_heads = alibi_slopes.shape[0]
|
| 284 |
+
bias = bias[None, :].repeat(
|
| 285 |
+
(num_heads, 1, 1)).to(alibi_slopes.device)
|
| 286 |
+
bias.mul_(alibi_slopes[:, None, None])
|
| 287 |
+
if make_attn_mask:
|
| 288 |
+
inf_mask = torch.empty(
|
| 289 |
+
(1, seq_len, seq_len),
|
| 290 |
+
dtype=bias.dtype).fill_(-torch.inf).triu_(diagonal=1).to(
|
| 291 |
+
alibi_slopes.device)
|
| 292 |
+
attn_biases.append((bias + inf_mask).to(dtype))
|
| 293 |
+
else:
|
| 294 |
+
attn_biases.append(bias.to(dtype))
|
| 295 |
+
|
| 296 |
+
return attn_biases
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _get_seq_len_block_table_args(
|
| 300 |
+
attn_metadata: ROCmFlashAttentionMetadata,
|
| 301 |
+
attn_type: str,
|
| 302 |
+
) -> tuple:
|
| 303 |
+
'''
|
| 304 |
+
The particular choice of sequence-length
|
| 305 |
+
attributes which should be extracted from attn_metadata is dependent
|
| 306 |
+
on the type of attention operation.
|
| 307 |
+
|
| 308 |
+
Decoder attn -> select entirely decoder self-attention-related fields
|
| 309 |
+
Encoder/decoder cross-attn -> select encoder sequence lengths
|
| 310 |
+
Encoder attn -> select encoder sequence lengths fields
|
| 311 |
+
Encoder-only attn -> select prefill sequence lengths with
|
| 312 |
+
bidirectional attention
|
| 313 |
+
|
| 314 |
+
Arguments:
|
| 315 |
+
|
| 316 |
+
* attn_metadata: Attention metadata structure associated with attention op
|
| 317 |
+
* attn_type: encoder attention, decoder self-attention,
|
| 318 |
+
encoder/decoder cross-attention, encoder-only
|
| 319 |
+
|
| 320 |
+
Returns:
|
| 321 |
+
|
| 322 |
+
* Appropriate sequence-lengths tensors for query and key
|
| 323 |
+
* Appropriate max sequence-length scalar
|
| 324 |
+
* Causal masking flag
|
| 325 |
+
'''
|
| 326 |
+
|
| 327 |
+
if attn_type == AttentionType.ENCODER:
|
| 328 |
+
assert attn_metadata.encoder_seq_lens is not None
|
| 329 |
+
assert attn_metadata.encoder_seq_lens_tensor is not None
|
| 330 |
+
query_seq_start_loc = torch.tensor(
|
| 331 |
+
list(itertools.accumulate([0] + attn_metadata.encoder_seq_lens)),
|
| 332 |
+
device=attn_metadata.encoder_seq_lens_tensor.device,
|
| 333 |
+
dtype=attn_metadata.encoder_seq_lens_tensor.dtype)
|
| 334 |
+
causal_mask = False
|
| 335 |
+
|
| 336 |
+
# No block tables associated with encoder attention
|
| 337 |
+
return (query_seq_start_loc, attn_metadata.max_encoder_seq_len,
|
| 338 |
+
query_seq_start_loc, attn_metadata.max_encoder_seq_len,
|
| 339 |
+
attn_metadata.encoder_seq_lens, causal_mask)
|
| 340 |
+
|
| 341 |
+
elif attn_type == AttentionType.ENCODER_ONLY:
|
| 342 |
+
# For encoder-only models, we use the prefill sequence lengths
|
| 343 |
+
assert attn_metadata.seq_lens is not None
|
| 344 |
+
assert attn_metadata.seq_lens_tensor is not None
|
| 345 |
+
query_seq_start_loc = torch.tensor(
|
| 346 |
+
list(itertools.accumulate([0] + attn_metadata.seq_lens)),
|
| 347 |
+
device=attn_metadata.seq_lens_tensor.device,
|
| 348 |
+
dtype=attn_metadata.seq_lens_tensor.dtype)
|
| 349 |
+
max_seq_len = attn_metadata.max_prefill_seq_len
|
| 350 |
+
# Encoder-only models typically use bidirectional attention
|
| 351 |
+
causal_mask = False
|
| 352 |
+
|
| 353 |
+
return (query_seq_start_loc, max_seq_len, query_seq_start_loc,
|
| 354 |
+
max_seq_len, attn_metadata.seq_lens, causal_mask)
|
| 355 |
+
|
| 356 |
+
elif attn_type == AttentionType.DECODER:
|
| 357 |
+
# Decoder self-attention
|
| 358 |
+
# Choose max_seq_len based on whether we are in prompt_run
|
| 359 |
+
assert attn_metadata.seq_lens is not None
|
| 360 |
+
assert attn_metadata.seq_lens_tensor is not None
|
| 361 |
+
query_seq_start_loc = torch.tensor(
|
| 362 |
+
list(itertools.accumulate([0] + attn_metadata.seq_lens)),
|
| 363 |
+
device=attn_metadata.seq_lens_tensor.device,
|
| 364 |
+
dtype=attn_metadata.seq_lens_tensor.dtype)
|
| 365 |
+
max_seq_len = attn_metadata.max_prefill_seq_len
|
| 366 |
+
causal_mask = True
|
| 367 |
+
|
| 368 |
+
return (query_seq_start_loc, max_seq_len, query_seq_start_loc,
|
| 369 |
+
max_seq_len, attn_metadata.seq_lens, causal_mask)
|
| 370 |
+
elif attn_type == AttentionType.ENCODER_DECODER:
|
| 371 |
+
assert attn_metadata.seq_lens is not None
|
| 372 |
+
assert attn_metadata.encoder_seq_lens_tensor is not None
|
| 373 |
+
query_start_loc = torch.tensor(
|
| 374 |
+
list(itertools.accumulate([0] + attn_metadata.seq_lens)),
|
| 375 |
+
device=attn_metadata.encoder_seq_lens_tensor.device,
|
| 376 |
+
dtype=attn_metadata.encoder_seq_lens_tensor.dtype)
|
| 377 |
+
|
| 378 |
+
assert attn_metadata.encoder_seq_lens is not None
|
| 379 |
+
assert attn_metadata.seq_lens_tensor is not None
|
| 380 |
+
key_seq_start_loc = torch.tensor(
|
| 381 |
+
list(itertools.accumulate([0] + attn_metadata.encoder_seq_lens)),
|
| 382 |
+
device=attn_metadata.seq_lens_tensor.device,
|
| 383 |
+
dtype=attn_metadata.seq_lens_tensor.dtype)
|
| 384 |
+
causal_mask = False
|
| 385 |
+
|
| 386 |
+
# Enc/dec cross-attention KVs match encoder sequence length;
|
| 387 |
+
# cross-attention utilizes special "cross" block tables
|
| 388 |
+
return (query_start_loc, attn_metadata.max_prefill_seq_len,
|
| 389 |
+
key_seq_start_loc, attn_metadata.max_encoder_seq_len,
|
| 390 |
+
attn_metadata.seq_lens, causal_mask)
|
| 391 |
+
else:
|
| 392 |
+
raise AttributeError(f"Invalid attention type {str(attn_type)}")
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
class ROCmFlashAttentionImpl(AttentionImpl):
|
| 396 |
+
"""
|
| 397 |
+
If the input tensors contain prompt tokens, the layout is as follows:
|
| 398 |
+
|<--------------- num_prompt_tokens -------------->|
|
| 399 |
+
|<--prompt_0-->|<--prompt_1-->|...|<--prompt_N-1-->|
|
| 400 |
+
|
| 401 |
+
Otherwise, the layout is as follows:
|
| 402 |
+
|<------------------ num_generation_tokens (M) ----------------->|
|
| 403 |
+
|<--generation_0-->|..........|<--generation_M-1-->|<--padding-->|
|
| 404 |
+
|
| 405 |
+
Generation tokens can contain padding when cuda-graph is used.
|
| 406 |
+
Currently, prompt tokens don't contain any padding.
|
| 407 |
+
|
| 408 |
+
The prompts might have different lengths, while the generation tokens
|
| 409 |
+
always have length 1.
|
| 410 |
+
|
| 411 |
+
If chunked prefill is enabled, prefill tokens and decode tokens can be
|
| 412 |
+
batched together in a flattened 1D query.
|
| 413 |
+
|
| 414 |
+
|<----- num_prefill_tokens ---->|<------- num_decode_tokens ----------->|
|
| 415 |
+
|<-prompt_0->|...|<-prompt_N-1->|<-generation_0->|...|<-generation_M-1->|
|
| 416 |
+
|
| 417 |
+
Currently, cuda graph is disabled for chunked prefill, meaning there's no
|
| 418 |
+
padding between prefill and decode tokens.
|
| 419 |
+
"""
|
| 420 |
+
|
| 421 |
+
def __init__(
|
| 422 |
+
self,
|
| 423 |
+
num_heads: int,
|
| 424 |
+
head_size: int,
|
| 425 |
+
scale: float,
|
| 426 |
+
num_kv_heads: int,
|
| 427 |
+
alibi_slopes: Optional[List[float]],
|
| 428 |
+
sliding_window: Optional[int],
|
| 429 |
+
kv_cache_dtype: str,
|
| 430 |
+
logits_soft_cap: Optional[float] = None,
|
| 431 |
+
attn_type: str = AttentionType.DECODER,
|
| 432 |
+
kv_sharing_target_layer_name: Optional[str] = None,
|
| 433 |
+
use_irope: bool = False,
|
| 434 |
+
) -> None:
|
| 435 |
+
if kv_sharing_target_layer_name is not None:
|
| 436 |
+
raise NotImplementedError("KV sharing is not supported in V0 "
|
| 437 |
+
"ROCM_FLASH backend.")
|
| 438 |
+
if use_irope:
|
| 439 |
+
logger.warning_once(
|
| 440 |
+
"Using irope in ROCm Flash Attention is not supported yet, it "
|
| 441 |
+
"will fail back to global attention for long context.")
|
| 442 |
+
if use_irope:
|
| 443 |
+
logger.warning(
|
| 444 |
+
"Using irope in V0 is not supported yet, it will fall back "
|
| 445 |
+
"to global attention for long context.")
|
| 446 |
+
if logits_soft_cap is None:
|
| 447 |
+
# In flash-attn, setting logits_soft_cap as 0 means no soft cap.
|
| 448 |
+
self.logits_soft_cap = 0.0
|
| 449 |
+
else:
|
| 450 |
+
self.logits_soft_cap = logits_soft_cap
|
| 451 |
+
self.attn_type = attn_type
|
| 452 |
+
self.num_heads = num_heads
|
| 453 |
+
self.head_size = head_size
|
| 454 |
+
self.scale = float(scale)
|
| 455 |
+
self.num_kv_heads = num_kv_heads
|
| 456 |
+
if alibi_slopes is not None:
|
| 457 |
+
alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
|
| 458 |
+
self.alibi_slopes = alibi_slopes
|
| 459 |
+
self.sliding_window = ((sliding_window, sliding_window)
|
| 460 |
+
if sliding_window is not None else (-1, -1))
|
| 461 |
+
self.kv_cache_dtype = kv_cache_dtype
|
| 462 |
+
|
| 463 |
+
self.num_queries_per_kv = self.num_heads // self.num_kv_heads
|
| 464 |
+
|
| 465 |
+
self.paged_attn_module = _get_paged_attn_module()
|
| 466 |
+
supported_head_sizes = self.paged_attn_module.get_supported_head_sizes(
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
if head_size not in supported_head_sizes:
|
| 470 |
+
raise ValueError(
|
| 471 |
+
f"Head size {head_size} is not supported by PagedAttention. "
|
| 472 |
+
f"Supported head sizes are: {supported_head_sizes}.")
|
| 473 |
+
|
| 474 |
+
self.use_naive_attn = False
|
| 475 |
+
# NOTE: Allow for switching between Triton and CK. Defaulting to triton.
|
| 476 |
+
self.use_triton_flash_attn = envs.VLLM_USE_TRITON_FLASH_ATTN
|
| 477 |
+
if self.use_triton_flash_attn:
|
| 478 |
+
if logits_soft_cap is not None:
|
| 479 |
+
raise ValueError(
|
| 480 |
+
"ROCm Triton FlashAttention does not support attention"
|
| 481 |
+
" logits soft capping."
|
| 482 |
+
" please try using the ROCm CK "
|
| 483 |
+
"FA backend instead by setting the env var "
|
| 484 |
+
"`VLLM_USE_TRITON_FLASH_ATTN=0`")
|
| 485 |
+
|
| 486 |
+
from vllm.attention.ops.triton_flash_attention import ( # noqa: F401
|
| 487 |
+
triton_attention)
|
| 488 |
+
self.triton_attn_func = triton_attention
|
| 489 |
+
logger.debug("Using Triton FA in ROCmBackend")
|
| 490 |
+
if self.sliding_window != (-1, -1):
|
| 491 |
+
logger.warning("ROCm Triton FA does not currently support "
|
| 492 |
+
"sliding window attention. If using half "
|
| 493 |
+
"precision, please try using the ROCm CK "
|
| 494 |
+
"FA backend instead by setting the env var "
|
| 495 |
+
"`VLLM_USE_TRITON_FLASH_ATTN=0`")
|
| 496 |
+
else:
|
| 497 |
+
# if not using triton, navi3x/navi21/navi10 do not use flash-attn
|
| 498 |
+
# either
|
| 499 |
+
if not current_platform.has_device_capability(90):
|
| 500 |
+
self.use_naive_attn = True
|
| 501 |
+
else:
|
| 502 |
+
try:
|
| 503 |
+
from flash_attn import flash_attn_varlen_func # noqa: F401
|
| 504 |
+
self.fa_attn_func = flash_attn_varlen_func
|
| 505 |
+
logger.debug("Using CK FA in ROCmBackend")
|
| 506 |
+
except ModuleNotFoundError:
|
| 507 |
+
self.use_naive_attn = True
|
| 508 |
+
|
| 509 |
+
if self.use_naive_attn:
|
| 510 |
+
if logits_soft_cap is not None:
|
| 511 |
+
raise ValueError(
|
| 512 |
+
"ROCm Naive FlashAttention does not support "
|
| 513 |
+
"attention logits soft capping.")
|
| 514 |
+
|
| 515 |
+
self.sdpa_attn_func = _sdpa_attention
|
| 516 |
+
logger.debug("Using naive (SDPA) attention in ROCmBackend")
|
| 517 |
+
|
| 518 |
+
self.aiter_kv_scales_initialized = False
|
| 519 |
+
self.force_fp8_attention = (
|
| 520 |
+
get_current_vllm_config() is not None
|
| 521 |
+
and get_current_vllm_config().model_config.override_attention_dtype
|
| 522 |
+
== "fp8")
|
| 523 |
+
|
| 524 |
+
def repeat_kv(self, x: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 525 |
+
"""torch.repeat_interleave(x, dim=1, repeats=n_rep)"""
|
| 526 |
+
tokens, n_kv_heads, head_dim = x.shape
|
| 527 |
+
return (x[:, :,
|
| 528 |
+
None, :].expand(tokens, n_kv_heads, n_rep,
|
| 529 |
+
head_dim).reshape(tokens, n_kv_heads * n_rep,
|
| 530 |
+
head_dim))
|
| 531 |
+
|
| 532 |
+
def fused_output_quant_supported(self, dtype: torch.dtype, static: bool,
|
| 533 |
+
group_shape: GroupShape):
|
| 534 |
+
if self.use_triton_flash_attn:
|
| 535 |
+
return dtype == current_platform.fp8_dtype(
|
| 536 |
+
) and static and group_shape == GroupShape.PER_TENSOR
|
| 537 |
+
|
| 538 |
+
# Only supported in the Triton backend
|
| 539 |
+
return False
|
| 540 |
+
|
| 541 |
+
def forward(
|
| 542 |
+
self,
|
| 543 |
+
layer: AttentionLayer,
|
| 544 |
+
query: torch.Tensor,
|
| 545 |
+
key: torch.Tensor,
|
| 546 |
+
value: torch.Tensor,
|
| 547 |
+
kv_cache: torch.Tensor,
|
| 548 |
+
attn_metadata: ROCmFlashAttentionMetadata,
|
| 549 |
+
output: Optional[torch.Tensor] = None,
|
| 550 |
+
output_scale: Optional[torch.Tensor] = None,
|
| 551 |
+
) -> torch.Tensor:
|
| 552 |
+
"""Forward pass with FlashAttention and PagedAttention.
|
| 553 |
+
|
| 554 |
+
For decoder-only models: query, key and value must be non-None.
|
| 555 |
+
|
| 556 |
+
For encoder/decoder models:
|
| 557 |
+
* ROCmFlashAttentionImpl.forward() may be invoked for both self- and
|
| 558 |
+
cross-attention layers.
|
| 559 |
+
* For self-attention: query, key and value must be non-None.
|
| 560 |
+
* For cross-attention:
|
| 561 |
+
* Query must be non-None
|
| 562 |
+
* During prefill, key and value must be non-None; key and value
|
| 563 |
+
get cached for use during decode.
|
| 564 |
+
* During decode, key and value may be None, since:
|
| 565 |
+
(1) key and value tensors were cached during prefill, and
|
| 566 |
+
(2) cross-attention key and value tensors do not grow during
|
| 567 |
+
decode
|
| 568 |
+
|
| 569 |
+
A note on how the attn_type (attention type enum) argument impacts
|
| 570 |
+
attention forward() behavior:
|
| 571 |
+
|
| 572 |
+
* DECODER: normal decoder-only behavior;
|
| 573 |
+
use decoder self-attention block table
|
| 574 |
+
* ENCODER: no KV caching; pass encoder sequence
|
| 575 |
+
attributes (encoder_seq_lens/encoder_seq_lens_tensor/
|
| 576 |
+
max_encoder_seq_len) to kernel, in lieu of decoder
|
| 577 |
+
sequence attributes (seq_lens/seq_lens_tensor/max_seq_len)
|
| 578 |
+
* ENCODER_DECODER: cross-attention behavior;
|
| 579 |
+
use cross-attention block table for caching KVs derived
|
| 580 |
+
from encoder hidden states; since KV sequence lengths
|
| 581 |
+
will match encoder sequence lengths, pass encoder sequence
|
| 582 |
+
attributes to kernel (encoder_seq_lens/encoder_seq_lens_tensor/
|
| 583 |
+
max_encoder_seq_len)
|
| 584 |
+
* ENCODER_ONLY: bidirectional attention with no KV caching;
|
| 585 |
+
use prefill sequence attributes
|
| 586 |
+
|
| 587 |
+
Args:
|
| 588 |
+
query: shape = [num_tokens, num_heads * head_size]
|
| 589 |
+
key: shape = [num_tokens, num_kv_heads * head_size]
|
| 590 |
+
value: shape = [num_tokens, num_kv_heads * head_size]
|
| 591 |
+
kv_cache = [2, num_blocks, block_size * num_kv_heads * head_size]
|
| 592 |
+
NOTE: kv_cache will be an empty tensor with shape [0]
|
| 593 |
+
for profiling run.
|
| 594 |
+
attn_metadata: Metadata for attention.
|
| 595 |
+
attn_type: Select attention type, between encoder attention,
|
| 596 |
+
decoder self-attention, or encoder/decoder cross-
|
| 597 |
+
attention. Defaults to decoder self-attention,
|
| 598 |
+
which is the vLLM default generally
|
| 599 |
+
Returns:
|
| 600 |
+
shape = [num_tokens, num_heads * head_size]
|
| 601 |
+
"""
|
| 602 |
+
assert output is not None, "Output tensor must be provided."
|
| 603 |
+
|
| 604 |
+
if output_scale is not None and not self.use_triton_flash_attn:
|
| 605 |
+
raise NotImplementedError(
|
| 606 |
+
"fused output quantization only supported for Triton"
|
| 607 |
+
" implementation in ROCMFlashAttentionImpl for now")
|
| 608 |
+
|
| 609 |
+
query = query.view(-1, self.num_heads, self.head_size)
|
| 610 |
+
if key is not None:
|
| 611 |
+
assert value is not None
|
| 612 |
+
key = key.view(-1, self.num_kv_heads, self.head_size)
|
| 613 |
+
value = value.view(-1, self.num_kv_heads, self.head_size)
|
| 614 |
+
else:
|
| 615 |
+
assert value is None
|
| 616 |
+
|
| 617 |
+
paged_attn = self.paged_attn_module
|
| 618 |
+
|
| 619 |
+
# Reshaping kv tensors is required for AITER paged attention kernel
|
| 620 |
+
# because it works on a different tensor shape,
|
| 621 |
+
# when the size of one element is one byte (int8/fp8 dtypes).
|
| 622 |
+
# This reshaping is only required on the first forward call
|
| 623 |
+
# and the kv cache must not be empty.
|
| 624 |
+
if (is_rocm_aiter_paged_attn_enabled() and kv_cache.dtype.itemsize == 1
|
| 625 |
+
and not self.aiter_kv_scales_initialized
|
| 626 |
+
and kv_cache.shape != torch.Size([0])):
|
| 627 |
+
num_blocks = kv_cache.shape[1]
|
| 628 |
+
block_size = kv_cache.shape[2] // (self.num_kv_heads *
|
| 629 |
+
self.head_size)
|
| 630 |
+
k_scale = torch.empty((self.num_kv_heads, num_blocks * block_size),
|
| 631 |
+
dtype=torch.float32,
|
| 632 |
+
device=kv_cache.device)
|
| 633 |
+
v_scale = torch.empty((self.num_kv_heads, num_blocks * block_size),
|
| 634 |
+
dtype=torch.float32,
|
| 635 |
+
device=kv_cache.device)
|
| 636 |
+
self.aiter_kv_scales_initialized = True
|
| 637 |
+
k_scale.fill_(layer._k_scale.item())
|
| 638 |
+
v_scale.fill_(layer._v_scale.item())
|
| 639 |
+
layer._k_scale = k_scale
|
| 640 |
+
layer._v_scale = v_scale
|
| 641 |
+
|
| 642 |
+
# Only update KV cache for decoder self-attention
|
| 643 |
+
# and encoder-decoder cross-attention
|
| 644 |
+
if self.attn_type not in [
|
| 645 |
+
AttentionType.ENCODER, AttentionType.ENCODER_ONLY
|
| 646 |
+
] and kv_cache.numel() > 0:
|
| 647 |
+
key_cache, value_cache = paged_attn.split_kv_cache(
|
| 648 |
+
kv_cache, self.num_kv_heads, self.head_size)
|
| 649 |
+
|
| 650 |
+
if key is not None and value is not None:
|
| 651 |
+
# Reshape the input keys and values and store them in the
|
| 652 |
+
# cache. If kv_cache is not provided, the new key and value
|
| 653 |
+
# tensors are not cached. This happens during the initial
|
| 654 |
+
# memory profiling run.
|
| 655 |
+
paged_attn.write_to_paged_cache(
|
| 656 |
+
key,
|
| 657 |
+
value,
|
| 658 |
+
key_cache,
|
| 659 |
+
value_cache,
|
| 660 |
+
attn_metadata.slot_mapping
|
| 661 |
+
if self.attn_type != AttentionType.ENCODER_DECODER else
|
| 662 |
+
attn_metadata.cross_slot_mapping,
|
| 663 |
+
self.kv_cache_dtype,
|
| 664 |
+
layer._k_scale,
|
| 665 |
+
layer._v_scale,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
if self.attn_type != AttentionType.ENCODER:
|
| 669 |
+
num_prefill_tokens = attn_metadata.num_prefill_tokens
|
| 670 |
+
elif self.attn_type == AttentionType.ENCODER_ONLY:
|
| 671 |
+
# For encoder-only models, all tokens are processed in one go
|
| 672 |
+
num_prefill_tokens = query.shape[0]
|
| 673 |
+
else:
|
| 674 |
+
assert attn_metadata.num_encoder_tokens is not None
|
| 675 |
+
num_prefill_tokens = attn_metadata.num_encoder_tokens
|
| 676 |
+
|
| 677 |
+
# Query for decode. KV is not needed because it is already cached.
|
| 678 |
+
decode_query = query[num_prefill_tokens:]
|
| 679 |
+
# QKV for prefill.
|
| 680 |
+
query = query[:num_prefill_tokens]
|
| 681 |
+
|
| 682 |
+
# For encoder-only and encoder models,
|
| 683 |
+
# we process all tokens at once
|
| 684 |
+
# For decoder and encoder-decoder,
|
| 685 |
+
# we may need to limit key/value to prefill tokens
|
| 686 |
+
if key is not None and value is not None \
|
| 687 |
+
and self.attn_type not in [AttentionType.ENCODER_DECODER,
|
| 688 |
+
AttentionType.ENCODER_ONLY]:
|
| 689 |
+
key = key[:num_prefill_tokens]
|
| 690 |
+
value = value[:num_prefill_tokens]
|
| 691 |
+
|
| 692 |
+
if prefill_meta := attn_metadata.prefill_metadata:
|
| 693 |
+
# Prompt run.
|
| 694 |
+
# normal attention and DECODER
|
| 695 |
+
if self.attn_type == AttentionType.DECODER and (
|
| 696 |
+
kv_cache.numel() == 0 or prefill_meta.block_tables is None
|
| 697 |
+
or prefill_meta.block_tables.numel() == 0):
|
| 698 |
+
(query_seq_start_loc, query_max_seq_len, key_seq_start_loc,
|
| 699 |
+
key_max_seq_len, seq_lens,
|
| 700 |
+
causal_mask) = (prefill_meta.seq_start_loc,
|
| 701 |
+
prefill_meta.max_prefill_seq_len,
|
| 702 |
+
prefill_meta.seq_start_loc,
|
| 703 |
+
prefill_meta.max_prefill_seq_len,
|
| 704 |
+
attn_metadata.seq_lens, True)
|
| 705 |
+
# prefix-enabled attention and ENCODER/ENCODER_DECODER
|
| 706 |
+
else:
|
| 707 |
+
(query_seq_start_loc, query_max_seq_len, key_seq_start_loc,
|
| 708 |
+
key_max_seq_len, seq_lens,
|
| 709 |
+
causal_mask) = _get_seq_len_block_table_args(
|
| 710 |
+
prefill_meta, self.attn_type)
|
| 711 |
+
# Prompt run.
|
| 712 |
+
if kv_cache.numel() == 0 or prefill_meta.block_tables.numel() == 0:
|
| 713 |
+
# triton attention
|
| 714 |
+
# When block_tables are not filled, it means q and k are the
|
| 715 |
+
# prompt, and they have the same length.
|
| 716 |
+
attn_masks = None
|
| 717 |
+
if self.use_triton_flash_attn:
|
| 718 |
+
if self.alibi_slopes is not None:
|
| 719 |
+
attn_masks = _make_alibi_bias(
|
| 720 |
+
self.alibi_slopes,
|
| 721 |
+
query.dtype,
|
| 722 |
+
seq_lens,
|
| 723 |
+
make_attn_mask=causal_mask) # type: ignore
|
| 724 |
+
|
| 725 |
+
use_fp8_scales = (layer._q_scale and layer._k_scale
|
| 726 |
+
and layer._v_scale and layer._prob_scale
|
| 727 |
+
and (self.kv_cache_dtype == "fp8"
|
| 728 |
+
or self.force_fp8_attention))
|
| 729 |
+
|
| 730 |
+
full_scales = (
|
| 731 |
+
layer._q_scale.item(), layer._k_scale.item(),
|
| 732 |
+
layer._v_scale.item(),
|
| 733 |
+
layer._prob_scale.item()) if use_fp8_scales else None
|
| 734 |
+
self.triton_attn_func(
|
| 735 |
+
query,
|
| 736 |
+
key,
|
| 737 |
+
value,
|
| 738 |
+
output[:num_prefill_tokens],
|
| 739 |
+
query_seq_start_loc,
|
| 740 |
+
key_seq_start_loc,
|
| 741 |
+
query_max_seq_len,
|
| 742 |
+
key_max_seq_len,
|
| 743 |
+
causal_mask,
|
| 744 |
+
self.scale,
|
| 745 |
+
attn_masks[0][None]
|
| 746 |
+
if attn_masks is not None else None,
|
| 747 |
+
full_scales,
|
| 748 |
+
output_scale,
|
| 749 |
+
)
|
| 750 |
+
elif self.use_naive_attn:
|
| 751 |
+
if self.num_kv_heads != self.num_heads:
|
| 752 |
+
# Interleave for MQA workaround.
|
| 753 |
+
key = self.repeat_kv(key, self.num_queries_per_kv)
|
| 754 |
+
value = self.repeat_kv(value, self.num_queries_per_kv)
|
| 755 |
+
if self.alibi_slopes is not None:
|
| 756 |
+
attn_masks = _make_alibi_bias(
|
| 757 |
+
self.alibi_slopes,
|
| 758 |
+
query.dtype,
|
| 759 |
+
attn_metadata.seq_lens,
|
| 760 |
+
make_attn_mask=causal_mask) # type: ignore
|
| 761 |
+
query = query.movedim(0, query.dim() - 2)
|
| 762 |
+
key = key.movedim(0, key.dim() - 2)
|
| 763 |
+
value = value.movedim(0, value.dim() - 2)
|
| 764 |
+
# sdpa math backend attention
|
| 765 |
+
self.sdpa_attn_func(
|
| 766 |
+
query,
|
| 767 |
+
key,
|
| 768 |
+
value,
|
| 769 |
+
output[:num_prefill_tokens],
|
| 770 |
+
query_seq_start_loc,
|
| 771 |
+
num_prefill_tokens,
|
| 772 |
+
self.num_heads,
|
| 773 |
+
self.head_size,
|
| 774 |
+
self.scale,
|
| 775 |
+
attn_masks,
|
| 776 |
+
)
|
| 777 |
+
else:
|
| 778 |
+
# upstream FA does not support an output arg, copy
|
| 779 |
+
output[:num_prefill_tokens] = self.fa_attn_func(
|
| 780 |
+
q=query,
|
| 781 |
+
k=key,
|
| 782 |
+
v=value,
|
| 783 |
+
cu_seqlens_q=query_seq_start_loc,
|
| 784 |
+
cu_seqlens_k=key_seq_start_loc,
|
| 785 |
+
max_seqlen_q=prefill_meta.max_prefill_seq_len,
|
| 786 |
+
max_seqlen_k=key_max_seq_len,
|
| 787 |
+
softmax_scale=self.scale,
|
| 788 |
+
causal=causal_mask,
|
| 789 |
+
window_size=self.sliding_window,
|
| 790 |
+
alibi_slopes=self.alibi_slopes,
|
| 791 |
+
softcap=self.logits_soft_cap,
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
else:
|
| 795 |
+
# prefix-enabled attention -
|
| 796 |
+
# not applicable for encoder-only models
|
| 797 |
+
if self.attn_type != AttentionType.ENCODER_ONLY:
|
| 798 |
+
output[:num_prefill_tokens] = paged_attn.forward_prefix(
|
| 799 |
+
query,
|
| 800 |
+
key,
|
| 801 |
+
value,
|
| 802 |
+
self.kv_cache_dtype,
|
| 803 |
+
key_cache,
|
| 804 |
+
value_cache,
|
| 805 |
+
prefill_meta.block_tables,
|
| 806 |
+
prefill_meta.query_start_loc,
|
| 807 |
+
prefill_meta.seq_lens_tensor,
|
| 808 |
+
prefill_meta.max_query_len,
|
| 809 |
+
self.alibi_slopes,
|
| 810 |
+
self.sliding_window[0],
|
| 811 |
+
layer._k_scale,
|
| 812 |
+
layer._v_scale,
|
| 813 |
+
)
|
| 814 |
+
# Skip decode phase for encoder-only models
|
| 815 |
+
if (decode_meta := attn_metadata.decode_metadata) and (
|
| 816 |
+
self.attn_type != AttentionType.ENCODER_ONLY):
|
| 817 |
+
# Decoding run.
|
| 818 |
+
# Whether to use rocm custom paged attention or not
|
| 819 |
+
num_seqs, num_heads, head_size = decode_query.shape
|
| 820 |
+
block_size = value_cache.shape[3]
|
| 821 |
+
gqa_ratio = num_heads // self.num_kv_heads
|
| 822 |
+
from vllm.platforms.rocm import use_rocm_custom_paged_attention
|
| 823 |
+
use_custom = use_rocm_custom_paged_attention(
|
| 824 |
+
decode_query.dtype, head_size, block_size, gqa_ratio,
|
| 825 |
+
decode_meta.max_decode_seq_len, self.sliding_window,
|
| 826 |
+
self.kv_cache_dtype, self.alibi_slopes)
|
| 827 |
+
|
| 828 |
+
if use_custom:
|
| 829 |
+
max_seq_len = (decode_meta.max_decode_seq_len if self.attn_type
|
| 830 |
+
!= AttentionType.ENCODER_DECODER else
|
| 831 |
+
decode_meta.max_encoder_seq_len)
|
| 832 |
+
assert max_seq_len is not None
|
| 833 |
+
max_num_partitions = (
|
| 834 |
+
(max_seq_len + _PARTITION_SIZE_ROCM - 1) //
|
| 835 |
+
_PARTITION_SIZE_ROCM)
|
| 836 |
+
assert _PARTITION_SIZE_ROCM % block_size == 0
|
| 837 |
+
tmp_output = torch.empty(
|
| 838 |
+
size=(num_seqs, num_heads, max_num_partitions, head_size),
|
| 839 |
+
dtype=query.dtype,
|
| 840 |
+
device=output.device,
|
| 841 |
+
)
|
| 842 |
+
exp_sums = torch.empty(
|
| 843 |
+
size=(num_seqs, num_heads, max_num_partitions),
|
| 844 |
+
dtype=torch.float32,
|
| 845 |
+
device=output.device,
|
| 846 |
+
)
|
| 847 |
+
max_logits = torch.empty_like(exp_sums)
|
| 848 |
+
|
| 849 |
+
query_start_loc = None
|
| 850 |
+
ops.paged_attention_rocm(
|
| 851 |
+
output[num_prefill_tokens:],
|
| 852 |
+
exp_sums,
|
| 853 |
+
max_logits,
|
| 854 |
+
tmp_output,
|
| 855 |
+
decode_query,
|
| 856 |
+
key_cache,
|
| 857 |
+
value_cache,
|
| 858 |
+
self.num_kv_heads,
|
| 859 |
+
self.scale,
|
| 860 |
+
decode_meta.block_tables
|
| 861 |
+
if self.attn_type != AttentionType.ENCODER_DECODER else
|
| 862 |
+
decode_meta.cross_block_tables,
|
| 863 |
+
decode_meta.seq_lens_tensor
|
| 864 |
+
if self.attn_type != AttentionType.ENCODER_DECODER else
|
| 865 |
+
decode_meta.encoder_seq_lens_tensor,
|
| 866 |
+
query_start_loc,
|
| 867 |
+
block_size,
|
| 868 |
+
max_seq_len,
|
| 869 |
+
self.alibi_slopes,
|
| 870 |
+
self.kv_cache_dtype,
|
| 871 |
+
layer._k_scale,
|
| 872 |
+
layer._v_scale,
|
| 873 |
+
output_scale,
|
| 874 |
+
)
|
| 875 |
+
else:
|
| 876 |
+
# PagedAttention does not support fused quant, manually quantize
|
| 877 |
+
if output_scale is None:
|
| 878 |
+
out_pa = output[num_prefill_tokens:]
|
| 879 |
+
else:
|
| 880 |
+
out_pa = torch.empty_like(output[num_prefill_tokens:],
|
| 881 |
+
dtype=query.dtype)
|
| 882 |
+
|
| 883 |
+
out_pa[:] = paged_attn.forward_decode(
|
| 884 |
+
decode_query,
|
| 885 |
+
key_cache,
|
| 886 |
+
value_cache,
|
| 887 |
+
decode_meta.block_tables
|
| 888 |
+
if self.attn_type != AttentionType.ENCODER_DECODER else
|
| 889 |
+
decode_meta.cross_block_tables,
|
| 890 |
+
decode_meta.seq_lens_tensor
|
| 891 |
+
if self.attn_type != AttentionType.ENCODER_DECODER else
|
| 892 |
+
decode_meta.encoder_seq_lens_tensor,
|
| 893 |
+
decode_meta.max_decode_seq_len
|
| 894 |
+
if self.attn_type != AttentionType.ENCODER_DECODER else
|
| 895 |
+
decode_meta.max_encoder_seq_len,
|
| 896 |
+
self.kv_cache_dtype,
|
| 897 |
+
self.num_kv_heads,
|
| 898 |
+
self.scale,
|
| 899 |
+
self.alibi_slopes,
|
| 900 |
+
layer._k_scale,
|
| 901 |
+
layer._v_scale,
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
# Manually perform quantization
|
| 905 |
+
if output_scale is not None:
|
| 906 |
+
out_uq = out_pa.view(-1, self.num_heads * self.head_size)
|
| 907 |
+
out_q = output.view(-1, self.num_heads * self.head_size)
|
| 908 |
+
ops.scaled_fp8_quant(out_uq,
|
| 909 |
+
output_scale,
|
| 910 |
+
output=out_q[num_prefill_tokens:])
|
| 911 |
+
|
| 912 |
+
# Reshape the output tensor.
|
| 913 |
+
return output.view(-1, self.num_heads * self.head_size)
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
def _sdpa_attention(
|
| 917 |
+
query: torch.Tensor,
|
| 918 |
+
key: torch.Tensor,
|
| 919 |
+
value: torch.Tensor,
|
| 920 |
+
output: torch.Tensor,
|
| 921 |
+
seq_lens: torch.Tensor,
|
| 922 |
+
num_tokens: int,
|
| 923 |
+
num_heads: int,
|
| 924 |
+
head_size: int,
|
| 925 |
+
scale: float,
|
| 926 |
+
attn_masks: Optional[List[torch.Tensor]] = None,
|
| 927 |
+
) -> torch.Tensor:
|
| 928 |
+
start = 0
|
| 929 |
+
assert output.shape == (num_tokens, num_heads, head_size)
|
| 930 |
+
assert output.dtype == query.dtype
|
| 931 |
+
assert output.device == query.device
|
| 932 |
+
|
| 933 |
+
for i, seq_len in enumerate(seq_lens):
|
| 934 |
+
end = start + seq_len
|
| 935 |
+
with torch.nn.attention.sdpa_kernel(
|
| 936 |
+
torch.nn.attention.SDPBackend.MATH):
|
| 937 |
+
sub_out = torch.nn.functional.scaled_dot_product_attention(
|
| 938 |
+
query[:, start:end, :],
|
| 939 |
+
key[:, start:end, :],
|
| 940 |
+
value[:, start:end, :],
|
| 941 |
+
dropout_p=0.0,
|
| 942 |
+
is_causal=attn_masks is None,
|
| 943 |
+
attn_mask=attn_masks[i] if attn_masks else None,
|
| 944 |
+
scale=scale).movedim(query.dim() - 2, 0)
|
| 945 |
+
output[start:end, :, :] = sub_out
|
| 946 |
+
start = end
|
| 947 |
+
|
| 948 |
+
return output
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/backends/utils.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
"""Attention backend utils"""
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from itertools import accumulate
|
| 8 |
+
from typing import (TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type,
|
| 9 |
+
TypeVar, Union)
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from vllm.attention import (AttentionMetadata, AttentionMetadataBuilder,
|
| 15 |
+
AttentionState)
|
| 16 |
+
from vllm.attention.backends.abstract import AttentionType
|
| 17 |
+
from vllm.config import ModelConfig
|
| 18 |
+
from vllm.logger import init_logger
|
| 19 |
+
from vllm.multimodal import MultiModalPlaceholderMap
|
| 20 |
+
from vllm.utils import async_tensor_h2d, make_tensor_with_pad
|
| 21 |
+
|
| 22 |
+
logger = init_logger(__name__)
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from vllm.worker.model_runner_base import ModelRunnerBase
|
| 26 |
+
|
| 27 |
+
# Error string(s) for encoder/decoder
|
| 28 |
+
# unsupported attention scenarios
|
| 29 |
+
STR_NOT_IMPL_ENC_DEC_ROCM_HIP = ("ROCm/HIP is not currently supported "
|
| 30 |
+
"with encoder/decoder models.")
|
| 31 |
+
|
| 32 |
+
PAD_SLOT_ID = -1
|
| 33 |
+
|
| 34 |
+
# Switch to numpy implementation of compute_slot_mapping
|
| 35 |
+
# if we have at least this many elements. Could be tuned further.
|
| 36 |
+
_COMPUTE_SLOT_MAPPING_NUMPY_NUMEL = 256
|
| 37 |
+
|
| 38 |
+
if TYPE_CHECKING:
|
| 39 |
+
from vllm.worker.model_runner import ModelInputForGPUBuilder
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def is_block_tables_empty(block_tables: Union[None, Dict]):
|
| 43 |
+
"""
|
| 44 |
+
Check if block_tables is None or a dictionary with all None values.
|
| 45 |
+
"""
|
| 46 |
+
if block_tables is None:
|
| 47 |
+
return True
|
| 48 |
+
return (isinstance(block_tables, dict)
|
| 49 |
+
and all(value is None for value in block_tables.values()))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def compute_slot_mapping_start_idx(is_prompt: bool, query_len: int,
|
| 53 |
+
context_len: int, sliding_window: int):
|
| 54 |
+
"""
|
| 55 |
+
Compute the start index of slot mapping.
|
| 56 |
+
"""
|
| 57 |
+
start_idx = 0
|
| 58 |
+
if is_prompt and sliding_window is not None:
|
| 59 |
+
start_idx = max(0, query_len - sliding_window)
|
| 60 |
+
return start_idx
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _compute_slot_mapping_python(slot_mapping: List[int],
|
| 64 |
+
block_table: List[int], range_start: int,
|
| 65 |
+
range_end: int, block_size: int):
|
| 66 |
+
for i in range(range_start, range_end):
|
| 67 |
+
block_number = block_table[i // block_size]
|
| 68 |
+
block_offset = i % block_size
|
| 69 |
+
slot = block_number * block_size + block_offset
|
| 70 |
+
slot_mapping.append(slot)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _compute_slot_mapping_numpy(slot_mapping: List[int],
|
| 74 |
+
block_table: List[int], range_start: int,
|
| 75 |
+
range_end: int, block_size: int):
|
| 76 |
+
block_table_array = np.array(block_table)
|
| 77 |
+
idx = np.arange(range_start, range_end)
|
| 78 |
+
block_offset = idx % block_size
|
| 79 |
+
idx //= block_size
|
| 80 |
+
seq_slot_mapping_array = block_table_array[idx]
|
| 81 |
+
seq_slot_mapping_array *= block_size
|
| 82 |
+
seq_slot_mapping_array += block_offset
|
| 83 |
+
slot_mapping.extend(seq_slot_mapping_array)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def compute_slot_mapping(is_profile_run: bool, slot_mapping: List[int],
|
| 87 |
+
seq_id: int, seq_len: int, context_len: int,
|
| 88 |
+
start_idx: int, block_size: int,
|
| 89 |
+
block_tables: Dict[int, List[int]]):
|
| 90 |
+
"""
|
| 91 |
+
Compute slot mapping.
|
| 92 |
+
"""
|
| 93 |
+
if is_profile_run:
|
| 94 |
+
# During memory profiling, the block tables are not
|
| 95 |
+
# initialized yet. In this case, we just use a dummy
|
| 96 |
+
# slot mapping.
|
| 97 |
+
# In embeddings, the block tables are {seq_id: None}.
|
| 98 |
+
slot_mapping.extend([PAD_SLOT_ID] * seq_len)
|
| 99 |
+
return
|
| 100 |
+
|
| 101 |
+
# Mask the [0, start_idx) tokens of the prompt with
|
| 102 |
+
# PAD_SLOT_ID, where start_idx is max(0, seq_len -
|
| 103 |
+
# sliding_window). For example, if the prompt len is 10,
|
| 104 |
+
# sliding window is 8, and block size is 4, the first two
|
| 105 |
+
# tokens are masked and the slot mapping will be
|
| 106 |
+
# [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
|
| 107 |
+
padding_mask_len = max(0, start_idx - context_len)
|
| 108 |
+
slot_mapping.extend([PAD_SLOT_ID] * padding_mask_len)
|
| 109 |
+
|
| 110 |
+
range_start = max(start_idx, context_len)
|
| 111 |
+
range_end = seq_len
|
| 112 |
+
numel = range_end - range_start
|
| 113 |
+
block_table = block_tables[seq_id]
|
| 114 |
+
|
| 115 |
+
# numpy implementation will be faster than python if we have
|
| 116 |
+
# many elements, otherwise it will be slower.
|
| 117 |
+
if numel < _COMPUTE_SLOT_MAPPING_NUMPY_NUMEL:
|
| 118 |
+
_compute_slot_mapping_python(slot_mapping, block_table, range_start,
|
| 119 |
+
range_end, block_size)
|
| 120 |
+
else:
|
| 121 |
+
_compute_slot_mapping_numpy(slot_mapping, block_table, range_start,
|
| 122 |
+
range_end, block_size)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
TAttentionMetadata = TypeVar("TAttentionMetadata", bound='AttentionMetadata')
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class CommonMetadataBuilder(AttentionMetadataBuilder[TAttentionMetadata]):
|
| 129 |
+
|
| 130 |
+
_metadata_cls: Type[TAttentionMetadata]
|
| 131 |
+
|
| 132 |
+
def __init__(self, input_builder: "ModelInputForGPUBuilder"):
|
| 133 |
+
self.input_builder = input_builder
|
| 134 |
+
self.runner = input_builder.runner
|
| 135 |
+
|
| 136 |
+
self.sliding_window = input_builder.sliding_window
|
| 137 |
+
self.block_size = input_builder.block_size
|
| 138 |
+
|
| 139 |
+
def prepare(self):
|
| 140 |
+
self.slot_mapping: List[int] = []
|
| 141 |
+
self.prefill_seq_lens: List[int] = []
|
| 142 |
+
self.context_lens: List[int] = []
|
| 143 |
+
self.block_tables: List[List[int]] = []
|
| 144 |
+
self.curr_seq_lens: List[int] = []
|
| 145 |
+
self.multimodal_placeholder_maps: Dict[
|
| 146 |
+
str,
|
| 147 |
+
MultiModalPlaceholderMap] = defaultdict(MultiModalPlaceholderMap)
|
| 148 |
+
self.num_prefills = 0
|
| 149 |
+
self.num_prefill_tokens = 0
|
| 150 |
+
self.num_decode_tokens = 0
|
| 151 |
+
|
| 152 |
+
def _add_seq_group(
|
| 153 |
+
self, inter_data: "ModelInputForGPUBuilder.InterDataForSeqGroup",
|
| 154 |
+
chunked_prefill_enabled: bool):
|
| 155 |
+
is_prompt = inter_data.is_prompt
|
| 156 |
+
block_tables = inter_data.block_tables
|
| 157 |
+
|
| 158 |
+
for (seq_id, token_len, seq_len, curr_seq_len, query_len, context_len,
|
| 159 |
+
curr_sliding_window_block) in zip(
|
| 160 |
+
inter_data.seq_ids, [len(t) for t in inter_data.input_tokens],
|
| 161 |
+
inter_data.orig_seq_lens, inter_data.seq_lens,
|
| 162 |
+
inter_data.query_lens, inter_data.context_lens,
|
| 163 |
+
inter_data.curr_sliding_window_blocks):
|
| 164 |
+
self.context_lens.append(context_len)
|
| 165 |
+
if is_prompt:
|
| 166 |
+
mm_maps = inter_data.multi_modal_placeholder_maps
|
| 167 |
+
if mm_maps:
|
| 168 |
+
for modality, placeholders in mm_maps.items():
|
| 169 |
+
self.multimodal_placeholder_maps[modality].extend(
|
| 170 |
+
placeholders)
|
| 171 |
+
|
| 172 |
+
self.num_prefills += 1
|
| 173 |
+
self.num_prefill_tokens += token_len
|
| 174 |
+
self.prefill_seq_lens.append(seq_len)
|
| 175 |
+
else:
|
| 176 |
+
assert query_len == 1, (
|
| 177 |
+
"seq_len: {}, context_len: {}, query_len: {}".format(
|
| 178 |
+
seq_len, context_len, query_len))
|
| 179 |
+
self.num_decode_tokens += query_len
|
| 180 |
+
self.curr_seq_lens.append(curr_seq_len)
|
| 181 |
+
|
| 182 |
+
# Compute block table.
|
| 183 |
+
# TODO(sang): Combine chunked prefill and prefix caching by
|
| 184 |
+
# only allowing multiple of block_size chunk size.
|
| 185 |
+
# NOTE: This only works for oooooooxxx style attention.
|
| 186 |
+
block_table = []
|
| 187 |
+
if inter_data.prefix_cache_hit:
|
| 188 |
+
block_table = block_tables[seq_id]
|
| 189 |
+
elif ((chunked_prefill_enabled or not is_prompt)
|
| 190 |
+
and block_tables is not None):
|
| 191 |
+
if curr_sliding_window_block == 0:
|
| 192 |
+
block_table = block_tables[seq_id]
|
| 193 |
+
else:
|
| 194 |
+
block_table = block_tables[seq_id][
|
| 195 |
+
-curr_sliding_window_block:]
|
| 196 |
+
self.block_tables.append(block_table)
|
| 197 |
+
|
| 198 |
+
# Compute slot mapping.
|
| 199 |
+
is_profile_run = is_block_tables_empty(block_tables)
|
| 200 |
+
start_idx = compute_slot_mapping_start_idx(is_prompt, query_len,
|
| 201 |
+
context_len,
|
| 202 |
+
self.sliding_window)
|
| 203 |
+
compute_slot_mapping(is_profile_run, self.slot_mapping, seq_id,
|
| 204 |
+
seq_len, context_len, start_idx,
|
| 205 |
+
self.block_size, inter_data.block_tables)
|
| 206 |
+
|
| 207 |
+
def build(self, seq_lens: List[int], query_lens: List[int],
|
| 208 |
+
cuda_graph_pad_size: int, batch_size: int):
|
| 209 |
+
"""Build attention metadata with on-device tensors.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
seq_lens: The maybe padded sequence lengths of the input sequences.
|
| 213 |
+
query_lens: The query lengths of the input sequences.
|
| 214 |
+
cuda_graph_pad_size: The padding size for cuda graph.
|
| 215 |
+
-1 if cuda graph is not used.
|
| 216 |
+
batch_size: The maybe padded batch size.
|
| 217 |
+
"""
|
| 218 |
+
for inter_data in self.input_builder.inter_data_list:
|
| 219 |
+
self._add_seq_group(inter_data,
|
| 220 |
+
self.input_builder.chunked_prefill_enabled)
|
| 221 |
+
|
| 222 |
+
device = self.runner.device
|
| 223 |
+
use_captured_graph = cuda_graph_pad_size != -1
|
| 224 |
+
|
| 225 |
+
max_query_len = max(query_lens)
|
| 226 |
+
max_prefill_seq_len = max(self.prefill_seq_lens, default=0)
|
| 227 |
+
max_decode_seq_len = max(self.curr_seq_lens, default=0)
|
| 228 |
+
num_decode_tokens = self.num_decode_tokens
|
| 229 |
+
query_start_loc = list(accumulate(query_lens, initial=0))
|
| 230 |
+
seq_start_loc = list(accumulate(seq_lens, initial=0))
|
| 231 |
+
|
| 232 |
+
if use_captured_graph:
|
| 233 |
+
self.slot_mapping.extend([PAD_SLOT_ID] * cuda_graph_pad_size)
|
| 234 |
+
self.block_tables.extend([] * cuda_graph_pad_size)
|
| 235 |
+
num_decode_tokens = batch_size
|
| 236 |
+
|
| 237 |
+
# The shape of graph_block_tables is
|
| 238 |
+
# [max batch size, max context len // block size].
|
| 239 |
+
input_block_tables = self.runner.graph_block_tables[:batch_size]
|
| 240 |
+
for i, block_table in enumerate(self.block_tables):
|
| 241 |
+
if block_table:
|
| 242 |
+
input_block_tables[i, :len(block_table)] = block_table
|
| 243 |
+
block_tables = torch.from_numpy(input_block_tables).to(
|
| 244 |
+
device, non_blocking=True)
|
| 245 |
+
else:
|
| 246 |
+
block_tables = make_tensor_with_pad(
|
| 247 |
+
self.block_tables,
|
| 248 |
+
pad=0,
|
| 249 |
+
dtype=torch.int,
|
| 250 |
+
device=device,
|
| 251 |
+
)
|
| 252 |
+
assert max_query_len > 0, "query_lens: {}".format(query_lens)
|
| 253 |
+
|
| 254 |
+
assert device is not None
|
| 255 |
+
context_lens_tensor = async_tensor_h2d(self.context_lens, torch.int,
|
| 256 |
+
device, self.runner.pin_memory)
|
| 257 |
+
seq_lens_tensor = async_tensor_h2d(seq_lens, torch.int, device,
|
| 258 |
+
self.runner.pin_memory)
|
| 259 |
+
slot_mapping_tensor = async_tensor_h2d(self.slot_mapping, torch.long,
|
| 260 |
+
device, self.runner.pin_memory)
|
| 261 |
+
query_start_loc_tensor = async_tensor_h2d(query_start_loc, torch.int32,
|
| 262 |
+
device,
|
| 263 |
+
self.runner.pin_memory)
|
| 264 |
+
seq_start_loc_tensor = async_tensor_h2d(seq_start_loc, torch.int32,
|
| 265 |
+
device, self.runner.pin_memory)
|
| 266 |
+
placeholder_index_maps = {
|
| 267 |
+
modality: placeholder_map.index_map()
|
| 268 |
+
for modality, placeholder_map in
|
| 269 |
+
self.multimodal_placeholder_maps.items()
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
return self._metadata_cls( # type: ignore
|
| 273 |
+
num_prefills=self.num_prefills,
|
| 274 |
+
slot_mapping=slot_mapping_tensor,
|
| 275 |
+
multi_modal_placeholder_index_maps=placeholder_index_maps,
|
| 276 |
+
enable_kv_scales_calculation=True,
|
| 277 |
+
num_prefill_tokens=self.num_prefill_tokens,
|
| 278 |
+
num_decode_tokens=num_decode_tokens,
|
| 279 |
+
seq_lens=seq_lens,
|
| 280 |
+
seq_lens_tensor=seq_lens_tensor,
|
| 281 |
+
max_query_len=max_query_len,
|
| 282 |
+
max_prefill_seq_len=max_prefill_seq_len,
|
| 283 |
+
max_decode_seq_len=max_decode_seq_len,
|
| 284 |
+
query_start_loc=query_start_loc_tensor,
|
| 285 |
+
seq_start_loc=seq_start_loc_tensor,
|
| 286 |
+
context_lens_tensor=context_lens_tensor,
|
| 287 |
+
block_tables=block_tables,
|
| 288 |
+
use_cuda_graph=use_captured_graph,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class CommonAttentionState(AttentionState):
|
| 293 |
+
|
| 294 |
+
def __init__(self, runner: "ModelRunnerBase"):
|
| 295 |
+
self.runner = runner
|
| 296 |
+
self._is_graph_capturing = False
|
| 297 |
+
|
| 298 |
+
@contextmanager
|
| 299 |
+
def graph_capture(self, max_batch_size: int):
|
| 300 |
+
|
| 301 |
+
self._is_graph_capturing = True
|
| 302 |
+
|
| 303 |
+
self._graph_slot_mapping = torch.full((max_batch_size, ),
|
| 304 |
+
PAD_SLOT_ID,
|
| 305 |
+
dtype=torch.long,
|
| 306 |
+
device=self.runner.device)
|
| 307 |
+
self._graph_seq_lens = torch.ones(max_batch_size,
|
| 308 |
+
dtype=torch.int32,
|
| 309 |
+
device=self.runner.device)
|
| 310 |
+
self._graph_block_tables = torch.from_numpy(
|
| 311 |
+
self.runner.graph_block_tables).to(device=self.runner.device)
|
| 312 |
+
|
| 313 |
+
yield
|
| 314 |
+
|
| 315 |
+
self._is_graph_capturing = False
|
| 316 |
+
del self._graph_slot_mapping
|
| 317 |
+
del self._graph_seq_lens
|
| 318 |
+
del self._graph_block_tables
|
| 319 |
+
|
| 320 |
+
def graph_clone(self, batch_size: int) -> "CommonAttentionState":
|
| 321 |
+
assert self._is_graph_capturing
|
| 322 |
+
return self.__class__(self.runner)
|
| 323 |
+
|
| 324 |
+
def graph_capture_get_metadata_for_batch(
|
| 325 |
+
self, batch_size: int, is_encoder_decoder_model: bool = False):
|
| 326 |
+
assert self._is_graph_capturing
|
| 327 |
+
attn_metadata = self.runner.attn_backend.make_metadata(
|
| 328 |
+
num_prefills=0,
|
| 329 |
+
num_prefill_tokens=0,
|
| 330 |
+
num_decode_tokens=batch_size,
|
| 331 |
+
slot_mapping=self._graph_slot_mapping[:batch_size],
|
| 332 |
+
multi_modal_placeholder_index_maps=None,
|
| 333 |
+
enable_kv_scales_calculation=True,
|
| 334 |
+
seq_lens=None,
|
| 335 |
+
seq_lens_tensor=self._graph_seq_lens[:batch_size],
|
| 336 |
+
max_query_len=1,
|
| 337 |
+
max_decode_query_len=1,
|
| 338 |
+
max_prefill_seq_len=0,
|
| 339 |
+
max_decode_seq_len=self.runner.max_seq_len_to_capture,
|
| 340 |
+
query_start_loc=None,
|
| 341 |
+
seq_start_loc=None,
|
| 342 |
+
context_lens_tensor=None,
|
| 343 |
+
block_tables=self._graph_block_tables[:batch_size],
|
| 344 |
+
use_cuda_graph=True,
|
| 345 |
+
)
|
| 346 |
+
if is_encoder_decoder_model:
|
| 347 |
+
# The encoder decoder model works only with XFormers and
|
| 348 |
+
# Flash Attention backend. Assert the same.
|
| 349 |
+
assert self.runner.attn_backend.get_name() in \
|
| 350 |
+
["XFORMERS", "FLASH_ATTN", "ROCM_FLASH"], \
|
| 351 |
+
f"Expected attn_backend name to be either 'XFORMERS'," \
|
| 352 |
+
f"'ROCM_FLASH', or 'FLASH_ATTN', but " \
|
| 353 |
+
f"got '{self.runner.attn_backend.get_name()}'"
|
| 354 |
+
self._update_captured_metadata_for_enc_dec_model(
|
| 355 |
+
batch_size=batch_size, attn_metadata=attn_metadata)
|
| 356 |
+
|
| 357 |
+
return attn_metadata
|
| 358 |
+
|
| 359 |
+
def get_graph_input_buffers(
|
| 360 |
+
self,
|
| 361 |
+
attn_metadata,
|
| 362 |
+
is_encoder_decoder_model: bool = False) -> Dict[str, Any]:
|
| 363 |
+
input_buffers = {
|
| 364 |
+
"slot_mapping": attn_metadata.slot_mapping,
|
| 365 |
+
"seq_lens_tensor": attn_metadata.decode_metadata.seq_lens_tensor,
|
| 366 |
+
"block_tables": attn_metadata.decode_metadata.block_tables,
|
| 367 |
+
}
|
| 368 |
+
if is_encoder_decoder_model:
|
| 369 |
+
# The encoder decoder model works only with XFormers and
|
| 370 |
+
# Flash Attention backend. Assert the same.
|
| 371 |
+
assert self.runner.attn_backend.get_name() in \
|
| 372 |
+
["XFORMERS", "FLASH_ATTN", "ROCM_FLASH"], \
|
| 373 |
+
f"Expected attn_backend name to be either 'XFORMERS'," \
|
| 374 |
+
f"'ROCM_FLASH', or 'FLASH_ATTN', but " \
|
| 375 |
+
f"got '{self.runner.attn_backend.get_name()}'"
|
| 376 |
+
self._add_additional_input_buffers_for_enc_dec_model(
|
| 377 |
+
attn_metadata=attn_metadata, input_buffers=input_buffers)
|
| 378 |
+
return input_buffers
|
| 379 |
+
|
| 380 |
+
def prepare_graph_input_buffers(
|
| 381 |
+
self,
|
| 382 |
+
input_buffers,
|
| 383 |
+
attn_metadata,
|
| 384 |
+
is_encoder_decoder_model: bool = False) -> None:
|
| 385 |
+
input_buffers["seq_lens_tensor"].copy_(
|
| 386 |
+
attn_metadata.decode_metadata.seq_lens_tensor, non_blocking=True)
|
| 387 |
+
input_buffers["block_tables"].copy_(
|
| 388 |
+
attn_metadata.decode_metadata.block_tables, non_blocking=True)
|
| 389 |
+
if is_encoder_decoder_model:
|
| 390 |
+
# The encoder decoder model works only with XFormers and
|
| 391 |
+
# Flash Attention backend. Assert the same.
|
| 392 |
+
assert self.runner.attn_backend.get_name() in\
|
| 393 |
+
["XFORMERS", "FLASH_ATTN"], \
|
| 394 |
+
f"Expected attn_backend name to be either 'XFORMERS' or "\
|
| 395 |
+
f"'FLASH_ATTN', but "\
|
| 396 |
+
f"got '{self.runner.attn_backend.get_name()}'"
|
| 397 |
+
self._prepare_input_buffers_for_enc_dec_model(
|
| 398 |
+
attn_metadata, input_buffers)
|
| 399 |
+
|
| 400 |
+
def begin_forward(self, model_input) -> None:
|
| 401 |
+
return
|
| 402 |
+
|
| 403 |
+
def _update_captured_metadata_for_enc_dec_model(self, batch_size: int,
|
| 404 |
+
attn_metadata):
|
| 405 |
+
"""
|
| 406 |
+
Updates the attention metadata parameters for CUDA graph capture in an
|
| 407 |
+
encoder-decoder model.
|
| 408 |
+
|
| 409 |
+
This method modifies attention-related tensors and metadata required
|
| 410 |
+
for CUDA graph capture in encoder-decoder models. Specifically, it
|
| 411 |
+
updates the cross-attention and encoder sequence tensors in the
|
| 412 |
+
AttentionMetadata object.
|
| 413 |
+
"""
|
| 414 |
+
# During decode phase the cross_slot_mapping will be empty. Hence set
|
| 415 |
+
# an empty tensor for CUDA Graph capture.
|
| 416 |
+
attn_metadata.cross_slot_mapping = torch.tensor(
|
| 417 |
+
[], dtype=torch.int).cuda()
|
| 418 |
+
attn_metadata.cross_block_tables = torch.full(
|
| 419 |
+
(batch_size, self.runner.get_max_block_per_batch()),
|
| 420 |
+
1,
|
| 421 |
+
dtype=torch.int).cuda()
|
| 422 |
+
attn_metadata.encoder_seq_lens = torch.full((batch_size, ),
|
| 423 |
+
1,
|
| 424 |
+
dtype=torch.int).cuda()
|
| 425 |
+
attn_metadata.encoder_seq_lens_tensor = torch.full(
|
| 426 |
+
(batch_size, ), 1, dtype=torch.int).cuda()
|
| 427 |
+
attn_metadata.max_encoder_seq_len = self.runner.max_seq_len_to_capture
|
| 428 |
+
attn_metadata.num_encoder_tokens = 0
|
| 429 |
+
|
| 430 |
+
def _add_additional_input_buffers_for_enc_dec_model(
|
| 431 |
+
self, attn_metadata, input_buffers: Dict[str, Any]):
|
| 432 |
+
"""
|
| 433 |
+
Saves additional input buffers specific to the encoder-decoder model
|
| 434 |
+
from the attention metadata.
|
| 435 |
+
|
| 436 |
+
This method extracts and stores encoder-decoder related input buffers
|
| 437 |
+
from the `attn_metadata` into the `input_buffers` dictionary. The
|
| 438 |
+
buffers include encoder sequence lengths, cross-slot mappings, and
|
| 439 |
+
cross-block tables, which are essential for the encoder-decoder model
|
| 440 |
+
during CUDA graph replay.
|
| 441 |
+
"""
|
| 442 |
+
input_buffers["encoder_seq_lens_tensor"] = (
|
| 443 |
+
attn_metadata.decode_metadata.encoder_seq_lens_tensor)
|
| 444 |
+
input_buffers["cross_slot_mapping"] = (
|
| 445 |
+
attn_metadata.decode_metadata.cross_slot_mapping)
|
| 446 |
+
input_buffers["cross_block_tables"] = (
|
| 447 |
+
attn_metadata.decode_metadata.cross_block_tables)
|
| 448 |
+
|
| 449 |
+
def _prepare_input_buffers_for_enc_dec_model(self, attn_metadata,
|
| 450 |
+
input_buffers: Dict[str,
|
| 451 |
+
Any]):
|
| 452 |
+
"""
|
| 453 |
+
Populates input buffers with data from the encoder-decoder model's
|
| 454 |
+
attention metadata.
|
| 455 |
+
|
| 456 |
+
This method fills the input buffers with encoder-decoder specific
|
| 457 |
+
tensors. It copies data from the `attn_metadata` and keyword arguments
|
| 458 |
+
(`kwargs`) into corresponding buffers in the `input_buffers` dictionary.
|
| 459 |
+
The copied data includes attention-related metadata as well as input
|
| 460 |
+
IDs and positional information for the encoder.
|
| 461 |
+
"""
|
| 462 |
+
input_buffers["encoder_seq_lens_tensor"].copy_(
|
| 463 |
+
attn_metadata.decode_metadata.encoder_seq_lens_tensor,
|
| 464 |
+
non_blocking=True)
|
| 465 |
+
input_buffers["cross_slot_mapping"].copy_(
|
| 466 |
+
attn_metadata.decode_metadata.cross_slot_mapping,
|
| 467 |
+
non_blocking=True)
|
| 468 |
+
input_buffers["cross_block_tables"].copy_(
|
| 469 |
+
attn_metadata.decode_metadata.cross_block_tables,
|
| 470 |
+
non_blocking=True)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def is_all_encoder_attn_metadata_set(attn_metadata):
|
| 474 |
+
'''
|
| 475 |
+
All attention metadata required for encoder attention is set.
|
| 476 |
+
'''
|
| 477 |
+
return ((attn_metadata.encoder_seq_lens is not None)
|
| 478 |
+
and (attn_metadata.encoder_seq_lens_tensor is not None)
|
| 479 |
+
and (attn_metadata.max_encoder_seq_len is not None))
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def is_all_cross_attn_metadata_set(attn_metadata):
|
| 483 |
+
'''
|
| 484 |
+
All attention metadata required for enc/dec cross-attention is set.
|
| 485 |
+
|
| 486 |
+
Superset of encoder attention required metadata.
|
| 487 |
+
'''
|
| 488 |
+
return (attn_metadata.is_all_encoder_attn_metadata_set
|
| 489 |
+
and (attn_metadata.cross_slot_mapping is not None)
|
| 490 |
+
and (attn_metadata.cross_block_tables is not None))
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def get_seq_len_block_table_args(
|
| 494 |
+
attn_metadata,
|
| 495 |
+
is_prompt: bool,
|
| 496 |
+
attn_type: str,
|
| 497 |
+
) -> tuple:
|
| 498 |
+
'''
|
| 499 |
+
The particular choice of sequence-length- and block-table-related
|
| 500 |
+
attributes which should be extracted from attn_metadata is dependent
|
| 501 |
+
on the type of attention operation.
|
| 502 |
+
|
| 503 |
+
Decoder attn -> select entirely decoder self-attention-related fields
|
| 504 |
+
Encoder/decoder cross-attn -> select encoder sequence lengths &
|
| 505 |
+
cross-attn block-tables fields
|
| 506 |
+
Encoder attn -> select encoder sequence lengths fields & no block tables
|
| 507 |
+
|
| 508 |
+
Arguments:
|
| 509 |
+
|
| 510 |
+
* attn_metadata: Attention metadata structure associated with attention op
|
| 511 |
+
* is_prompt: True if prefill, False otherwise
|
| 512 |
+
* attn_type: encoder attention, decoder self-attention,
|
| 513 |
+
encoder/decoder cross-attention
|
| 514 |
+
|
| 515 |
+
Returns:
|
| 516 |
+
|
| 517 |
+
* Appropriate sequence-lengths tensor
|
| 518 |
+
* Appropriate max sequence-length scalar
|
| 519 |
+
* Appropriate block tables (or None)
|
| 520 |
+
'''
|
| 521 |
+
|
| 522 |
+
if attn_type == AttentionType.DECODER:
|
| 523 |
+
# Decoder self-attention
|
| 524 |
+
# Choose max_seq_len based on whether we are in prompt_run
|
| 525 |
+
if is_prompt:
|
| 526 |
+
max_seq_len = attn_metadata.max_prefill_seq_len
|
| 527 |
+
else:
|
| 528 |
+
max_seq_len = attn_metadata.max_decode_seq_len
|
| 529 |
+
return (attn_metadata.seq_lens_tensor, max_seq_len,
|
| 530 |
+
attn_metadata.block_tables)
|
| 531 |
+
elif attn_type == AttentionType.ENCODER_DECODER:
|
| 532 |
+
# Enc/dec cross-attention KVs match encoder sequence length;
|
| 533 |
+
# cross-attention utilizes special "cross" block tables
|
| 534 |
+
return (attn_metadata.encoder_seq_lens_tensor,
|
| 535 |
+
attn_metadata.max_encoder_seq_len,
|
| 536 |
+
attn_metadata.cross_block_tables)
|
| 537 |
+
elif attn_type == AttentionType.ENCODER:
|
| 538 |
+
# No block tables associated with encoder attention
|
| 539 |
+
return (attn_metadata.encoder_seq_lens_tensor,
|
| 540 |
+
attn_metadata.max_encoder_seq_len, None)
|
| 541 |
+
else:
|
| 542 |
+
raise AttributeError(f"Invalid attention type {str(attn_type)}")
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def get_num_prefill_decode_query_kv_tokens(
|
| 546 |
+
attn_metadata,
|
| 547 |
+
attn_type: str,
|
| 548 |
+
) -> Tuple[int, int, int]:
|
| 549 |
+
"""
|
| 550 |
+
Calculate the number of prefill and decode tokens for query, key/value
|
| 551 |
+
based on the attention metadata and the specified attention type.
|
| 552 |
+
|
| 553 |
+
Args:
|
| 554 |
+
attn_metadata (AttentionMetadata): Attention Metadata object.
|
| 555 |
+
attn_type (AttentionType): The type of attention being used.
|
| 556 |
+
Returns:
|
| 557 |
+
Tuple[int, int, int]: A tuple containing three integers:
|
| 558 |
+
- The number of prefill query tokens.
|
| 559 |
+
- The number of prefill key/value tokens.
|
| 560 |
+
- The number of decode query tokens.
|
| 561 |
+
|
| 562 |
+
Raises:
|
| 563 |
+
AssertionError: If the number of encoder tokens in `attn_metadata`
|
| 564 |
+
is `None` when required for the calculations.
|
| 565 |
+
"""
|
| 566 |
+
num_prefill_query_tokens = 0
|
| 567 |
+
num_decode_query_tokens = 0
|
| 568 |
+
num_prefill_kv_tokens = 0
|
| 569 |
+
if attn_type == AttentionType.ENCODER:
|
| 570 |
+
# Encoder attention is only invoked during prefill phase.
|
| 571 |
+
# The same input servers a both query and key.
|
| 572 |
+
assert attn_metadata.num_encoder_tokens is not None
|
| 573 |
+
num_prefill_query_tokens = attn_metadata.num_encoder_tokens
|
| 574 |
+
num_prefill_kv_tokens = attn_metadata.num_encoder_tokens
|
| 575 |
+
num_decode_query_tokens = 0
|
| 576 |
+
elif attn_type == AttentionType.ENCODER_DECODER:
|
| 577 |
+
assert attn_metadata.num_encoder_tokens is not None
|
| 578 |
+
num_prefill_query_tokens = attn_metadata.num_prefill_tokens
|
| 579 |
+
# The key is the encoder/cross-attention.
|
| 580 |
+
num_prefill_kv_tokens = attn_metadata.num_encoder_tokens
|
| 581 |
+
num_decode_query_tokens = attn_metadata.num_decode_tokens
|
| 582 |
+
else: # attn_type == AttentionType.DECODER or
|
| 583 |
+
# attn_type == AttentionType.ENCODER_ONLY
|
| 584 |
+
num_prefill_query_tokens = attn_metadata.num_prefill_tokens
|
| 585 |
+
num_prefill_kv_tokens = attn_metadata.num_prefill_tokens
|
| 586 |
+
num_decode_query_tokens = attn_metadata.num_decode_tokens
|
| 587 |
+
|
| 588 |
+
return (num_prefill_query_tokens, num_prefill_kv_tokens,
|
| 589 |
+
num_decode_query_tokens)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
@dataclass
|
| 593 |
+
class MLADims:
|
| 594 |
+
q_lora_rank: Optional[int]
|
| 595 |
+
kv_lora_rank: int
|
| 596 |
+
qk_nope_head_dim: int
|
| 597 |
+
qk_rope_head_dim: int
|
| 598 |
+
v_head_dim: int
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def get_mla_dims(model_config: ModelConfig) -> MLADims:
|
| 602 |
+
hf_text_config = model_config.hf_text_config
|
| 603 |
+
|
| 604 |
+
return MLADims(
|
| 605 |
+
q_lora_rank=getattr(hf_text_config, "q_lora_rank", None),
|
| 606 |
+
kv_lora_rank=hf_text_config.kv_lora_rank,
|
| 607 |
+
qk_nope_head_dim=hf_text_config.qk_nope_head_dim,
|
| 608 |
+
qk_rope_head_dim=hf_text_config.qk_rope_head_dim,
|
| 609 |
+
v_head_dim=hf_text_config.v_head_dim,
|
| 610 |
+
)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/__init__.py
ADDED
|
File without changes
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (174 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/__pycache__/chunked_local_attention.cpython-312.pyc
ADDED
|
Binary file (3.21 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/layers/chunked_local_attention.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
import functools
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from vllm import envs
|
| 9 |
+
from vllm.attention.backends.abstract import AttentionBackend
|
| 10 |
+
from vllm.attention.selector import get_attn_backend
|
| 11 |
+
from vllm.config import CacheConfig, QuantizationConfig
|
| 12 |
+
from vllm.v1.attention.backends.utils import (
|
| 13 |
+
CommonAttentionMetadata, make_local_attention_virtual_batches,
|
| 14 |
+
subclass_attention_backend, subclass_attention_metadata_builder)
|
| 15 |
+
|
| 16 |
+
from ..layer import Attention
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@functools.lru_cache
|
| 20 |
+
def create_chunked_local_attention_backend(
|
| 21 |
+
underlying_attn_backend: AttentionBackend,
|
| 22 |
+
attention_chunk_size: int,
|
| 23 |
+
block_size: int,
|
| 24 |
+
) -> type[AttentionBackend]:
|
| 25 |
+
prefix = f"ChunkedLocalAttention_{attention_chunk_size}_{block_size}_"
|
| 26 |
+
|
| 27 |
+
def build_preprocess_fn(cm: CommonAttentionMetadata):
|
| 28 |
+
return make_local_attention_virtual_batches(attention_chunk_size, cm,
|
| 29 |
+
block_size)
|
| 30 |
+
|
| 31 |
+
# Dynamically create a new attention backend that wraps the
|
| 32 |
+
# underlying attention backend but applies
|
| 33 |
+
# `make_local_attention_virtual_batches` before calling `build(...)`
|
| 34 |
+
builder_cls = subclass_attention_metadata_builder(
|
| 35 |
+
name_prefix=prefix,
|
| 36 |
+
builder_cls=underlying_attn_backend.get_builder_cls(),
|
| 37 |
+
build_preprocess_fn=build_preprocess_fn)
|
| 38 |
+
attn_backend = subclass_attention_backend(
|
| 39 |
+
name_prefix=prefix,
|
| 40 |
+
attention_backend_cls=underlying_attn_backend,
|
| 41 |
+
builder_cls=builder_cls)
|
| 42 |
+
|
| 43 |
+
return attn_backend
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class ChunkedLocalAttention(Attention):
|
| 47 |
+
|
| 48 |
+
def __init__(self,
|
| 49 |
+
num_heads: int,
|
| 50 |
+
head_size: int,
|
| 51 |
+
scale: float,
|
| 52 |
+
attention_chunk_size: int,
|
| 53 |
+
num_kv_heads: Optional[int] = None,
|
| 54 |
+
alibi_slopes: Optional[List[float]] = None,
|
| 55 |
+
cache_config: Optional[CacheConfig] = None,
|
| 56 |
+
quant_config: Optional[QuantizationConfig] = None,
|
| 57 |
+
kv_sharing_target_layer_name: Optional[str] = None,
|
| 58 |
+
prefix: str = ""):
|
| 59 |
+
dtype = torch.get_default_dtype()
|
| 60 |
+
if cache_config is not None:
|
| 61 |
+
kv_cache_dtype = cache_config.cache_dtype
|
| 62 |
+
block_size = cache_config.block_size
|
| 63 |
+
else:
|
| 64 |
+
kv_cache_dtype = "auto"
|
| 65 |
+
block_size = 16
|
| 66 |
+
|
| 67 |
+
if envs.VLLM_USE_V1:
|
| 68 |
+
underlying_attn_backend = get_attn_backend(head_size, dtype,
|
| 69 |
+
kv_cache_dtype,
|
| 70 |
+
block_size)
|
| 71 |
+
|
| 72 |
+
attn_backend = create_chunked_local_attention_backend(
|
| 73 |
+
underlying_attn_backend, attention_chunk_size, block_size)
|
| 74 |
+
else:
|
| 75 |
+
# in v0 the local attention is handled inside the backends
|
| 76 |
+
attn_backend = None
|
| 77 |
+
|
| 78 |
+
super().__init__(
|
| 79 |
+
num_heads=num_heads,
|
| 80 |
+
head_size=head_size,
|
| 81 |
+
scale=scale,
|
| 82 |
+
num_kv_heads=num_kv_heads,
|
| 83 |
+
alibi_slopes=alibi_slopes,
|
| 84 |
+
cache_config=cache_config,
|
| 85 |
+
quant_config=quant_config,
|
| 86 |
+
prefix=prefix,
|
| 87 |
+
kv_sharing_target_layer_name=kv_sharing_target_layer_name,
|
| 88 |
+
attn_backend=attn_backend)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (171 Bytes). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/merge_attn_states.cpython-312.pyc
ADDED
|
Binary file (2.01 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/prefix_prefill.cpython-312.pyc
ADDED
|
Binary file (31.2 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/rocm_aiter_mla.cpython-312.pyc
ADDED
|
Binary file (4.04 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/triton_decode_attention.cpython-312.pyc
ADDED
|
Binary file (18.5 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/__pycache__/triton_merge_attn_states.cpython-312.pyc
ADDED
|
Binary file (3.4 kB). View file
|
|
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/chunked_prefill_paged_decode.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
# Authors:
|
| 5 |
+
# - Burkhard Ringlein <ngl@zurich.ibm.com>
|
| 6 |
+
# - Jan van Lunteren <jvl@zurich.ibm.com>
|
| 7 |
+
# - Chih-Chieh Yang <chih.chieh.yang@ibm.com>
|
| 8 |
+
# - Thomas Parnell <tpa@zurich.ibm.com>
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from vllm import _custom_ops as ops
|
| 13 |
+
from vllm.platforms import current_platform
|
| 14 |
+
from vllm.triton_utils import tl, triton
|
| 15 |
+
|
| 16 |
+
from .prefix_prefill import context_attention_fwd
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@triton.jit
|
| 20 |
+
def cdiv_fn(x, y):
|
| 21 |
+
return (x + y - 1) // y
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@triton.jit
|
| 25 |
+
def kernel_paged_attention_2d(
|
| 26 |
+
output_ptr, # [num_tokens, num_query_heads, head_size]
|
| 27 |
+
query_ptr, # [num_tokens, num_query_heads, head_size]
|
| 28 |
+
key_cache_ptr, # [num_blks, num_kv_heads, head_size // x, blk_size, x]
|
| 29 |
+
value_cache_ptr, # [num_blks, num_kv_heads, head_size, blk_size]
|
| 30 |
+
sink_ptr, # [num_query_heads]
|
| 31 |
+
block_tables_ptr, # [num_seqs, max_num_blocks_per_seq]
|
| 32 |
+
seq_lens_ptr, # [num_seqs]
|
| 33 |
+
alibi_slopes_ptr, # [num_query_heads]
|
| 34 |
+
scale, # float32
|
| 35 |
+
k_scale, # float32
|
| 36 |
+
v_scale, # float32
|
| 37 |
+
num_query_heads: tl.constexpr, # int
|
| 38 |
+
num_queries_per_kv: tl.constexpr, # int
|
| 39 |
+
num_queries_per_kv_padded: tl.constexpr, # int
|
| 40 |
+
block_table_stride: tl.int64, # int
|
| 41 |
+
query_stride_0: tl.int64, # int
|
| 42 |
+
query_stride_1: tl.int64, # int, should be equal to head_size
|
| 43 |
+
output_stride_0: tl.int64, # int
|
| 44 |
+
output_stride_1: tl.int64, # int, should be equal to head_size
|
| 45 |
+
BLOCK_SIZE: tl.constexpr, # int
|
| 46 |
+
HEAD_SIZE: tl.constexpr, # int
|
| 47 |
+
HEAD_SIZE_PADDED: tl.constexpr, # int, must be power of 2
|
| 48 |
+
USE_ALIBI_SLOPES: tl.constexpr, # bool
|
| 49 |
+
SLIDING_WINDOW: tl.constexpr, # int
|
| 50 |
+
x: tl.constexpr, # int
|
| 51 |
+
stride_k_cache_0: tl.int64, # int
|
| 52 |
+
stride_k_cache_1: tl.int64, # int
|
| 53 |
+
stride_k_cache_2: tl.int64, # int
|
| 54 |
+
stride_k_cache_3: tl.int64, # int
|
| 55 |
+
stride_k_cache_4: tl.int64, # int
|
| 56 |
+
stride_v_cache_0: tl.int64, # int
|
| 57 |
+
stride_v_cache_1: tl.int64, # int
|
| 58 |
+
stride_v_cache_2: tl.int64, # int
|
| 59 |
+
stride_v_cache_3: tl.int64, # int
|
| 60 |
+
filter_by_query_len: tl.constexpr, # bool
|
| 61 |
+
query_start_len_ptr, # [num_seqs+1]
|
| 62 |
+
USE_SINKS: tl.constexpr, # bool
|
| 63 |
+
):
|
| 64 |
+
seq_idx = tl.program_id(0)
|
| 65 |
+
kv_head_idx = tl.program_id(1)
|
| 66 |
+
|
| 67 |
+
if filter_by_query_len:
|
| 68 |
+
cur_batch_in_all_start_index = tl.load(query_start_len_ptr + seq_idx)
|
| 69 |
+
cur_batch_in_all_stop_index = tl.load(query_start_len_ptr + seq_idx +
|
| 70 |
+
1)
|
| 71 |
+
cur_batch_query_len = cur_batch_in_all_stop_index \
|
| 72 |
+
- cur_batch_in_all_start_index
|
| 73 |
+
if cur_batch_query_len > 1:
|
| 74 |
+
return
|
| 75 |
+
else:
|
| 76 |
+
cur_batch_in_all_start_index = seq_idx
|
| 77 |
+
|
| 78 |
+
query_head_idx = kv_head_idx * num_queries_per_kv + tl.arange(
|
| 79 |
+
0, num_queries_per_kv_padded)
|
| 80 |
+
|
| 81 |
+
query_offset = (cur_batch_in_all_start_index * query_stride_0 +
|
| 82 |
+
query_head_idx[:, None] * query_stride_1)
|
| 83 |
+
|
| 84 |
+
head_mask = query_head_idx < (kv_head_idx + 1) * num_queries_per_kv
|
| 85 |
+
head_mask = head_mask & (query_head_idx < num_query_heads)
|
| 86 |
+
|
| 87 |
+
dim_mask = tl.where(tl.arange(0, HEAD_SIZE_PADDED) < HEAD_SIZE, 1,
|
| 88 |
+
0).to(tl.int1)
|
| 89 |
+
|
| 90 |
+
# Q : (num_queries_per_kv, HEAD_SIZE,)
|
| 91 |
+
Q = tl.load(
|
| 92 |
+
query_ptr + query_offset + tl.arange(0, HEAD_SIZE_PADDED)[None, :],
|
| 93 |
+
mask=dim_mask[None, :] & head_mask[:, None],
|
| 94 |
+
other=0.0,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
block_table_offset = seq_idx * block_table_stride
|
| 98 |
+
|
| 99 |
+
if not USE_SINKS:
|
| 100 |
+
M = tl.full([num_queries_per_kv_padded],
|
| 101 |
+
float("-inf"),
|
| 102 |
+
dtype=tl.float32)
|
| 103 |
+
else:
|
| 104 |
+
M = tl.load(
|
| 105 |
+
sink_ptr + query_head_idx,
|
| 106 |
+
mask=head_mask,
|
| 107 |
+
other=float("-inf"),
|
| 108 |
+
).to(dtype=tl.float32)
|
| 109 |
+
|
| 110 |
+
L = tl.full([num_queries_per_kv_padded], 1.0, dtype=tl.float32)
|
| 111 |
+
acc = tl.zeros([num_queries_per_kv_padded, HEAD_SIZE_PADDED],
|
| 112 |
+
dtype=tl.float32)
|
| 113 |
+
|
| 114 |
+
# sequence len for this particular sequence
|
| 115 |
+
seq_len = tl.load(seq_lens_ptr + seq_idx)
|
| 116 |
+
|
| 117 |
+
# alibi slope for this head
|
| 118 |
+
if USE_ALIBI_SLOPES:
|
| 119 |
+
alibi_slope = tl.load(alibi_slopes_ptr + query_head_idx,
|
| 120 |
+
mask=head_mask,
|
| 121 |
+
other=0.0)
|
| 122 |
+
|
| 123 |
+
num_blocks = cdiv_fn(seq_len, BLOCK_SIZE)
|
| 124 |
+
|
| 125 |
+
# iterate through tiles
|
| 126 |
+
for j in range(0, num_blocks):
|
| 127 |
+
|
| 128 |
+
physical_block_idx = tl.load(block_tables_ptr + block_table_offset + j)
|
| 129 |
+
|
| 130 |
+
offs_n = tl.arange(0, BLOCK_SIZE)
|
| 131 |
+
offs_d = tl.arange(0, HEAD_SIZE_PADDED)
|
| 132 |
+
|
| 133 |
+
v_offset = (physical_block_idx * stride_v_cache_0 +
|
| 134 |
+
kv_head_idx * stride_v_cache_1 +
|
| 135 |
+
offs_d[None, :] * stride_v_cache_2 +
|
| 136 |
+
offs_n[:, None] * stride_v_cache_3)
|
| 137 |
+
|
| 138 |
+
k_offset = (physical_block_idx * stride_k_cache_0 +
|
| 139 |
+
kv_head_idx * stride_k_cache_1 +
|
| 140 |
+
(offs_d[:, None] // x) * stride_k_cache_2 +
|
| 141 |
+
offs_n[None, :] * stride_k_cache_3 +
|
| 142 |
+
(offs_d[:, None] % x) * stride_k_cache_4)
|
| 143 |
+
|
| 144 |
+
# K : (HEAD_SIZE, BLOCK_SIZE)
|
| 145 |
+
K_load = tl.load(key_cache_ptr + k_offset,
|
| 146 |
+
mask=dim_mask[:, None],
|
| 147 |
+
other=0.0)
|
| 148 |
+
|
| 149 |
+
if K_load.dtype.is_fp8():
|
| 150 |
+
K = (K_load.to(tl.float32) * tl.load(k_scale)).to(Q.dtype)
|
| 151 |
+
else:
|
| 152 |
+
K = K_load
|
| 153 |
+
|
| 154 |
+
# V : (BLOCK_SIZE, HEAD_SIZE)
|
| 155 |
+
V_load = tl.load(value_cache_ptr + v_offset,
|
| 156 |
+
mask=dim_mask[None, :],
|
| 157 |
+
other=0.0)
|
| 158 |
+
|
| 159 |
+
if V_load.dtype.is_fp8():
|
| 160 |
+
V = (V_load.to(tl.float32) * tl.load(v_scale)).to(Q.dtype)
|
| 161 |
+
else:
|
| 162 |
+
V = V_load
|
| 163 |
+
|
| 164 |
+
seq_offset = j * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
| 165 |
+
boundary = tl.full([BLOCK_SIZE], seq_len, dtype=tl.int32)
|
| 166 |
+
seq_mask = seq_offset[None, :] < boundary
|
| 167 |
+
|
| 168 |
+
# S : (num_queries_per_kv, BLOCK_SIZE,)
|
| 169 |
+
S = tl.where(head_mask[:, None] & seq_mask, 0.0,
|
| 170 |
+
float("-inf")).to(tl.float32)
|
| 171 |
+
S += scale * tl.dot(Q, K)
|
| 172 |
+
|
| 173 |
+
context_len = seq_len - 1
|
| 174 |
+
|
| 175 |
+
if SLIDING_WINDOW > 0:
|
| 176 |
+
S = tl.where((context_len - seq_offset) < SLIDING_WINDOW, S,
|
| 177 |
+
-10000)
|
| 178 |
+
|
| 179 |
+
if USE_ALIBI_SLOPES:
|
| 180 |
+
S += alibi_slope[:, None] * (seq_offset - context_len)
|
| 181 |
+
|
| 182 |
+
# compute running maximum
|
| 183 |
+
# m_j : (num_queries_per_kv,)
|
| 184 |
+
m_j = tl.maximum(M, tl.max(S, axis=1))
|
| 185 |
+
|
| 186 |
+
# P : (num_queries_per_kv, BLOCK_SIZE,)
|
| 187 |
+
P = tl.exp(S - m_j[:, None])
|
| 188 |
+
|
| 189 |
+
# l_j : (num_queries_per_kv,)
|
| 190 |
+
l_j = tl.sum(P, axis=1)
|
| 191 |
+
|
| 192 |
+
# alpha : (num_queries_per_kv, )
|
| 193 |
+
alpha = tl.exp(M - m_j)
|
| 194 |
+
|
| 195 |
+
# acc : (num_queries_per_kv, BLOCK_SIZE,)
|
| 196 |
+
acc = acc * alpha[:, None]
|
| 197 |
+
|
| 198 |
+
# update constants
|
| 199 |
+
L = L * alpha + l_j
|
| 200 |
+
M = m_j
|
| 201 |
+
|
| 202 |
+
# acc : (num_queries_per_kv, BLOCK_SIZE,)
|
| 203 |
+
acc += tl.dot(P.to(V.dtype), V)
|
| 204 |
+
|
| 205 |
+
# epilogue
|
| 206 |
+
acc = acc / L[:, None]
|
| 207 |
+
|
| 208 |
+
output_offset = (cur_batch_in_all_start_index * output_stride_0 +
|
| 209 |
+
query_head_idx * output_stride_1)
|
| 210 |
+
|
| 211 |
+
tl.store(
|
| 212 |
+
output_ptr + output_offset[:, None] +
|
| 213 |
+
tl.arange(0, HEAD_SIZE_PADDED)[None, :],
|
| 214 |
+
acc,
|
| 215 |
+
mask=dim_mask[None, :] & head_mask[:, None],
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def chunked_prefill_paged_decode(
|
| 220 |
+
query,
|
| 221 |
+
key,
|
| 222 |
+
value,
|
| 223 |
+
output,
|
| 224 |
+
kv_cache_dtype,
|
| 225 |
+
key_cache,
|
| 226 |
+
value_cache,
|
| 227 |
+
block_table,
|
| 228 |
+
query_start_loc,
|
| 229 |
+
seq_lens,
|
| 230 |
+
max_seq_len,
|
| 231 |
+
max_query_len,
|
| 232 |
+
k_scale,
|
| 233 |
+
v_scale,
|
| 234 |
+
alibi_slopes=None,
|
| 235 |
+
sliding_window=None,
|
| 236 |
+
sm_scale=None,
|
| 237 |
+
# Optional tensor for sinks
|
| 238 |
+
sinks=None,
|
| 239 |
+
):
|
| 240 |
+
|
| 241 |
+
if sm_scale is None:
|
| 242 |
+
sm_scale = 1.0 / (query.shape[1]**0.5)
|
| 243 |
+
|
| 244 |
+
use_alibi_slopes = alibi_slopes is not None
|
| 245 |
+
|
| 246 |
+
if sliding_window is None or sliding_window <= 0:
|
| 247 |
+
sliding_window = 0
|
| 248 |
+
|
| 249 |
+
if max_query_len > 1:
|
| 250 |
+
context_attention_fwd(
|
| 251 |
+
q=query,
|
| 252 |
+
k=key,
|
| 253 |
+
v=value,
|
| 254 |
+
o=output,
|
| 255 |
+
kv_cache_dtype=kv_cache_dtype,
|
| 256 |
+
k_cache=key_cache,
|
| 257 |
+
v_cache=value_cache,
|
| 258 |
+
b_loc=block_table,
|
| 259 |
+
b_start_loc=query_start_loc,
|
| 260 |
+
b_seq_len=seq_lens,
|
| 261 |
+
max_seq_len=max_seq_len,
|
| 262 |
+
max_input_len=max_query_len,
|
| 263 |
+
k_scale=k_scale,
|
| 264 |
+
v_scale=v_scale,
|
| 265 |
+
alibi_slopes=alibi_slopes,
|
| 266 |
+
sliding_window=sliding_window,
|
| 267 |
+
sm_scale=sm_scale,
|
| 268 |
+
skip_decode=True,
|
| 269 |
+
sinks=sinks,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
block_size = value_cache.shape[3]
|
| 273 |
+
num_seqs = len(seq_lens)
|
| 274 |
+
num_query_heads = query.shape[1]
|
| 275 |
+
num_kv_heads = key.shape[1]
|
| 276 |
+
num_queries_per_kv = query.shape[1] // key.shape[1]
|
| 277 |
+
head_size = query.shape[2]
|
| 278 |
+
|
| 279 |
+
# Conversion of FP8 Tensor from uint8 storage to
|
| 280 |
+
# appropriate torch.dtype for interpretation by Triton
|
| 281 |
+
if "fp8" in kv_cache_dtype:
|
| 282 |
+
assert key_cache.dtype in [torch.uint8, current_platform.fp8_dtype()]
|
| 283 |
+
assert value_cache.dtype in [torch.uint8, current_platform.fp8_dtype()]
|
| 284 |
+
|
| 285 |
+
if kv_cache_dtype in ("fp8", "fp8_e4m3"):
|
| 286 |
+
target_dtype = current_platform.fp8_dtype()
|
| 287 |
+
elif kv_cache_dtype == "fp8_e5m2":
|
| 288 |
+
target_dtype = torch.float8_e5m2
|
| 289 |
+
else:
|
| 290 |
+
raise ValueError("Unsupported FP8 dtype:", kv_cache_dtype)
|
| 291 |
+
|
| 292 |
+
key_cache = key_cache.view(target_dtype)
|
| 293 |
+
value_cache = value_cache.view(target_dtype)
|
| 294 |
+
|
| 295 |
+
num_queries_per_kv_padded = max(triton.next_power_of_2(num_queries_per_kv),
|
| 296 |
+
16)
|
| 297 |
+
|
| 298 |
+
from vllm.platforms.rocm import use_rocm_custom_paged_attention
|
| 299 |
+
use_custom = use_rocm_custom_paged_attention(
|
| 300 |
+
query.dtype,
|
| 301 |
+
head_size,
|
| 302 |
+
block_size,
|
| 303 |
+
num_queries_per_kv,
|
| 304 |
+
max_seq_len,
|
| 305 |
+
sliding_window,
|
| 306 |
+
kv_cache_dtype,
|
| 307 |
+
alibi_slopes,
|
| 308 |
+
sinks,
|
| 309 |
+
)
|
| 310 |
+
if use_custom:
|
| 311 |
+
_PARTITION_SIZE_ROCM = 256
|
| 312 |
+
max_num_partitions = ((max_seq_len + _PARTITION_SIZE_ROCM - 1) //
|
| 313 |
+
_PARTITION_SIZE_ROCM)
|
| 314 |
+
assert _PARTITION_SIZE_ROCM % block_size == 0
|
| 315 |
+
total_num_seq = block_table.shape[0]
|
| 316 |
+
tmp_output = torch.empty(
|
| 317 |
+
size=(total_num_seq, num_query_heads, max_num_partitions,
|
| 318 |
+
head_size),
|
| 319 |
+
dtype=output.dtype,
|
| 320 |
+
device=output.device,
|
| 321 |
+
)
|
| 322 |
+
exp_sums = torch.empty(
|
| 323 |
+
size=(total_num_seq, num_query_heads, max_num_partitions),
|
| 324 |
+
dtype=torch.float32,
|
| 325 |
+
device=output.device,
|
| 326 |
+
)
|
| 327 |
+
max_logits = torch.empty_like(exp_sums)
|
| 328 |
+
|
| 329 |
+
ops.paged_attention_rocm(
|
| 330 |
+
output,
|
| 331 |
+
exp_sums,
|
| 332 |
+
max_logits,
|
| 333 |
+
tmp_output,
|
| 334 |
+
query,
|
| 335 |
+
key_cache,
|
| 336 |
+
value_cache,
|
| 337 |
+
num_kv_heads,
|
| 338 |
+
scale=sm_scale,
|
| 339 |
+
block_tables=block_table,
|
| 340 |
+
seq_lens=seq_lens,
|
| 341 |
+
query_start_loc=query_start_loc,
|
| 342 |
+
block_size=block_size,
|
| 343 |
+
max_seq_len=max_seq_len,
|
| 344 |
+
alibi_slopes=alibi_slopes,
|
| 345 |
+
kv_cache_dtype=kv_cache_dtype,
|
| 346 |
+
k_scale=k_scale,
|
| 347 |
+
v_scale=v_scale,
|
| 348 |
+
)
|
| 349 |
+
else:
|
| 350 |
+
kernel_paged_attention_2d[(
|
| 351 |
+
num_seqs,
|
| 352 |
+
num_kv_heads,
|
| 353 |
+
)](
|
| 354 |
+
output_ptr=output,
|
| 355 |
+
query_ptr=query,
|
| 356 |
+
key_cache_ptr=key_cache,
|
| 357 |
+
value_cache_ptr=value_cache,
|
| 358 |
+
sink_ptr=sinks,
|
| 359 |
+
block_tables_ptr=block_table,
|
| 360 |
+
seq_lens_ptr=seq_lens,
|
| 361 |
+
alibi_slopes_ptr=alibi_slopes,
|
| 362 |
+
scale=sm_scale,
|
| 363 |
+
k_scale=k_scale,
|
| 364 |
+
v_scale=v_scale,
|
| 365 |
+
num_query_heads=num_query_heads,
|
| 366 |
+
num_queries_per_kv=num_queries_per_kv,
|
| 367 |
+
num_queries_per_kv_padded=num_queries_per_kv_padded,
|
| 368 |
+
block_table_stride=block_table.stride(0),
|
| 369 |
+
query_stride_0=query.stride(0),
|
| 370 |
+
query_stride_1=query.stride(1),
|
| 371 |
+
output_stride_0=output.stride(0),
|
| 372 |
+
output_stride_1=output.stride(1),
|
| 373 |
+
BLOCK_SIZE=block_size,
|
| 374 |
+
HEAD_SIZE=head_size,
|
| 375 |
+
HEAD_SIZE_PADDED=triton.next_power_of_2(head_size),
|
| 376 |
+
USE_ALIBI_SLOPES=use_alibi_slopes,
|
| 377 |
+
SLIDING_WINDOW=sliding_window,
|
| 378 |
+
x=key_cache.shape[4],
|
| 379 |
+
stride_k_cache_0=key_cache.stride(0),
|
| 380 |
+
stride_k_cache_1=key_cache.stride(1),
|
| 381 |
+
stride_k_cache_2=key_cache.stride(2),
|
| 382 |
+
stride_k_cache_3=key_cache.stride(3),
|
| 383 |
+
stride_k_cache_4=key_cache.stride(4),
|
| 384 |
+
stride_v_cache_0=value_cache.stride(0),
|
| 385 |
+
stride_v_cache_1=value_cache.stride(1),
|
| 386 |
+
stride_v_cache_2=value_cache.stride(2),
|
| 387 |
+
stride_v_cache_3=value_cache.stride(3),
|
| 388 |
+
filter_by_query_len=True,
|
| 389 |
+
query_start_len_ptr=query_start_loc,
|
| 390 |
+
USE_SINKS=sinks is not None,
|
| 391 |
+
)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/paged_attn.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from vllm import _custom_ops as ops
|
| 10 |
+
from vllm.triton_utils import HAS_TRITON
|
| 11 |
+
|
| 12 |
+
if HAS_TRITON:
|
| 13 |
+
from vllm.attention.ops.prefix_prefill import context_attention_fwd
|
| 14 |
+
|
| 15 |
+
# Should be the same as PARTITION_SIZE in `paged_attention_v2_launcher`.
|
| 16 |
+
_PARTITION_SIZE = 512
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class PagedAttentionMetadata:
|
| 21 |
+
"""Metadata for PagedAttention."""
|
| 22 |
+
# (batch_size,). The length of sequences (entire tokens seen so far) per
|
| 23 |
+
# sequence.
|
| 24 |
+
seq_lens_tensor: Optional[torch.Tensor]
|
| 25 |
+
# Maximum sequence length in the batch. 0 if it is prefill-only batch.
|
| 26 |
+
max_decode_seq_len: int
|
| 27 |
+
# (batch_size, max_blocks_per_seq).
|
| 28 |
+
# Block addresses per sequence. (Seq id -> list of physical block)
|
| 29 |
+
# E.g., [0, 1, 2] means tokens are stored in 0th, 1st, and 2nd blocks
|
| 30 |
+
# in the kv cache. Each block can contain up to block_size tokens.
|
| 31 |
+
# 2nd dimensions are padded up to max_blocks_per_seq if it is cuda-graph
|
| 32 |
+
# captured.
|
| 33 |
+
block_tables: Optional[torch.Tensor]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PagedAttention:
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def get_supported_head_sizes() -> List[int]:
|
| 40 |
+
return [32, 64, 80, 96, 112, 120, 128, 192, 256]
|
| 41 |
+
|
| 42 |
+
@staticmethod
|
| 43 |
+
def get_kv_cache_shape(
|
| 44 |
+
num_blocks: int,
|
| 45 |
+
block_size: int,
|
| 46 |
+
num_kv_heads: int,
|
| 47 |
+
head_size: int,
|
| 48 |
+
) -> Tuple[int, ...]:
|
| 49 |
+
return (2, num_blocks, block_size * num_kv_heads * head_size)
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def split_kv_cache(
|
| 53 |
+
kv_cache: torch.Tensor,
|
| 54 |
+
num_kv_heads: int,
|
| 55 |
+
head_size: int,
|
| 56 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 57 |
+
x = 16 // kv_cache.element_size()
|
| 58 |
+
num_blocks = kv_cache.shape[1]
|
| 59 |
+
|
| 60 |
+
key_cache = kv_cache[0]
|
| 61 |
+
key_cache = key_cache.view(num_blocks, num_kv_heads, head_size // x,
|
| 62 |
+
-1, x)
|
| 63 |
+
value_cache = kv_cache[1]
|
| 64 |
+
value_cache = value_cache.view(num_blocks, num_kv_heads, head_size, -1)
|
| 65 |
+
return key_cache, value_cache
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def write_to_paged_cache(
|
| 69 |
+
key: torch.Tensor,
|
| 70 |
+
value: torch.Tensor,
|
| 71 |
+
key_cache: torch.Tensor,
|
| 72 |
+
value_cache: torch.Tensor,
|
| 73 |
+
slot_mapping: torch.Tensor,
|
| 74 |
+
kv_cache_dtype: str,
|
| 75 |
+
k_scale: torch.Tensor,
|
| 76 |
+
v_scale: torch.Tensor,
|
| 77 |
+
) -> None:
|
| 78 |
+
ops.reshape_and_cache(
|
| 79 |
+
key,
|
| 80 |
+
value,
|
| 81 |
+
key_cache,
|
| 82 |
+
value_cache,
|
| 83 |
+
slot_mapping.flatten(),
|
| 84 |
+
kv_cache_dtype,
|
| 85 |
+
k_scale,
|
| 86 |
+
v_scale,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
@staticmethod
|
| 90 |
+
def forward_decode(
|
| 91 |
+
query: torch.Tensor,
|
| 92 |
+
key_cache: torch.Tensor,
|
| 93 |
+
value_cache: torch.Tensor,
|
| 94 |
+
block_tables: torch.Tensor,
|
| 95 |
+
seq_lens: torch.Tensor,
|
| 96 |
+
max_seq_len: int,
|
| 97 |
+
kv_cache_dtype: str,
|
| 98 |
+
num_kv_heads: int,
|
| 99 |
+
scale: float,
|
| 100 |
+
alibi_slopes: Optional[torch.Tensor],
|
| 101 |
+
k_scale: torch.Tensor,
|
| 102 |
+
v_scale: torch.Tensor,
|
| 103 |
+
tp_rank: int = 0,
|
| 104 |
+
blocksparse_local_blocks: int = 0,
|
| 105 |
+
blocksparse_vert_stride: int = 0,
|
| 106 |
+
blocksparse_block_size: int = 64,
|
| 107 |
+
blocksparse_head_sliding_step: int = 0,
|
| 108 |
+
) -> torch.Tensor:
|
| 109 |
+
if blocksparse_vert_stride is not None and blocksparse_vert_stride > 1:
|
| 110 |
+
# use blocksparse paged attention
|
| 111 |
+
block_size = value_cache.size(-1)
|
| 112 |
+
assert (blocksparse_block_size > 0 and
|
| 113 |
+
blocksparse_block_size % block_size == 0), \
|
| 114 |
+
(f"{blocksparse_block_size=} needs to be a multiple of"
|
| 115 |
+
f"{block_size=} used in block_tables.")
|
| 116 |
+
|
| 117 |
+
output = torch.empty_like(query)
|
| 118 |
+
block_size = value_cache.shape[3]
|
| 119 |
+
num_seqs, num_heads, head_size = query.shape
|
| 120 |
+
max_num_partitions = ((max_seq_len + _PARTITION_SIZE - 1) //
|
| 121 |
+
_PARTITION_SIZE)
|
| 122 |
+
# NOTE(woosuk): We use a simple heuristic to decide whether to use
|
| 123 |
+
# PagedAttention V1 or V2. If the number of partitions is 1, we use
|
| 124 |
+
# V1 to avoid the overhead of reduction. Also, if the number of
|
| 125 |
+
# sequences or heads is large, we use V1 since there is enough work
|
| 126 |
+
# to parallelize.
|
| 127 |
+
# TODO(woosuk): Tune this heuristic.
|
| 128 |
+
# For context len > 8192, use V2 kernel to avoid shared memory shortage.
|
| 129 |
+
use_v1 = (max_seq_len <= 8192
|
| 130 |
+
and (max_num_partitions == 1 or num_seqs * num_heads > 512))
|
| 131 |
+
|
| 132 |
+
if use_v1:
|
| 133 |
+
# Run PagedAttention V1.
|
| 134 |
+
ops.paged_attention_v1(
|
| 135 |
+
output,
|
| 136 |
+
query,
|
| 137 |
+
key_cache,
|
| 138 |
+
value_cache,
|
| 139 |
+
num_kv_heads,
|
| 140 |
+
scale,
|
| 141 |
+
block_tables,
|
| 142 |
+
seq_lens,
|
| 143 |
+
block_size,
|
| 144 |
+
max_seq_len,
|
| 145 |
+
alibi_slopes,
|
| 146 |
+
kv_cache_dtype,
|
| 147 |
+
k_scale,
|
| 148 |
+
v_scale,
|
| 149 |
+
tp_rank,
|
| 150 |
+
blocksparse_local_blocks,
|
| 151 |
+
blocksparse_vert_stride,
|
| 152 |
+
blocksparse_block_size,
|
| 153 |
+
blocksparse_head_sliding_step,
|
| 154 |
+
)
|
| 155 |
+
else:
|
| 156 |
+
# Run PagedAttention V2.
|
| 157 |
+
assert _PARTITION_SIZE % block_size == 0
|
| 158 |
+
tmp_output = torch.empty(
|
| 159 |
+
size=(num_seqs, num_heads, max_num_partitions, head_size),
|
| 160 |
+
dtype=output.dtype,
|
| 161 |
+
device=output.device,
|
| 162 |
+
)
|
| 163 |
+
exp_sums = torch.empty(
|
| 164 |
+
size=(num_seqs, num_heads, max_num_partitions),
|
| 165 |
+
dtype=torch.float32,
|
| 166 |
+
device=output.device,
|
| 167 |
+
)
|
| 168 |
+
max_logits = torch.empty_like(exp_sums)
|
| 169 |
+
ops.paged_attention_v2(
|
| 170 |
+
output,
|
| 171 |
+
exp_sums,
|
| 172 |
+
max_logits,
|
| 173 |
+
tmp_output,
|
| 174 |
+
query,
|
| 175 |
+
key_cache,
|
| 176 |
+
value_cache,
|
| 177 |
+
num_kv_heads,
|
| 178 |
+
scale,
|
| 179 |
+
block_tables,
|
| 180 |
+
seq_lens,
|
| 181 |
+
block_size,
|
| 182 |
+
max_seq_len,
|
| 183 |
+
alibi_slopes,
|
| 184 |
+
kv_cache_dtype,
|
| 185 |
+
k_scale,
|
| 186 |
+
v_scale,
|
| 187 |
+
tp_rank,
|
| 188 |
+
blocksparse_local_blocks,
|
| 189 |
+
blocksparse_vert_stride,
|
| 190 |
+
blocksparse_block_size,
|
| 191 |
+
blocksparse_head_sliding_step,
|
| 192 |
+
)
|
| 193 |
+
return output
|
| 194 |
+
|
| 195 |
+
@staticmethod
|
| 196 |
+
def forward_prefix(
|
| 197 |
+
query: torch.Tensor,
|
| 198 |
+
key: torch.Tensor,
|
| 199 |
+
value: torch.Tensor,
|
| 200 |
+
kv_cache_dtype: str,
|
| 201 |
+
key_cache: torch.Tensor,
|
| 202 |
+
value_cache: torch.Tensor,
|
| 203 |
+
block_tables: torch.Tensor,
|
| 204 |
+
query_start_loc: torch.Tensor,
|
| 205 |
+
seq_lens_tensor: torch.Tensor,
|
| 206 |
+
max_query_len: int,
|
| 207 |
+
alibi_slopes: Optional[torch.Tensor],
|
| 208 |
+
sliding_window: Optional[int],
|
| 209 |
+
k_scale: torch.Tensor,
|
| 210 |
+
v_scale: torch.Tensor,
|
| 211 |
+
) -> torch.Tensor:
|
| 212 |
+
output = torch.empty_like(query)
|
| 213 |
+
max_seq_len = None
|
| 214 |
+
context_attention_fwd(
|
| 215 |
+
query,
|
| 216 |
+
key,
|
| 217 |
+
value,
|
| 218 |
+
output,
|
| 219 |
+
kv_cache_dtype,
|
| 220 |
+
key_cache,
|
| 221 |
+
value_cache,
|
| 222 |
+
block_tables,
|
| 223 |
+
# query_start_loc is (batch_size + 1,)
|
| 224 |
+
query_start_loc,
|
| 225 |
+
seq_lens_tensor,
|
| 226 |
+
max_seq_len,
|
| 227 |
+
max_query_len,
|
| 228 |
+
k_scale,
|
| 229 |
+
v_scale,
|
| 230 |
+
alibi_slopes,
|
| 231 |
+
sliding_window,
|
| 232 |
+
)
|
| 233 |
+
return output
|
| 234 |
+
|
| 235 |
+
@staticmethod
|
| 236 |
+
def swap_blocks(
|
| 237 |
+
src_kv_cache: torch.Tensor,
|
| 238 |
+
dst_kv_cache: torch.Tensor,
|
| 239 |
+
src_to_dst: torch.Tensor,
|
| 240 |
+
) -> None:
|
| 241 |
+
src_key_cache = src_kv_cache[0]
|
| 242 |
+
dst_key_cache = dst_kv_cache[0]
|
| 243 |
+
ops.swap_blocks(src_key_cache, dst_key_cache, src_to_dst)
|
| 244 |
+
|
| 245 |
+
src_value_cache = src_kv_cache[1]
|
| 246 |
+
dst_value_cache = dst_kv_cache[1]
|
| 247 |
+
ops.swap_blocks(src_value_cache, dst_value_cache, src_to_dst)
|
| 248 |
+
|
| 249 |
+
@staticmethod
|
| 250 |
+
def copy_blocks(
|
| 251 |
+
kv_caches: List[torch.Tensor],
|
| 252 |
+
src_to_dists: torch.Tensor,
|
| 253 |
+
) -> None:
|
| 254 |
+
key_caches = [kv_cache[0] for kv_cache in kv_caches]
|
| 255 |
+
value_caches = [kv_cache[1] for kv_cache in kv_caches]
|
| 256 |
+
ops.copy_blocks(key_caches, value_caches, src_to_dists)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/pallas_kv_cache_update.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
import functools
|
| 5 |
+
|
| 6 |
+
import jax
|
| 7 |
+
from jax.experimental import pallas as pl
|
| 8 |
+
from jax.experimental.pallas import tpu as pltpu
|
| 9 |
+
|
| 10 |
+
from vllm.utils import cdiv
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _kv_cache_update_kernel(
|
| 14 |
+
# Prefetch
|
| 15 |
+
slices_ref, # [3, padded_num_slices], list of (kv_cache_start,
|
| 16 |
+
# new_kv_start, slice_len)
|
| 17 |
+
num_slices_ref, # [1]
|
| 18 |
+
# Input
|
| 19 |
+
new_kv_hbm_ref, # [num_tokens, num_combined_kv_heads, head_dim]
|
| 20 |
+
kv_cache_hbm_ref, # [total_num_pages * page_size, num_combined_kv_heads,
|
| 21 |
+
# head_dim]
|
| 22 |
+
# Output
|
| 23 |
+
_, # [total_num_pages * page_size, num_combined_kv_heads, head_dim]
|
| 24 |
+
# Scratch
|
| 25 |
+
scratch, # [num_slices_per_block, page_size, num_combined_kv_heads,
|
| 26 |
+
# head_dim]
|
| 27 |
+
sem,
|
| 28 |
+
):
|
| 29 |
+
async_copies = []
|
| 30 |
+
block_idx = pl.program_id(0)
|
| 31 |
+
num_slices_per_block = scratch.shape[0]
|
| 32 |
+
|
| 33 |
+
# Copy from new_kv_hbm_ref to scratch
|
| 34 |
+
for i in range(num_slices_per_block):
|
| 35 |
+
offset_i = i + block_idx * num_slices_per_block
|
| 36 |
+
new_kv_start = jax.lax.select(offset_i < num_slices_ref[0],
|
| 37 |
+
slices_ref[1, offset_i], 0)
|
| 38 |
+
length = jax.lax.select(offset_i < num_slices_ref[0],
|
| 39 |
+
slices_ref[2, offset_i], 0)
|
| 40 |
+
async_copy = pltpu.make_async_copy(
|
| 41 |
+
new_kv_hbm_ref.at[pl.ds(new_kv_start, length), ...],
|
| 42 |
+
scratch.at[i, pl.ds(0, length), ...],
|
| 43 |
+
sem,
|
| 44 |
+
)
|
| 45 |
+
async_copy.start()
|
| 46 |
+
async_copies.append(async_copy)
|
| 47 |
+
|
| 48 |
+
for async_copy in async_copies:
|
| 49 |
+
async_copy.wait()
|
| 50 |
+
|
| 51 |
+
# Copy from scratch to kv_cache_hbm_ref
|
| 52 |
+
async_copies.clear()
|
| 53 |
+
for i in range(num_slices_per_block):
|
| 54 |
+
offset_i = i + block_idx * num_slices_per_block
|
| 55 |
+
kv_cache_start = jax.lax.select(offset_i < num_slices_ref[0],
|
| 56 |
+
slices_ref[0, offset_i], 0)
|
| 57 |
+
length = jax.lax.select(offset_i < num_slices_ref[0],
|
| 58 |
+
slices_ref[2, offset_i], 0)
|
| 59 |
+
async_copy = pltpu.make_async_copy(
|
| 60 |
+
scratch.at[i, pl.ds(0, length), ...],
|
| 61 |
+
kv_cache_hbm_ref.at[pl.ds(kv_cache_start, length), ...],
|
| 62 |
+
sem,
|
| 63 |
+
)
|
| 64 |
+
async_copy.start()
|
| 65 |
+
async_copies.append(async_copy)
|
| 66 |
+
for async_copy in async_copies:
|
| 67 |
+
async_copy.wait()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@functools.partial(
|
| 71 |
+
jax.jit,
|
| 72 |
+
static_argnames=["page_size", "num_slices_per_block"],
|
| 73 |
+
)
|
| 74 |
+
def kv_cache_update(
|
| 75 |
+
new_kv: jax.Array, # [total_num_token, num_combined_kv_heads, head_dim]
|
| 76 |
+
slices: jax.
|
| 77 |
+
Array, # [3, slices], list of (kv_cache_start, new_kv_start, slice_len)
|
| 78 |
+
kv_cache: jax.
|
| 79 |
+
Array, # [total_num_pages * page_size, num_combined_kv_heads, head_dim]
|
| 80 |
+
num_kv_update_slices: jax.Array, # [1]
|
| 81 |
+
*,
|
| 82 |
+
page_size: int = 32,
|
| 83 |
+
num_slices_per_block: int = 8,
|
| 84 |
+
):
|
| 85 |
+
_, num_combined_kv_heads, head_dim = new_kv.shape
|
| 86 |
+
assert kv_cache.shape[1] == num_combined_kv_heads
|
| 87 |
+
assert kv_cache.shape[2] == head_dim
|
| 88 |
+
assert head_dim % 128 == 0
|
| 89 |
+
# TODO: Add dynamic check to make sure that the all the slice lengths are
|
| 90 |
+
# smaller or equal to page_size
|
| 91 |
+
|
| 92 |
+
in_specs = [
|
| 93 |
+
pl.BlockSpec(memory_space=pltpu.TPUMemorySpace.ANY),
|
| 94 |
+
pl.BlockSpec(memory_space=pltpu.TPUMemorySpace.ANY),
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
out_specs = [pl.BlockSpec(memory_space=pltpu.TPUMemorySpace.ANY)]
|
| 98 |
+
out_shape = [jax.ShapeDtypeStruct(kv_cache.shape, dtype=kv_cache.dtype)]
|
| 99 |
+
|
| 100 |
+
scalar_prefetches = [slices, num_kv_update_slices]
|
| 101 |
+
scratch = pltpu.VMEM(
|
| 102 |
+
(num_slices_per_block, page_size, num_combined_kv_heads, head_dim),
|
| 103 |
+
new_kv.dtype,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
scratch_shapes = [
|
| 107 |
+
scratch,
|
| 108 |
+
pltpu.SemaphoreType.DMA,
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
kernel = pl.pallas_call(
|
| 112 |
+
_kv_cache_update_kernel,
|
| 113 |
+
grid_spec=pltpu.PrefetchScalarGridSpec(
|
| 114 |
+
num_scalar_prefetch=len(scalar_prefetches),
|
| 115 |
+
in_specs=in_specs,
|
| 116 |
+
out_specs=out_specs,
|
| 117 |
+
grid=(cdiv(num_kv_update_slices[0], num_slices_per_block), ),
|
| 118 |
+
scratch_shapes=scratch_shapes,
|
| 119 |
+
),
|
| 120 |
+
out_shape=out_shape,
|
| 121 |
+
input_output_aliases={len(scalar_prefetches) + 1: 0},
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
return kernel(*scalar_prefetches, new_kv, kv_cache)[0]
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/rocm_aiter_mla.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from vllm.platforms import current_platform
|
| 9 |
+
from vllm.utils import direct_register_custom_op, is_torch_equal_or_newer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_aiter_mla_metadata(max_batch_size: int, block_size: int,
|
| 13 |
+
max_block_per_batch: int,
|
| 14 |
+
device: torch.device) -> tuple[torch.Tensor, ...]:
|
| 15 |
+
paged_kv_indices = torch.zeros(max_batch_size * max_block_per_batch,
|
| 16 |
+
dtype=torch.int32,
|
| 17 |
+
device=device)
|
| 18 |
+
paged_kv_indptr = torch.zeros(max_batch_size + 1,
|
| 19 |
+
dtype=torch.int32,
|
| 20 |
+
device=device)
|
| 21 |
+
paged_kv_last_page_lens = torch.full((max_batch_size, ),
|
| 22 |
+
block_size,
|
| 23 |
+
dtype=torch.int32)
|
| 24 |
+
qo_indptr = torch.zeros(max_batch_size + 1, dtype=torch.int, device=device)
|
| 25 |
+
return paged_kv_indices, paged_kv_indptr, paged_kv_last_page_lens, qo_indptr
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def aiter_mla_decode_fwd(
|
| 29 |
+
q: torch.Tensor,
|
| 30 |
+
kv_buffer: torch.Tensor,
|
| 31 |
+
o: torch.Tensor,
|
| 32 |
+
sm_scale: float,
|
| 33 |
+
qo_indptr: torch.Tensor,
|
| 34 |
+
max_seqlen_qo: int,
|
| 35 |
+
kv_indptr: Optional[torch.Tensor] = None,
|
| 36 |
+
kv_indices: Optional[torch.Tensor] = None,
|
| 37 |
+
kv_last_page_lens: Optional[torch.Tensor] = None,
|
| 38 |
+
logit_cap: float = 0.0,
|
| 39 |
+
):
|
| 40 |
+
|
| 41 |
+
torch.ops.vllm.rocm_aiter_mla_decode_fwd(q,
|
| 42 |
+
kv_buffer.view(
|
| 43 |
+
-1, 1, 1, q.shape[-1]),
|
| 44 |
+
o,
|
| 45 |
+
qo_indptr,
|
| 46 |
+
max_seqlen_qo,
|
| 47 |
+
kv_indptr,
|
| 48 |
+
kv_indices,
|
| 49 |
+
kv_last_page_lens,
|
| 50 |
+
sm_scale=sm_scale,
|
| 51 |
+
logit_cap=logit_cap)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def mla_decode_fwd_impl(
|
| 55 |
+
q: torch.Tensor,
|
| 56 |
+
kv_buffer: torch.Tensor,
|
| 57 |
+
o: torch.Tensor,
|
| 58 |
+
qo_indptr: torch.Tensor,
|
| 59 |
+
max_seqlen_qo: int,
|
| 60 |
+
kv_indptr: Optional[torch.Tensor] = None,
|
| 61 |
+
kv_indices: Optional[torch.Tensor] = None,
|
| 62 |
+
kv_last_page_lens: Optional[torch.Tensor] = None,
|
| 63 |
+
sm_scale: float = 1.0,
|
| 64 |
+
logit_cap: float = 0.0,
|
| 65 |
+
) -> None:
|
| 66 |
+
from aiter.mla import mla_decode_fwd
|
| 67 |
+
|
| 68 |
+
mla_decode_fwd(q,
|
| 69 |
+
kv_buffer.view(-1, 1, 1, q.shape[-1]),
|
| 70 |
+
o,
|
| 71 |
+
qo_indptr,
|
| 72 |
+
kv_indptr,
|
| 73 |
+
kv_indices,
|
| 74 |
+
kv_last_page_lens,
|
| 75 |
+
max_seqlen_qo,
|
| 76 |
+
sm_scale=sm_scale,
|
| 77 |
+
logit_cap=logit_cap)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def mla_decode_fwd_fake(
|
| 81 |
+
q: torch.Tensor,
|
| 82 |
+
kv_buffer: torch.Tensor,
|
| 83 |
+
o: torch.Tensor,
|
| 84 |
+
qo_indptr: torch.Tensor,
|
| 85 |
+
max_seqlen_qo: int,
|
| 86 |
+
kv_indptr: Optional[torch.Tensor] = None,
|
| 87 |
+
kv_indices: Optional[torch.Tensor] = None,
|
| 88 |
+
kv_last_page_lens: Optional[torch.Tensor] = None,
|
| 89 |
+
sm_scale: float = 1.0,
|
| 90 |
+
logit_cap: float = 0.0,
|
| 91 |
+
) -> None:
|
| 92 |
+
pass
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if current_platform.is_rocm():
|
| 96 |
+
if is_torch_equal_or_newer("2.7.0"):
|
| 97 |
+
tags = ()
|
| 98 |
+
else:
|
| 99 |
+
tags = (torch.Tag.needs_fixed_stride_order, ),
|
| 100 |
+
direct_register_custom_op(op_name="rocm_aiter_mla_decode_fwd",
|
| 101 |
+
op_func=mla_decode_fwd_impl,
|
| 102 |
+
mutates_args=["o"],
|
| 103 |
+
fake_impl=mla_decode_fwd_fake,
|
| 104 |
+
tags=tags)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/rocm_aiter_paged_attn.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import aiter as rocm_aiter
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from vllm.attention.ops.paged_attn import PagedAttention
|
| 9 |
+
from vllm.platforms import current_platform
|
| 10 |
+
from vllm.utils import cdiv
|
| 11 |
+
|
| 12 |
+
FP8_DTYPE = current_platform.fp8_dtype()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AITERPagedAttention(PagedAttention):
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def write_to_paged_cache(
|
| 19 |
+
key: torch.Tensor,
|
| 20 |
+
value: torch.Tensor,
|
| 21 |
+
key_cache: torch.Tensor,
|
| 22 |
+
value_cache: torch.Tensor,
|
| 23 |
+
slot_mapping: torch.Tensor,
|
| 24 |
+
kv_cache_dtype: str,
|
| 25 |
+
k_scale: torch.Tensor,
|
| 26 |
+
v_scale: torch.Tensor,
|
| 27 |
+
) -> None:
|
| 28 |
+
if kv_cache_dtype not in ["int8", "fp8", "fp8_e4m3"]:
|
| 29 |
+
PagedAttention.write_to_paged_cache(key, value, key_cache,
|
| 30 |
+
value_cache, slot_mapping,
|
| 31 |
+
kv_cache_dtype, k_scale,
|
| 32 |
+
v_scale)
|
| 33 |
+
else:
|
| 34 |
+
kv_cache_torch_dtype = (FP8_DTYPE
|
| 35 |
+
if "fp8" in kv_cache_dtype else torch.int8)
|
| 36 |
+
key_cache = key_cache.view(kv_cache_torch_dtype)
|
| 37 |
+
value_cache = value_cache.view(kv_cache_torch_dtype)
|
| 38 |
+
|
| 39 |
+
rocm_aiter.reshape_and_cache_with_pertoken_quant(
|
| 40 |
+
key, value, key_cache, value_cache, k_scale, v_scale,
|
| 41 |
+
slot_mapping.flatten(), True)
|
| 42 |
+
|
| 43 |
+
@staticmethod
|
| 44 |
+
def forward_decode(
|
| 45 |
+
query: torch.Tensor,
|
| 46 |
+
key_cache: torch.Tensor,
|
| 47 |
+
value_cache: torch.Tensor,
|
| 48 |
+
block_tables: torch.Tensor,
|
| 49 |
+
seq_lens: torch.Tensor,
|
| 50 |
+
max_seq_len: int,
|
| 51 |
+
kv_cache_dtype: str,
|
| 52 |
+
num_kv_heads: int,
|
| 53 |
+
scale: float,
|
| 54 |
+
alibi_slopes: Optional[torch.Tensor],
|
| 55 |
+
k_scale: torch.Tensor,
|
| 56 |
+
v_scale: torch.Tensor,
|
| 57 |
+
tp_rank: int = 0,
|
| 58 |
+
blocksparse_local_blocks: int = 0,
|
| 59 |
+
blocksparse_vert_stride: int = 0,
|
| 60 |
+
blocksparse_block_size: int = 64,
|
| 61 |
+
blocksparse_head_sliding_step: int = 0,
|
| 62 |
+
) -> torch.Tensor:
|
| 63 |
+
if kv_cache_dtype not in ["int8", "fp8", "fp8_e4m3"]:
|
| 64 |
+
return PagedAttention.forward_decode(
|
| 65 |
+
query=query,
|
| 66 |
+
key_cache=key_cache,
|
| 67 |
+
value_cache=value_cache,
|
| 68 |
+
block_tables=block_tables,
|
| 69 |
+
seq_lens=seq_lens,
|
| 70 |
+
max_seq_len=max_seq_len,
|
| 71 |
+
kv_cache_dtype=kv_cache_dtype,
|
| 72 |
+
num_kv_heads=num_kv_heads,
|
| 73 |
+
scale=scale,
|
| 74 |
+
alibi_slopes=alibi_slopes,
|
| 75 |
+
k_scale=k_scale,
|
| 76 |
+
v_scale=v_scale,
|
| 77 |
+
tp_rank=tp_rank,
|
| 78 |
+
blocksparse_local_blocks=blocksparse_local_blocks,
|
| 79 |
+
blocksparse_vert_stride=blocksparse_vert_stride,
|
| 80 |
+
blocksparse_block_size=blocksparse_block_size,
|
| 81 |
+
blocksparse_head_sliding_step=blocksparse_head_sliding_step)
|
| 82 |
+
|
| 83 |
+
if "fp8" in kv_cache_dtype:
|
| 84 |
+
key_cache = key_cache.view(torch.float8_e4m3fnuz)
|
| 85 |
+
value_cache = value_cache.view(torch.float8_e4m3fnuz)
|
| 86 |
+
|
| 87 |
+
if blocksparse_vert_stride is not None and blocksparse_vert_stride > 1:
|
| 88 |
+
# use blocksparse paged attention
|
| 89 |
+
block_size = value_cache.size(-1)
|
| 90 |
+
assert (blocksparse_block_size > 0 and
|
| 91 |
+
blocksparse_block_size % block_size == 0), \
|
| 92 |
+
(f"{blocksparse_block_size=} needs to be a multiple of"
|
| 93 |
+
f"{block_size=} used in block_tables.")
|
| 94 |
+
|
| 95 |
+
output = torch.empty_like(query)
|
| 96 |
+
block_size = value_cache.shape[3]
|
| 97 |
+
max_num_blocks_per_seq = cdiv(max_seq_len, block_size)
|
| 98 |
+
|
| 99 |
+
rocm_aiter.pa_fwd_asm(query, key_cache, value_cache, block_tables,
|
| 100 |
+
seq_lens, max_num_blocks_per_seq, k_scale,
|
| 101 |
+
v_scale, output)
|
| 102 |
+
return output
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/attention/ops/triton_decode_attention.py
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
|
| 4 |
+
# Adapted from
|
| 5 |
+
# https://github.com/sgl-project/sglang/blob/9f635ea50de920aa507f486daafba26a5b837574/python/sglang/srt/layers/attention/triton_ops/decode_attention.py
|
| 6 |
+
# which was originally adapted from
|
| 7 |
+
# https://github.com/ModelTC/lightllm/blob/96353e868a840db4d103138caf15ed9dbea8c186/lightllm/models/deepseek2/triton_kernel/gqa_flash_decoding_stage1.py
|
| 8 |
+
# https://github.com/ModelTC/lightllm/blob/96353e868a840db4d103138caf15ed9dbea8c186/lightllm/models/deepseek2/triton_kernel/gqa_flash_decoding_stage2.py
|
| 9 |
+
|
| 10 |
+
# Changes:
|
| 11 |
+
# - Add support for page size >= 1.
|
| 12 |
+
|
| 13 |
+
# Copyright 2025 vLLM Team
|
| 14 |
+
# Copyright 2023-2024 SGLang Team
|
| 15 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 16 |
+
# you may not use this file except in compliance with the License.
|
| 17 |
+
# You may obtain a copy of the License at
|
| 18 |
+
#
|
| 19 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 20 |
+
#
|
| 21 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 22 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 23 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 24 |
+
# See the License for the specific language governing permissions and
|
| 25 |
+
# limitations under the License.
|
| 26 |
+
# ==============================================================================
|
| 27 |
+
"""
|
| 28 |
+
Memory-efficient attention for decoding.
|
| 29 |
+
It supports page size >= 1.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
import logging
|
| 33 |
+
|
| 34 |
+
from packaging import version
|
| 35 |
+
|
| 36 |
+
from vllm.platforms import current_platform
|
| 37 |
+
from vllm.triton_utils import tl, triton
|
| 38 |
+
|
| 39 |
+
is_hip_ = current_platform.is_rocm()
|
| 40 |
+
|
| 41 |
+
logger = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
# Only print the following warnings when triton version < 3.2.0.
|
| 44 |
+
# The issue won't affect performance or accuracy.
|
| 45 |
+
if version.parse(triton.__version__) < version.parse('3.2.0'):
|
| 46 |
+
logger.warning(
|
| 47 |
+
"The following error message 'operation scheduled before its operands' "
|
| 48 |
+
"can be ignored.")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@triton.jit
|
| 52 |
+
def tanh(x):
|
| 53 |
+
# Tanh is just a scaled sigmoid
|
| 54 |
+
return 2 * tl.sigmoid(2 * x) - 1
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@triton.jit
|
| 58 |
+
def _fwd_kernel_stage1(
|
| 59 |
+
Q,
|
| 60 |
+
K_Buffer,
|
| 61 |
+
V_Buffer,
|
| 62 |
+
sm_scale,
|
| 63 |
+
Req_to_tokens,
|
| 64 |
+
B_Seqlen,
|
| 65 |
+
Att_Out,
|
| 66 |
+
stride_req_to_tokens_b,
|
| 67 |
+
stride_qbs,
|
| 68 |
+
stride_qh,
|
| 69 |
+
stride_buf_kbs,
|
| 70 |
+
stride_buf_kh,
|
| 71 |
+
stride_buf_vbs,
|
| 72 |
+
stride_buf_vh,
|
| 73 |
+
stride_mid_ob,
|
| 74 |
+
stride_mid_oh,
|
| 75 |
+
stride_mid_os,
|
| 76 |
+
kv_group_num: tl.constexpr,
|
| 77 |
+
BLOCK_DMODEL: tl.constexpr,
|
| 78 |
+
BLOCK_DV: tl.constexpr,
|
| 79 |
+
BLOCK_N: tl.constexpr,
|
| 80 |
+
NUM_KV_SPLITS: tl.constexpr,
|
| 81 |
+
PAGE_SIZE: tl.constexpr,
|
| 82 |
+
logit_cap: tl.constexpr,
|
| 83 |
+
Lk: tl.constexpr,
|
| 84 |
+
Lv: tl.constexpr,
|
| 85 |
+
):
|
| 86 |
+
cur_batch = tl.program_id(0)
|
| 87 |
+
cur_head = tl.program_id(1)
|
| 88 |
+
split_kv_id = tl.program_id(2)
|
| 89 |
+
|
| 90 |
+
cur_kv_head = cur_head // kv_group_num
|
| 91 |
+
|
| 92 |
+
offs_d = tl.arange(0, BLOCK_DMODEL)
|
| 93 |
+
offs_dv = tl.arange(0, BLOCK_DV)
|
| 94 |
+
mask_d = offs_d < Lk
|
| 95 |
+
mask_dv = offs_dv < Lv
|
| 96 |
+
cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)
|
| 97 |
+
cur_batch_req_idx = cur_batch
|
| 98 |
+
|
| 99 |
+
off_q = cur_batch * stride_qbs + cur_head * stride_qh + offs_d
|
| 100 |
+
q = tl.load(Q + off_q, mask=mask_d, other=0.0)
|
| 101 |
+
|
| 102 |
+
kv_len_per_split = tl.cdiv(cur_batch_seq_len, NUM_KV_SPLITS)
|
| 103 |
+
split_kv_start = kv_len_per_split * split_kv_id
|
| 104 |
+
split_kv_end = tl.minimum(split_kv_start + kv_len_per_split,
|
| 105 |
+
cur_batch_seq_len)
|
| 106 |
+
|
| 107 |
+
e_max = -float("inf")
|
| 108 |
+
e_sum = 0.0
|
| 109 |
+
acc = tl.zeros([BLOCK_DV], dtype=tl.float32)
|
| 110 |
+
|
| 111 |
+
if split_kv_end > split_kv_start:
|
| 112 |
+
for start_n in range(split_kv_start, split_kv_end, BLOCK_N):
|
| 113 |
+
offs_n = start_n + tl.arange(0, BLOCK_N)
|
| 114 |
+
kv_page_number = tl.load(
|
| 115 |
+
Req_to_tokens + stride_req_to_tokens_b * cur_batch_req_idx +
|
| 116 |
+
offs_n // PAGE_SIZE,
|
| 117 |
+
mask=offs_n < split_kv_end,
|
| 118 |
+
other=0,
|
| 119 |
+
)
|
| 120 |
+
kv_loc = kv_page_number * PAGE_SIZE + offs_n % PAGE_SIZE
|
| 121 |
+
offs_buf_k = (kv_loc[:, None] * stride_buf_kbs +
|
| 122 |
+
cur_kv_head * stride_buf_kh + offs_d[None, :])
|
| 123 |
+
k = tl.load(
|
| 124 |
+
K_Buffer + offs_buf_k,
|
| 125 |
+
mask=(offs_n[:, None] < split_kv_end) & (mask_d[None, :]),
|
| 126 |
+
other=0.0,
|
| 127 |
+
)
|
| 128 |
+
qk = tl.sum(q[None, :] * k, 1)
|
| 129 |
+
qk *= sm_scale
|
| 130 |
+
|
| 131 |
+
if logit_cap > 0:
|
| 132 |
+
qk = logit_cap * tanh(qk / logit_cap)
|
| 133 |
+
|
| 134 |
+
qk = tl.where(offs_n < split_kv_end, qk, float("-inf"))
|
| 135 |
+
|
| 136 |
+
offs_buf_v = (kv_loc[:, None] * stride_buf_vbs +
|
| 137 |
+
cur_kv_head * stride_buf_vh + offs_dv[None, :])
|
| 138 |
+
v = tl.load(
|
| 139 |
+
V_Buffer + offs_buf_v,
|
| 140 |
+
mask=(offs_n[:, None] < split_kv_end) & (mask_dv[None, :]),
|
| 141 |
+
other=0.0,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
n_e_max = tl.maximum(tl.max(qk, 0), e_max)
|
| 145 |
+
re_scale = tl.exp(e_max - n_e_max)
|
| 146 |
+
p = tl.exp(qk - n_e_max)
|
| 147 |
+
acc *= re_scale
|
| 148 |
+
acc += tl.sum(p[:, None] * v, 0)
|
| 149 |
+
|
| 150 |
+
e_sum = e_sum * re_scale + tl.sum(p, 0)
|
| 151 |
+
e_max = n_e_max
|
| 152 |
+
|
| 153 |
+
offs_mid_o = (cur_batch * stride_mid_ob + cur_head * stride_mid_oh +
|
| 154 |
+
split_kv_id * stride_mid_os + offs_dv)
|
| 155 |
+
|
| 156 |
+
tl.store(
|
| 157 |
+
Att_Out + offs_mid_o,
|
| 158 |
+
acc / e_sum,
|
| 159 |
+
mask=(mask_dv),
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
offs_mid_o_1 = (cur_batch * stride_mid_ob + cur_head * stride_mid_oh +
|
| 163 |
+
split_kv_id * stride_mid_os + Lv)
|
| 164 |
+
|
| 165 |
+
tl.store(
|
| 166 |
+
Att_Out + offs_mid_o_1,
|
| 167 |
+
e_max + tl.log(e_sum),
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _decode_att_m_fwd(
|
| 172 |
+
q,
|
| 173 |
+
k_buffer,
|
| 174 |
+
v_buffer,
|
| 175 |
+
att_out,
|
| 176 |
+
Req_to_tokens,
|
| 177 |
+
B_Seqlen,
|
| 178 |
+
num_kv_splits,
|
| 179 |
+
sm_scale,
|
| 180 |
+
page_size,
|
| 181 |
+
logit_cap,
|
| 182 |
+
):
|
| 183 |
+
BLOCK = 64 if not is_hip_ else 8
|
| 184 |
+
|
| 185 |
+
NUM_KV_SPLITS = num_kv_splits
|
| 186 |
+
Lk = k_buffer.shape[-1]
|
| 187 |
+
Lv = v_buffer.shape[-1]
|
| 188 |
+
|
| 189 |
+
batch, head_num = q.shape[0], q.shape[1]
|
| 190 |
+
|
| 191 |
+
grid = (batch, head_num, NUM_KV_SPLITS)
|
| 192 |
+
kv_group_num = q.shape[1] // k_buffer.shape[-2]
|
| 193 |
+
|
| 194 |
+
num_warps = 4
|
| 195 |
+
if kv_group_num != 1:
|
| 196 |
+
num_warps = 1 if is_hip_ else 2
|
| 197 |
+
|
| 198 |
+
BLOCK_DMODEL = triton.next_power_of_2(Lk)
|
| 199 |
+
BLOCK_DV = triton.next_power_of_2(Lv)
|
| 200 |
+
|
| 201 |
+
_fwd_kernel_stage1[grid](
|
| 202 |
+
q,
|
| 203 |
+
k_buffer,
|
| 204 |
+
v_buffer,
|
| 205 |
+
sm_scale,
|
| 206 |
+
Req_to_tokens,
|
| 207 |
+
B_Seqlen,
|
| 208 |
+
att_out,
|
| 209 |
+
Req_to_tokens.stride(0),
|
| 210 |
+
q.stride(0),
|
| 211 |
+
q.stride(1),
|
| 212 |
+
k_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 213 |
+
k_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 214 |
+
v_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 215 |
+
v_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 216 |
+
att_out.stride(0),
|
| 217 |
+
att_out.stride(1),
|
| 218 |
+
att_out.stride(2),
|
| 219 |
+
kv_group_num=kv_group_num,
|
| 220 |
+
BLOCK_DMODEL=BLOCK_DMODEL,
|
| 221 |
+
BLOCK_DV=BLOCK_DV,
|
| 222 |
+
BLOCK_N=BLOCK,
|
| 223 |
+
NUM_KV_SPLITS=NUM_KV_SPLITS,
|
| 224 |
+
PAGE_SIZE=page_size,
|
| 225 |
+
logit_cap=logit_cap,
|
| 226 |
+
num_warps=num_warps,
|
| 227 |
+
num_stages=2,
|
| 228 |
+
Lk=Lk,
|
| 229 |
+
Lv=Lv,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@triton.jit
|
| 234 |
+
def _fwd_grouped_kernel_stage1(
|
| 235 |
+
Q,
|
| 236 |
+
K_Buffer,
|
| 237 |
+
V_Buffer,
|
| 238 |
+
sm_scale,
|
| 239 |
+
Req_to_tokens,
|
| 240 |
+
B_Seqlen,
|
| 241 |
+
Att_Out,
|
| 242 |
+
stride_req_to_tokens_b,
|
| 243 |
+
stride_qbs,
|
| 244 |
+
stride_qh,
|
| 245 |
+
stride_buf_kbs,
|
| 246 |
+
stride_buf_kh,
|
| 247 |
+
stride_buf_vbs,
|
| 248 |
+
stride_buf_vh,
|
| 249 |
+
stride_mid_ob,
|
| 250 |
+
stride_mid_oh,
|
| 251 |
+
stride_mid_os,
|
| 252 |
+
kv_group_num: tl.constexpr,
|
| 253 |
+
q_head_num: tl.constexpr,
|
| 254 |
+
BLOCK_DMODEL: tl.constexpr,
|
| 255 |
+
BLOCK_DPE: tl.constexpr,
|
| 256 |
+
BLOCK_DV: tl.constexpr,
|
| 257 |
+
BLOCK_N: tl.constexpr,
|
| 258 |
+
BLOCK_H: tl.constexpr,
|
| 259 |
+
NUM_KV_SPLITS: tl.constexpr,
|
| 260 |
+
PAGE_SIZE: tl.constexpr,
|
| 261 |
+
logit_cap: tl.constexpr,
|
| 262 |
+
Lk: tl.constexpr,
|
| 263 |
+
Lv: tl.constexpr,
|
| 264 |
+
):
|
| 265 |
+
cur_batch = tl.program_id(0)
|
| 266 |
+
cur_head_id = tl.program_id(1)
|
| 267 |
+
cur_kv_head = cur_head_id // tl.cdiv(kv_group_num, BLOCK_H)
|
| 268 |
+
split_kv_id = tl.program_id(2)
|
| 269 |
+
|
| 270 |
+
if kv_group_num > BLOCK_H:
|
| 271 |
+
VALID_BLOCK_H: tl.constexpr = BLOCK_H
|
| 272 |
+
else:
|
| 273 |
+
VALID_BLOCK_H: tl.constexpr = kv_group_num
|
| 274 |
+
cur_head = cur_head_id * VALID_BLOCK_H + tl.arange(0, BLOCK_H)
|
| 275 |
+
mask_h = cur_head < (cur_head_id + 1) * VALID_BLOCK_H
|
| 276 |
+
mask_h = mask_h & (cur_head < q_head_num)
|
| 277 |
+
|
| 278 |
+
offs_d = tl.arange(0, BLOCK_DMODEL)
|
| 279 |
+
offs_dv = tl.arange(0, BLOCK_DV)
|
| 280 |
+
mask_d = offs_d < Lk
|
| 281 |
+
mask_dv = offs_dv < Lv
|
| 282 |
+
cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)
|
| 283 |
+
cur_batch_req_idx = cur_batch
|
| 284 |
+
|
| 285 |
+
offs_q = cur_batch * stride_qbs + cur_head[:, None] * stride_qh + offs_d[
|
| 286 |
+
None, :]
|
| 287 |
+
q = tl.load(Q + offs_q,
|
| 288 |
+
mask=(mask_h[:, None]) & (mask_d[None, :]),
|
| 289 |
+
other=0.0)
|
| 290 |
+
|
| 291 |
+
if BLOCK_DPE > 0:
|
| 292 |
+
offs_dpe = BLOCK_DMODEL + tl.arange(0, BLOCK_DPE)
|
| 293 |
+
mask_dpe = offs_dpe < Lk
|
| 294 |
+
off_qpe = (cur_batch * stride_qbs + cur_head[:, None] * stride_qh +
|
| 295 |
+
offs_dpe[None, :])
|
| 296 |
+
qpe = tl.load(Q + off_qpe,
|
| 297 |
+
mask=(mask_h[:, None]) & (mask_dpe[None, :]),
|
| 298 |
+
other=0.0)
|
| 299 |
+
|
| 300 |
+
kv_len_per_split = tl.cdiv(cur_batch_seq_len, NUM_KV_SPLITS)
|
| 301 |
+
split_kv_start = kv_len_per_split * split_kv_id
|
| 302 |
+
split_kv_end = tl.minimum(split_kv_start + kv_len_per_split,
|
| 303 |
+
cur_batch_seq_len)
|
| 304 |
+
|
| 305 |
+
e_max = tl.zeros([BLOCK_H], dtype=tl.float32) - float("inf")
|
| 306 |
+
e_sum = tl.zeros([BLOCK_H], dtype=tl.float32)
|
| 307 |
+
acc = tl.zeros([BLOCK_H, BLOCK_DV], dtype=tl.float32)
|
| 308 |
+
|
| 309 |
+
if split_kv_end > split_kv_start:
|
| 310 |
+
for start_n in range(split_kv_start, split_kv_end, BLOCK_N):
|
| 311 |
+
offs_n = start_n + tl.arange(0, BLOCK_N)
|
| 312 |
+
kv_page_number = tl.load(
|
| 313 |
+
Req_to_tokens + stride_req_to_tokens_b * cur_batch_req_idx +
|
| 314 |
+
offs_n // PAGE_SIZE,
|
| 315 |
+
mask=offs_n < split_kv_end,
|
| 316 |
+
other=0,
|
| 317 |
+
)
|
| 318 |
+
kv_loc = kv_page_number * PAGE_SIZE + offs_n % PAGE_SIZE
|
| 319 |
+
offs_buf_k = (kv_loc[None, :] * stride_buf_kbs +
|
| 320 |
+
cur_kv_head * stride_buf_kh + offs_d[:, None])
|
| 321 |
+
k = tl.load(
|
| 322 |
+
K_Buffer + offs_buf_k,
|
| 323 |
+
mask=(offs_n[None, :] < split_kv_end) & (mask_d[:, None]),
|
| 324 |
+
other=0.0,
|
| 325 |
+
)
|
| 326 |
+
qk = tl.dot(q, k.to(q.dtype))
|
| 327 |
+
if BLOCK_DPE > 0:
|
| 328 |
+
offs_buf_kpe = (kv_loc[None, :] * stride_buf_kbs +
|
| 329 |
+
cur_kv_head * stride_buf_kh +
|
| 330 |
+
offs_dpe[:, None])
|
| 331 |
+
kpe = tl.load(
|
| 332 |
+
K_Buffer + offs_buf_kpe,
|
| 333 |
+
mask=(offs_n[None, :] < split_kv_end) &
|
| 334 |
+
(mask_dpe[:, None]),
|
| 335 |
+
other=0.0,
|
| 336 |
+
)
|
| 337 |
+
qk += tl.dot(qpe, kpe.to(qpe.dtype))
|
| 338 |
+
qk *= sm_scale
|
| 339 |
+
|
| 340 |
+
if logit_cap > 0:
|
| 341 |
+
qk = logit_cap * tanh(qk / logit_cap)
|
| 342 |
+
|
| 343 |
+
qk = tl.where(mask_h[:, None] & (offs_n[None, :] < split_kv_end),
|
| 344 |
+
qk, float("-inf"))
|
| 345 |
+
|
| 346 |
+
offs_buf_v = (kv_loc[:, None] * stride_buf_vbs +
|
| 347 |
+
cur_kv_head * stride_buf_vh + offs_dv[None, :])
|
| 348 |
+
v = tl.load(
|
| 349 |
+
V_Buffer + offs_buf_v,
|
| 350 |
+
mask=(offs_n[:, None] < split_kv_end) & (mask_dv[None, :]),
|
| 351 |
+
other=0.0,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
n_e_max = tl.maximum(tl.max(qk, 1), e_max)
|
| 355 |
+
re_scale = tl.exp(e_max - n_e_max)
|
| 356 |
+
p = tl.exp(qk - n_e_max[:, None])
|
| 357 |
+
acc *= re_scale[:, None]
|
| 358 |
+
acc += tl.dot(p.to(v.dtype), v)
|
| 359 |
+
|
| 360 |
+
e_sum = e_sum * re_scale + tl.sum(p, 1)
|
| 361 |
+
e_max = n_e_max
|
| 362 |
+
|
| 363 |
+
offs_mid_o = (cur_batch * stride_mid_ob +
|
| 364 |
+
cur_head[:, None] * stride_mid_oh +
|
| 365 |
+
split_kv_id * stride_mid_os + offs_dv[None, :])
|
| 366 |
+
|
| 367 |
+
tl.store(
|
| 368 |
+
Att_Out + offs_mid_o,
|
| 369 |
+
acc / e_sum[:, None],
|
| 370 |
+
mask=(mask_h[:, None]) & (mask_dv[None, :]),
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
offs_mid_o_1 = (cur_batch * stride_mid_ob + cur_head * stride_mid_oh +
|
| 374 |
+
split_kv_id * stride_mid_os + Lv)
|
| 375 |
+
|
| 376 |
+
tl.store(
|
| 377 |
+
Att_Out + offs_mid_o_1,
|
| 378 |
+
e_max + tl.log(e_sum),
|
| 379 |
+
mask=mask_h,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _decode_grouped_att_m_fwd(
|
| 384 |
+
q,
|
| 385 |
+
k_buffer,
|
| 386 |
+
v_buffer,
|
| 387 |
+
att_out,
|
| 388 |
+
Req_to_tokens,
|
| 389 |
+
B_Seqlen,
|
| 390 |
+
num_kv_splits,
|
| 391 |
+
sm_scale,
|
| 392 |
+
page_size,
|
| 393 |
+
logit_cap,
|
| 394 |
+
):
|
| 395 |
+
BLOCK = 32
|
| 396 |
+
Lk = k_buffer.shape[-1]
|
| 397 |
+
Lv = v_buffer.shape[-1]
|
| 398 |
+
|
| 399 |
+
# [TODO] work around shmem limit on MI3xx
|
| 400 |
+
if is_hip_ and Lk >= 576:
|
| 401 |
+
BLOCK = 16
|
| 402 |
+
|
| 403 |
+
if Lk == 576:
|
| 404 |
+
BLOCK_DMODEL = 512
|
| 405 |
+
BLOCK_DPE = 64
|
| 406 |
+
elif Lk == 288:
|
| 407 |
+
BLOCK_DMODEL = 256
|
| 408 |
+
BLOCK_DPE = 32
|
| 409 |
+
else:
|
| 410 |
+
BLOCK_DMODEL = triton.next_power_of_2(Lk)
|
| 411 |
+
BLOCK_DPE = 0
|
| 412 |
+
BLOCK_DV = triton.next_power_of_2(Lv)
|
| 413 |
+
|
| 414 |
+
batch, head_num = q.shape[0], q.shape[1]
|
| 415 |
+
kv_group_num = q.shape[1] // k_buffer.shape[-2]
|
| 416 |
+
|
| 417 |
+
BLOCK_H = 16
|
| 418 |
+
NUM_KV_SPLITS = num_kv_splits
|
| 419 |
+
grid = (
|
| 420 |
+
batch,
|
| 421 |
+
triton.cdiv(head_num, min(BLOCK_H, kv_group_num)),
|
| 422 |
+
NUM_KV_SPLITS,
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
extra_kargs = {}
|
| 426 |
+
num_stages = 2
|
| 427 |
+
if is_hip_:
|
| 428 |
+
# https://rocm.docs.amd.com/en/latest/how-to/rocm-for-ai/inference-optimization/workload.html#mi300x-triton-kernel-performance-optimization
|
| 429 |
+
# https://github.com/triton-lang/triton/blob/main/third_party/amd/backend/compiler.py
|
| 430 |
+
extra_kargs = {
|
| 431 |
+
"waves_per_eu": 1,
|
| 432 |
+
"matrix_instr_nonkdim": 16,
|
| 433 |
+
"kpack": 2
|
| 434 |
+
}
|
| 435 |
+
num_stages = 1
|
| 436 |
+
|
| 437 |
+
_fwd_grouped_kernel_stage1[grid](
|
| 438 |
+
q,
|
| 439 |
+
k_buffer,
|
| 440 |
+
v_buffer,
|
| 441 |
+
sm_scale,
|
| 442 |
+
Req_to_tokens,
|
| 443 |
+
B_Seqlen,
|
| 444 |
+
att_out,
|
| 445 |
+
Req_to_tokens.stride(0),
|
| 446 |
+
q.stride(0),
|
| 447 |
+
q.stride(1),
|
| 448 |
+
k_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 449 |
+
k_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 450 |
+
v_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 451 |
+
v_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
| 452 |
+
att_out.stride(0),
|
| 453 |
+
att_out.stride(1),
|
| 454 |
+
att_out.stride(2),
|
| 455 |
+
kv_group_num=kv_group_num,
|
| 456 |
+
q_head_num=head_num,
|
| 457 |
+
BLOCK_DMODEL=BLOCK_DMODEL,
|
| 458 |
+
BLOCK_DPE=BLOCK_DPE,
|
| 459 |
+
BLOCK_DV=BLOCK_DV,
|
| 460 |
+
BLOCK_N=BLOCK,
|
| 461 |
+
BLOCK_H=BLOCK_H,
|
| 462 |
+
NUM_KV_SPLITS=NUM_KV_SPLITS,
|
| 463 |
+
PAGE_SIZE=page_size,
|
| 464 |
+
logit_cap=logit_cap,
|
| 465 |
+
num_warps=4,
|
| 466 |
+
num_stages=num_stages,
|
| 467 |
+
Lk=Lk,
|
| 468 |
+
Lv=Lv,
|
| 469 |
+
**extra_kargs,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@triton.jit
|
| 474 |
+
def _fwd_kernel_stage2(
|
| 475 |
+
Mid_O,
|
| 476 |
+
o,
|
| 477 |
+
B_Seqlen,
|
| 478 |
+
stride_mid_ob,
|
| 479 |
+
stride_mid_oh,
|
| 480 |
+
stride_mid_os,
|
| 481 |
+
stride_obs,
|
| 482 |
+
stride_oh,
|
| 483 |
+
NUM_KV_SPLITS: tl.constexpr,
|
| 484 |
+
BLOCK_DV: tl.constexpr,
|
| 485 |
+
Lv: tl.constexpr,
|
| 486 |
+
):
|
| 487 |
+
cur_batch = tl.program_id(0)
|
| 488 |
+
cur_head = tl.program_id(1)
|
| 489 |
+
|
| 490 |
+
cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)
|
| 491 |
+
|
| 492 |
+
offs_d = tl.arange(0, BLOCK_DV)
|
| 493 |
+
mask_d = offs_d < Lv
|
| 494 |
+
|
| 495 |
+
e_sum = 0.0
|
| 496 |
+
e_max = -float("inf")
|
| 497 |
+
acc = tl.zeros([BLOCK_DV], dtype=tl.float32)
|
| 498 |
+
|
| 499 |
+
offs_v = cur_batch * stride_mid_ob + cur_head * stride_mid_oh + offs_d
|
| 500 |
+
offs_logic = cur_batch * stride_mid_ob + cur_head * stride_mid_oh + Lv
|
| 501 |
+
|
| 502 |
+
for split_kv_id in range(0, NUM_KV_SPLITS):
|
| 503 |
+
kv_len_per_split = tl.cdiv(cur_batch_seq_len, NUM_KV_SPLITS)
|
| 504 |
+
split_kv_start = kv_len_per_split * split_kv_id
|
| 505 |
+
split_kv_end = tl.minimum(split_kv_start + kv_len_per_split,
|
| 506 |
+
cur_batch_seq_len)
|
| 507 |
+
|
| 508 |
+
if split_kv_end > split_kv_start:
|
| 509 |
+
tv = tl.load(Mid_O + offs_v + split_kv_id * stride_mid_os,
|
| 510 |
+
mask=mask_d,
|
| 511 |
+
other=0.0)
|
| 512 |
+
tlogic = tl.load(Mid_O + offs_logic + split_kv_id * stride_mid_os)
|
| 513 |
+
n_e_max = tl.maximum(tlogic, e_max)
|
| 514 |
+
|
| 515 |
+
old_scale = tl.exp(e_max - n_e_max)
|
| 516 |
+
acc *= old_scale
|
| 517 |
+
exp_logic = tl.exp(tlogic - n_e_max)
|
| 518 |
+
acc += exp_logic * tv
|
| 519 |
+
|
| 520 |
+
e_sum = e_sum * old_scale + exp_logic
|
| 521 |
+
e_max = n_e_max
|
| 522 |
+
|
| 523 |
+
tl.store(
|
| 524 |
+
o + cur_batch * stride_obs + cur_head * stride_oh + offs_d,
|
| 525 |
+
acc / e_sum,
|
| 526 |
+
mask=mask_d,
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _decode_softmax_reducev_fwd(
|
| 531 |
+
logits,
|
| 532 |
+
q,
|
| 533 |
+
o,
|
| 534 |
+
v_buffer,
|
| 535 |
+
b_seq_len,
|
| 536 |
+
num_kv_splits,
|
| 537 |
+
):
|
| 538 |
+
batch, head_num = q.shape[0], q.shape[1]
|
| 539 |
+
Lv = v_buffer.shape[-1]
|
| 540 |
+
BLOCK_DV = triton.next_power_of_2(Lv)
|
| 541 |
+
|
| 542 |
+
NUM_KV_SPLITS = num_kv_splits
|
| 543 |
+
|
| 544 |
+
extra_kargs = {}
|
| 545 |
+
if is_hip_:
|
| 546 |
+
# https://rocm.docs.amd.com/en/docs-6.2.0/how-to/llm-fine-tuning-optimization/optimizing-triton-kernel.html
|
| 547 |
+
# https://github.com/triton-lang/triton/blob/main/third_party/amd/backend/compiler.py
|
| 548 |
+
extra_kargs = {
|
| 549 |
+
"waves_per_eu": 4,
|
| 550 |
+
"matrix_instr_nonkdim": 16,
|
| 551 |
+
"kpack": 2
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
grid = (batch, head_num)
|
| 555 |
+
_fwd_kernel_stage2[grid](
|
| 556 |
+
logits,
|
| 557 |
+
o,
|
| 558 |
+
b_seq_len,
|
| 559 |
+
logits.stride(0),
|
| 560 |
+
logits.stride(1),
|
| 561 |
+
logits.stride(2),
|
| 562 |
+
o.stride(0),
|
| 563 |
+
o.stride(1),
|
| 564 |
+
NUM_KV_SPLITS=NUM_KV_SPLITS,
|
| 565 |
+
BLOCK_DV=BLOCK_DV,
|
| 566 |
+
Lv=Lv,
|
| 567 |
+
num_warps=4,
|
| 568 |
+
num_stages=2,
|
| 569 |
+
**extra_kargs,
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def decode_attention_fwd_normal(
|
| 574 |
+
q,
|
| 575 |
+
k_buffer,
|
| 576 |
+
v_buffer,
|
| 577 |
+
o,
|
| 578 |
+
req_to_token,
|
| 579 |
+
b_seq_len,
|
| 580 |
+
attn_logits,
|
| 581 |
+
num_kv_splits,
|
| 582 |
+
sm_scale,
|
| 583 |
+
page_size,
|
| 584 |
+
logit_cap=0.0,
|
| 585 |
+
):
|
| 586 |
+
_decode_att_m_fwd(
|
| 587 |
+
q,
|
| 588 |
+
k_buffer,
|
| 589 |
+
v_buffer,
|
| 590 |
+
attn_logits,
|
| 591 |
+
req_to_token,
|
| 592 |
+
b_seq_len,
|
| 593 |
+
num_kv_splits,
|
| 594 |
+
sm_scale,
|
| 595 |
+
page_size,
|
| 596 |
+
logit_cap,
|
| 597 |
+
)
|
| 598 |
+
_decode_softmax_reducev_fwd(attn_logits, q, o, v_buffer, b_seq_len,
|
| 599 |
+
num_kv_splits)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def decode_attention_fwd_grouped(
|
| 603 |
+
q,
|
| 604 |
+
k_buffer,
|
| 605 |
+
v_buffer,
|
| 606 |
+
o,
|
| 607 |
+
req_to_token,
|
| 608 |
+
b_seq_len,
|
| 609 |
+
attn_logits,
|
| 610 |
+
num_kv_splits,
|
| 611 |
+
sm_scale,
|
| 612 |
+
page_size,
|
| 613 |
+
logit_cap=0.0,
|
| 614 |
+
):
|
| 615 |
+
_decode_grouped_att_m_fwd(
|
| 616 |
+
q,
|
| 617 |
+
k_buffer,
|
| 618 |
+
v_buffer,
|
| 619 |
+
attn_logits,
|
| 620 |
+
req_to_token,
|
| 621 |
+
b_seq_len,
|
| 622 |
+
num_kv_splits,
|
| 623 |
+
sm_scale,
|
| 624 |
+
page_size,
|
| 625 |
+
logit_cap,
|
| 626 |
+
)
|
| 627 |
+
_decode_softmax_reducev_fwd(attn_logits, q, o, v_buffer, b_seq_len,
|
| 628 |
+
num_kv_splits)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def decode_attention_fwd(
|
| 632 |
+
q,
|
| 633 |
+
k_buffer,
|
| 634 |
+
v_buffer,
|
| 635 |
+
o,
|
| 636 |
+
req_to_token,
|
| 637 |
+
b_seq_len,
|
| 638 |
+
attn_logits,
|
| 639 |
+
num_kv_splits,
|
| 640 |
+
sm_scale,
|
| 641 |
+
page_size=1,
|
| 642 |
+
logit_cap=0.0,
|
| 643 |
+
):
|
| 644 |
+
assert num_kv_splits == attn_logits.shape[2]
|
| 645 |
+
kv_group_num = q.shape[1] // v_buffer.shape[-2]
|
| 646 |
+
|
| 647 |
+
if kv_group_num == 1:
|
| 648 |
+
# MHA
|
| 649 |
+
decode_attention_fwd_normal(
|
| 650 |
+
q,
|
| 651 |
+
k_buffer,
|
| 652 |
+
v_buffer,
|
| 653 |
+
o,
|
| 654 |
+
req_to_token,
|
| 655 |
+
b_seq_len,
|
| 656 |
+
attn_logits,
|
| 657 |
+
num_kv_splits,
|
| 658 |
+
sm_scale,
|
| 659 |
+
page_size,
|
| 660 |
+
logit_cap,
|
| 661 |
+
)
|
| 662 |
+
else:
|
| 663 |
+
# GQA/MQA/MLA
|
| 664 |
+
decode_attention_fwd_grouped(
|
| 665 |
+
q,
|
| 666 |
+
k_buffer,
|
| 667 |
+
v_buffer,
|
| 668 |
+
o,
|
| 669 |
+
req_to_token,
|
| 670 |
+
b_seq_len,
|
| 671 |
+
attn_logits,
|
| 672 |
+
num_kv_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the vLLM project
|
| 4 |
+
"""
|
| 5 |
+
Fused Attention
|
| 6 |
+
===============
|
| 7 |
+
|
| 8 |
+
This is a Triton implementation of the Flash Attention v2 algorithm from Tri Dao
|
| 9 |
+
(https://tridao.me/publications/flash2/flash2.pdf)
|
| 10 |
+
Credits: OpenAI kernel team, AMD ML Frameworks Triton team
|
| 11 |
+
|
| 12 |
+
Features supported:
|
| 13 |
+
|
| 14 |
+
1) Fwd with causal masking
|
| 15 |
+
2) Any sequence lengths without padding (currently fwd kernel only)
|
| 16 |
+
3) Support for different sequence lengths for q and k
|
| 17 |
+
4) Nested tensor API currently does not support dropout or bias.
|
| 18 |
+
|
| 19 |
+
Not currently supported:
|
| 20 |
+
|
| 21 |
+
1) Non power of two head dims
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
from vllm.platforms import current_platform
|
| 28 |
+
from vllm.triton_utils import tl, triton
|
| 29 |
+
|
| 30 |
+
# Avoid misleading ROCm warning.
|
| 31 |
+
if current_platform.is_rocm():
|
| 32 |
+
from vllm.platforms.rocm import on_gfx1x
|
| 33 |
+
else:
|
| 34 |
+
on_gfx1x = lambda *args, **kwargs: False
|
| 35 |
+
|
| 36 |
+
torch_dtype: tl.constexpr = torch.float16
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@triton.jit
|
| 40 |
+
def cdiv_fn(x, y):
|
| 41 |
+
return (x + y - 1) // y
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@triton.jit
|
| 45 |
+
def max_fn(x, y):
|
| 46 |
+
return tl.math.max(x, y)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@triton.jit
|
| 50 |
+
def dropout_offsets(philox_seed, philox_offset, dropout_p, m, n, stride):
|
| 51 |
+
ms = tl.arange(0, m)
|
| 52 |
+
ns = tl.arange(0, n)
|
| 53 |
+
return philox_offset + ms[:, None] * stride + ns[None, :]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@triton.jit
|
| 57 |
+
def dropout_rng(philox_seed, philox_offset, dropout_p, m, n, stride):
|
| 58 |
+
rng_offsets = dropout_offsets(philox_seed, philox_offset, dropout_p, m, n,
|
| 59 |
+
stride).to(tl.uint32)
|
| 60 |
+
# TODO: use tl.randint for better performance
|
| 61 |
+
return tl.rand(philox_seed, rng_offsets)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@triton.jit
|
| 65 |
+
def dropout_mask(philox_seed, philox_offset, dropout_p, m, n, stride):
|
| 66 |
+
rng_output = dropout_rng(philox_seed, philox_offset, dropout_p, m, n,
|
| 67 |
+
stride)
|
| 68 |
+
rng_keep = rng_output > dropout_p
|
| 69 |
+
return rng_keep
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@triton.jit
|
| 73 |
+
def load_fn(block_ptr, first, second, pad):
|
| 74 |
+
if first and second:
|
| 75 |
+
tensor = tl.load(block_ptr, boundary_check=(0, 1), padding_option=pad)
|
| 76 |
+
elif first:
|
| 77 |
+
tensor = tl.load(block_ptr, boundary_check=(0, ), padding_option=pad)
|
| 78 |
+
elif second:
|
| 79 |
+
tensor = tl.load(block_ptr, boundary_check=(1, ), padding_option=pad)
|
| 80 |
+
else:
|
| 81 |
+
tensor = tl.load(block_ptr)
|
| 82 |
+
return tensor
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@triton.jit
|
| 86 |
+
def _attn_fwd_inner(
|
| 87 |
+
acc,
|
| 88 |
+
l_i,
|
| 89 |
+
m_i,
|
| 90 |
+
q,
|
| 91 |
+
K_block_ptr,
|
| 92 |
+
V_block_ptr,
|
| 93 |
+
start_m,
|
| 94 |
+
actual_seqlen_k,
|
| 95 |
+
dropout_p,
|
| 96 |
+
philox_seed,
|
| 97 |
+
batch_philox_offset,
|
| 98 |
+
encoded_softmax_block_ptr,
|
| 99 |
+
block_min,
|
| 100 |
+
block_max,
|
| 101 |
+
offs_n_causal,
|
| 102 |
+
masked_blocks,
|
| 103 |
+
n_extra_tokens,
|
| 104 |
+
bias_ptr,
|
| 105 |
+
IS_CAUSAL: tl.constexpr,
|
| 106 |
+
BLOCK_M: tl.constexpr,
|
| 107 |
+
BLOCK_DMODEL: tl.constexpr,
|
| 108 |
+
BLOCK_N: tl.constexpr,
|
| 109 |
+
OFFS_M: tl.constexpr,
|
| 110 |
+
OFFS_N: tl.constexpr,
|
| 111 |
+
PRE_LOAD_V: tl.constexpr,
|
| 112 |
+
MASK_STEPS: tl.constexpr,
|
| 113 |
+
ENABLE_DROPOUT: tl.constexpr,
|
| 114 |
+
RETURN_ENCODED_SOFTMAX: tl.constexpr,
|
| 115 |
+
PADDED_HEAD: tl.constexpr,
|
| 116 |
+
USE_FP8: tl.constexpr,
|
| 117 |
+
qk_scale,
|
| 118 |
+
p_descale,
|
| 119 |
+
):
|
| 120 |
+
# loop over k, v, and update accumulator
|
| 121 |
+
for start_n in range(block_min, block_max, BLOCK_N):
|
| 122 |
+
# For padded blocks, we will overrun the tensor size if
|
| 123 |
+
# we load all BLOCK_N. For others, the blocks are all within range.
|
| 124 |
+
k = load_fn(
|
| 125 |
+
K_block_ptr,
|
| 126 |
+
PADDED_HEAD,
|
| 127 |
+
MASK_STEPS and (n_extra_tokens != 0),
|
| 128 |
+
"zero",
|
| 129 |
+
)
|
| 130 |
+
if PRE_LOAD_V:
|
| 131 |
+
v = load_fn(
|
| 132 |
+
V_block_ptr,
|
| 133 |
+
MASK_STEPS and (n_extra_tokens != 0),
|
| 134 |
+
PADDED_HEAD,
|
| 135 |
+
"zero",
|
| 136 |
+
)
|
| 137 |
+
qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
|
| 138 |
+
# We start from end of seqlen_k so only the first iteration would need
|
| 139 |
+
# to be checked for padding if it is not a multiple of block_n
|
| 140 |
+
# TODO: This can be optimized to only be true for the padded block.
|
| 141 |
+
if MASK_STEPS: # noqa: SIM102
|
| 142 |
+
# If this is the last block / iteration, we want to
|
| 143 |
+
# mask if the sequence length is not a multiple of block size
|
| 144 |
+
# a solution is to always do BLOCK_M // BLOCK_N + 1 steps
|
| 145 |
+
# if not is_modulo_mn. last step might get wasted but that is okay.
|
| 146 |
+
# check if this masking works for that case.
|
| 147 |
+
if (start_n + BLOCK_N == block_max) and (n_extra_tokens != 0):
|
| 148 |
+
boundary_m = tl.full([BLOCK_M],
|
| 149 |
+
actual_seqlen_k,
|
| 150 |
+
dtype=tl.int32)
|
| 151 |
+
size_n = start_n + OFFS_N[None, :]
|
| 152 |
+
mask = size_n < boundary_m[:, None]
|
| 153 |
+
qk = tl.where(mask, qk, float("-inf"))
|
| 154 |
+
if IS_CAUSAL:
|
| 155 |
+
causal_boundary = start_n + offs_n_causal
|
| 156 |
+
causal_mask = OFFS_M[:, None] >= causal_boundary[None, :]
|
| 157 |
+
qk = tl.where(causal_mask, qk, float("-inf"))
|
| 158 |
+
# -- compute qk ----
|
| 159 |
+
qk += tl.dot(q, k)
|
| 160 |
+
if USE_FP8:
|
| 161 |
+
qk *= qk_scale
|
| 162 |
+
if bias_ptr is not None:
|
| 163 |
+
bias = load_fn(bias_ptr, False, MASK_STEPS
|
| 164 |
+
and (n_extra_tokens != 0), "zero")
|
| 165 |
+
# While bias is added after multiplying qk with sm_scale, our
|
| 166 |
+
# optimization to use 2^x instead of e^x results in an additional
|
| 167 |
+
# scale factor of log2(e) which we must also multiply the bias with.
|
| 168 |
+
qk += bias * 1.44269504089
|
| 169 |
+
m_ij = tl.maximum(m_i, tl.max(qk, 1))
|
| 170 |
+
qk = qk - m_ij[:, None]
|
| 171 |
+
p = tl.math.exp2(qk)
|
| 172 |
+
|
| 173 |
+
# CAVEAT: Must update l_ij before applying dropout
|
| 174 |
+
l_ij = tl.sum(p, 1)
|
| 175 |
+
if ENABLE_DROPOUT:
|
| 176 |
+
philox_offset = (batch_philox_offset +
|
| 177 |
+
start_m * BLOCK_M * actual_seqlen_k + start_n -
|
| 178 |
+
BLOCK_N)
|
| 179 |
+
keep = dropout_mask(
|
| 180 |
+
philox_seed,
|
| 181 |
+
philox_offset,
|
| 182 |
+
dropout_p,
|
| 183 |
+
BLOCK_M,
|
| 184 |
+
BLOCK_N,
|
| 185 |
+
actual_seqlen_k,
|
| 186 |
+
)
|
| 187 |
+
if RETURN_ENCODED_SOFTMAX:
|
| 188 |
+
tl.store(
|
| 189 |
+
encoded_softmax_block_ptr,
|
| 190 |
+
tl.where(keep, p,
|
| 191 |
+
-p).to(encoded_softmax_block_ptr.type.element_ty),
|
| 192 |
+
)
|
| 193 |
+
p = tl.where(keep, p, 0.0)
|
| 194 |
+
elif RETURN_ENCODED_SOFTMAX:
|
| 195 |
+
tl.store(
|
| 196 |
+
encoded_softmax_block_ptr,
|
| 197 |
+
p.to(encoded_softmax_block_ptr.type.element_ty),
|
| 198 |
+
)
|
| 199 |
+
# -- update output accumulator --
|
| 200 |
+
alpha = tl.math.exp2(m_i - m_ij)
|
| 201 |
+
acc = acc * alpha[:, None]
|
| 202 |
+
if not PRE_LOAD_V:
|
| 203 |
+
v = load_fn(
|
| 204 |
+
V_block_ptr,
|
| 205 |
+
MASK_STEPS and (n_extra_tokens != 0),
|
| 206 |
+
PADDED_HEAD,
|
| 207 |
+
"zero",
|
| 208 |
+
)
|
| 209 |
+
# -- update m_i and l_i
|
| 210 |
+
l_i = l_i * alpha + l_ij
|
| 211 |
+
# update m_i and l_i
|
| 212 |
+
m_i = m_ij
|
| 213 |
+
|
| 214 |
+
if USE_FP8:
|
| 215 |
+
p *= p_descale
|
| 216 |
+
|
| 217 |
+
acc += tl.dot(p.to(V_block_ptr.type.element_ty), v)
|
| 218 |
+
|
| 219 |
+
V_block_ptr = tl.advance(V_block_ptr, (BLOCK_N, 0))
|
| 220 |
+
K_block_ptr = tl.advance(K_block_ptr, (0, BLOCK_N))
|
| 221 |
+
if bias_ptr is not None:
|
| 222 |
+
bias_ptr = tl.advance(bias_ptr, (0, BLOCK_N))
|
| 223 |
+
if RETURN_ENCODED_SOFTMAX:
|
| 224 |
+
encoded_softmax_block_ptr = tl.advance(encoded_softmax_block_ptr,
|
| 225 |
+
(0, BLOCK_N))
|
| 226 |
+
return acc, l_i, m_i
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def get_cdna_autotune_configs():
|
| 230 |
+
return [
|
| 231 |
+
triton.Config(
|
| 232 |
+
{
|
| 233 |
+
'BLOCK_M': 256,
|
| 234 |
+
'BLOCK_N': 64,
|
| 235 |
+
'waves_per_eu': 2,
|
| 236 |
+
'PRE_LOAD_V': False
|
| 237 |
+
},
|
| 238 |
+
num_stages=1,
|
| 239 |
+
num_warps=8),
|
| 240 |
+
triton.Config(
|
| 241 |
+
{
|
| 242 |
+
'BLOCK_M': 128,
|
| 243 |
+
'BLOCK_N': 128,
|
| 244 |
+
'waves_per_eu': 2,
|
| 245 |
+
'PRE_LOAD_V': False
|
| 246 |
+
},
|
| 247 |
+
num_stages=1,
|
| 248 |
+
num_warps=4),
|
| 249 |
+
triton.Config(
|
| 250 |
+
{
|
| 251 |
+
'BLOCK_M': 256,
|
| 252 |
+
'BLOCK_N': 128,
|
| 253 |
+
'waves_per_eu': 2,
|
| 254 |
+
'PRE_LOAD_V': False
|
| 255 |
+
},
|
| 256 |
+
num_stages=1,
|
| 257 |
+
num_warps=8),
|
| 258 |
+
triton.Config(
|
| 259 |
+
{
|
| 260 |
+
'BLOCK_M': 128,
|
| 261 |
+
'BLOCK_N': 64,
|
| 262 |
+
'waves_per_eu': 1,
|
| 263 |
+
'PRE_LOAD_V': False
|
| 264 |
+
},
|
| 265 |
+
num_stages=1,
|
| 266 |
+
num_warps=4),
|
| 267 |
+
triton.Config(
|
| 268 |
+
{
|
| 269 |
+
'BLOCK_M': 128,
|
| 270 |
+
'BLOCK_N': 64,
|
| 271 |
+
'waves_per_eu': 3,
|
| 272 |
+
'PRE_LOAD_V': True
|
| 273 |
+
},
|
| 274 |
+
num_stages=1,
|
| 275 |
+
num_warps=4),
|
| 276 |
+
triton.Config(
|
| 277 |
+
{
|
| 278 |
+
'BLOCK_M': 128,
|
| 279 |
+
'BLOCK_N': 64,
|
| 280 |
+
'waves_per_eu': 3,
|
| 281 |
+
'PRE_LOAD_V': False
|
| 282 |
+
},
|
| 283 |
+
num_stages=1,
|
| 284 |
+
num_warps=4),
|
| 285 |
+
triton.Config(
|
| 286 |
+
{
|
| 287 |
+
'BLOCK_M': 64,
|
| 288 |
+
'BLOCK_N': 64,
|
| 289 |
+
'waves_per_eu': 4,
|
| 290 |
+
'PRE_LOAD_V': False
|
| 291 |
+
},
|
| 292 |
+
num_stages=1,
|
| 293 |
+
num_warps=8),
|
| 294 |
+
triton.Config(
|
| 295 |
+
{
|
| 296 |
+
'BLOCK_M': 32,
|
| 297 |
+
'BLOCK_N': 32,
|
| 298 |
+
'waves_per_eu': 4,
|
| 299 |
+
'PRE_LOAD_V': False
|
| 300 |
+
},
|
| 301 |
+
num_stages=1,
|
| 302 |
+
num_warps=8),
|
| 303 |
+
# TODO: This config fails with head_size not pow2 with data mismatches.
|
| 304 |
+
# triton.Config({'BLOCK_M': 32, 'BLOCK_N': 16, 'waves_per_eu': 1,
|
| 305 |
+
# 'PRE_LOAD_V': False}, num_stages=1, num_warps=4),
|
| 306 |
+
|
| 307 |
+
# Fails in AccelerateAMDMatmul (Triton) assert when using FP8:
|
| 308 |
+
# triton.Config(
|
| 309 |
+
# {
|
| 310 |
+
# "BLOCK_M": 16,
|
| 311 |
+
# "BLOCK_N": 16,
|
| 312 |
+
# "waves_per_eu": 1,
|
| 313 |
+
# "PRE_LOAD_V": False,
|
| 314 |
+
# },
|
| 315 |
+
# num_stages=1,
|
| 316 |
+
# num_warps=4,
|
| 317 |
+
# ),
|
| 318 |
+
], ['IS_CAUSAL', 'dropout_p', 'BLOCK_DMODEL', 'USE_FP8']
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def get_rdna_autotune_configs():
|
| 322 |
+
return [
|
| 323 |
+
triton.Config(
|
| 324 |
+
{
|
| 325 |
+
'BLOCK_M': 32,
|
| 326 |
+
'BLOCK_N': 32,
|
| 327 |
+
'waves_per_eu': 4,
|
| 328 |
+
'PRE_LOAD_V': False
|
| 329 |
+
},
|
| 330 |
+
num_stages=1,
|
| 331 |
+
num_warps=2),
|
| 332 |
+
triton.Config(
|
| 333 |
+
{
|
| 334 |
+
'BLOCK_M': 32,
|
| 335 |
+
'BLOCK_N': 32,
|
| 336 |
+
'waves_per_eu': 2,
|
| 337 |
+
'PRE_LOAD_V': False
|
| 338 |
+
},
|
| 339 |
+
num_stages=1,
|
| 340 |
+
num_warps=2),
|
| 341 |
+
triton.Config(
|
| 342 |
+
{
|
| 343 |
+
'BLOCK_M': 32,
|
| 344 |
+
'BLOCK_N': 16,
|
| 345 |
+
'waves_per_eu': 4,
|
| 346 |
+
'PRE_LOAD_V': False
|
| 347 |
+
},
|
| 348 |
+
num_stages=1,
|
| 349 |
+
num_warps=2),
|
| 350 |
+
triton.Config(
|
| 351 |
+
{
|
| 352 |
+
'BLOCK_M': 32,
|
| 353 |
+
'BLOCK_N': 16,
|
| 354 |
+
'waves_per_eu': 2,
|
| 355 |
+
'PRE_LOAD_V': False
|
| 356 |
+
},
|
| 357 |
+
num_stages=1,
|
| 358 |
+
num_warps=2),
|
| 359 |
+
# Fails in AccelerateAMDMatmul (Triton) assert when using FP8:
|
| 360 |
+
# triton.Config(
|
| 361 |
+
# {
|
| 362 |
+
# 'BLOCK_M': 16,
|
| 363 |
+
# 'BLOCK_N': 16,
|
| 364 |
+
# 'waves_per_eu': 4,
|
| 365 |
+
# 'PRE_LOAD_V': False
|
| 366 |
+
# },
|
| 367 |
+
# num_stages=1,
|
| 368 |
+
# num_warps=2),
|
| 369 |
+
# triton.Config(
|
| 370 |
+
# {
|
| 371 |
+
# 'BLOCK_M': 16,
|
| 372 |
+
# 'BLOCK_N': 16,
|
| 373 |
+
# 'waves_per_eu': 2,
|
| 374 |
+
# 'PRE_LOAD_V': False
|
| 375 |
+
# },
|
| 376 |
+
# num_stages=1,
|
| 377 |
+
# num_warps=2),
|
| 378 |
+
# # Fall-back config.
|
| 379 |
+
# triton.Config(
|
| 380 |
+
# {
|
| 381 |
+
# 'BLOCK_M': 16,
|
| 382 |
+
# 'BLOCK_N': 16,
|
| 383 |
+
# 'waves_per_eu': 1,
|
| 384 |
+
# 'PRE_LOAD_V': False
|
| 385 |
+
# },
|
| 386 |
+
# num_stages=1,
|
| 387 |
+
# num_warps=2),
|
| 388 |
+
], ['IS_CAUSAL', 'dropout_p', 'BLOCK_DMODEL', 'USE_FP8']
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def get_autotune_configs():
|
| 392 |
+
if on_gfx1x():
|
| 393 |
+
return get_rdna_autotune_configs()
|
| 394 |
+
else:
|
| 395 |
+
return get_cdna_autotune_configs()
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
autotune_configs, autotune_keys = get_autotune_configs()
|
| 399 |
+
|
| 400 |
+
float8_info = torch.finfo(current_platform.fp8_dtype())
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
@triton.autotune(
|
| 404 |
+
configs=autotune_configs,
|
| 405 |
+
key=autotune_keys,
|
| 406 |
+
)
|
| 407 |
+
@triton.jit
|
| 408 |
+
def attn_fwd(
|
| 409 |
+
Q,
|
| 410 |
+
K,
|
| 411 |
+
V,
|
| 412 |
+
bias,
|
| 413 |
+
sm_scale,
|
| 414 |
+
q_scale,
|
| 415 |
+
k_scale,
|
| 416 |
+
v_scale,
|
| 417 |
+
p_scale,
|
| 418 |
+
p_descale,
|
| 419 |
+
o_descale,
|
| 420 |
+
L,
|
| 421 |
+
Out,
|
| 422 |
+
stride_qz: tl.int64,
|
| 423 |
+
stride_qh: tl.int64,
|
| 424 |
+
stride_qm: tl.int64,
|
| 425 |
+
stride_qk: tl.int64,
|
| 426 |
+
stride_kz: tl.int64,
|
| 427 |
+
stride_kh: tl.int64,
|
| 428 |
+
stride_kn: tl.int64,
|
| 429 |
+
stride_kk: tl.int64,
|
| 430 |
+
stride_vz: tl.int64,
|
| 431 |
+
stride_vh: tl.int64,
|
| 432 |
+
stride_vk: tl.int64,
|
| 433 |
+
stride_vn: tl.int64,
|
| 434 |
+
stride_oz: tl.int64,
|
| 435 |
+
stride_oh: tl.int64,
|
| 436 |
+
stride_om: tl.int64,
|
| 437 |
+
stride_on: tl.int64,
|
| 438 |
+
stride_bz: tl.int64,
|
| 439 |
+
stride_bh: tl.int64,
|
| 440 |
+
stride_bm: tl.int64,
|
| 441 |
+
stride_bn: tl.int64,
|
| 442 |
+
cu_seqlens_q,
|
| 443 |
+
cu_seqlens_k,
|
| 444 |
+
dropout_p,
|
| 445 |
+
philox_seed,
|
| 446 |
+
philox_offset_base,
|
| 447 |
+
encoded_softmax,
|
| 448 |
+
HQ: tl.constexpr,
|
| 449 |
+
HK: tl.constexpr,
|
| 450 |
+
ACTUAL_BLOCK_DMODEL: tl.constexpr,
|
| 451 |
+
MAX_SEQLENS_Q: tl.constexpr,
|
| 452 |
+
MAX_SEQLENS_K: tl.constexpr,
|
| 453 |
+
VARLEN: tl.constexpr,
|
| 454 |
+
IS_CAUSAL: tl.constexpr,
|
| 455 |
+
BLOCK_M: tl.constexpr,
|
| 456 |
+
BLOCK_DMODEL: tl.constexpr,
|
| 457 |
+
USE_FP8: tl.constexpr,
|
| 458 |
+
USE_FP8_OUT: tl.constexpr,
|
| 459 |
+
BLOCK_N: tl.constexpr,
|
| 460 |
+
PRE_LOAD_V: tl.constexpr,
|
| 461 |
+
BIAS_TYPE: tl.constexpr,
|
| 462 |
+
ENABLE_DROPOUT: tl.constexpr,
|
| 463 |
+
RETURN_ENCODED_SOFTMAX: tl.constexpr,
|
| 464 |
+
FP8_MIN: tl.constexpr = float8_info.min,
|
| 465 |
+
FP8_MAX: tl.constexpr = float8_info.max,
|
| 466 |
+
):
|
| 467 |
+
start_m = tl.program_id(0)
|
| 468 |
+
off_h_q = tl.program_id(1)
|
| 469 |
+
off_z = tl.program_id(2)
|
| 470 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 471 |
+
offs_n = tl.arange(0, BLOCK_N)
|
| 472 |
+
if VARLEN:
|
| 473 |
+
cu_seqlens_q_start = tl.load(cu_seqlens_q + off_z)
|
| 474 |
+
cu_seqlens_q_end = tl.load(cu_seqlens_q + off_z + 1)
|
| 475 |
+
seqlen_q = cu_seqlens_q_end - cu_seqlens_q_start
|
| 476 |
+
# We have a one-size-fits-all grid in id(0). Some seqlens might be too
|
| 477 |
+
# small for all start_m so for those we return early.
|
| 478 |
+
if start_m * BLOCK_M > seqlen_q:
|
| 479 |
+
return
|
| 480 |
+
cu_seqlens_k_start = tl.load(cu_seqlens_k + off_z)
|
| 481 |
+
cu_seqlens_k_end = tl.load(cu_seqlens_k + off_z + 1)
|
| 482 |
+
seqlen_k = cu_seqlens_k_end - cu_seqlens_k_start
|
| 483 |
+
else:
|
| 484 |
+
cu_seqlens_q_start = 0
|
| 485 |
+
cu_seqlens_k_start = 0
|
| 486 |
+
seqlen_q = MAX_SEQLENS_Q
|
| 487 |
+
seqlen_k = MAX_SEQLENS_K
|
| 488 |
+
|
| 489 |
+
# Now we compute whether we need to exit early due to causal masking.
|
| 490 |
+
# This is because for seqlen_q > seqlen_k, M rows of the attn scores
|
| 491 |
+
# are completely masked, resulting in 0s written to the output, and
|
| 492 |
+
# inf written to LSE. We don't need to do any GEMMs in this case.
|
| 493 |
+
# This block of code determines what N is, and if this WG is operating
|
| 494 |
+
# on those M rows.
|
| 495 |
+
n_blocks = cdiv_fn(seqlen_k, BLOCK_N)
|
| 496 |
+
if IS_CAUSAL:
|
| 497 |
+
# If seqlen_q == seqlen_k, the attn scores are a square matrix.
|
| 498 |
+
# If seqlen_q != seqlen_k, attn scores are rectangular which means
|
| 499 |
+
# the causal mask boundary is bottom right aligned, and ends at either
|
| 500 |
+
# the top edge (seqlen_q < seqlen_k) or left edge.
|
| 501 |
+
# This captures the decrease in n_blocks if we have a rectangular attn
|
| 502 |
+
# matrix
|
| 503 |
+
n_blocks_seqlen = cdiv_fn(
|
| 504 |
+
(start_m + 1) * BLOCK_M + seqlen_k - seqlen_q, BLOCK_N)
|
| 505 |
+
# This is what adjusts the block_max for the current WG, only
|
| 506 |
+
# if IS_CAUSAL. Otherwise we want to always iterate through all n_blocks
|
| 507 |
+
n_blocks = min(n_blocks, n_blocks_seqlen)
|
| 508 |
+
# If we have no blocks after adjusting for seqlen deltas, this WG is
|
| 509 |
+
# part of the blocks that are all 0. We exit early.
|
| 510 |
+
if n_blocks <= 0:
|
| 511 |
+
o_offset = (off_z * stride_oz + cu_seqlens_q_start * stride_om +
|
| 512 |
+
off_h_q * stride_oh)
|
| 513 |
+
O_block_ptr = tl.make_block_ptr(
|
| 514 |
+
base=Out + o_offset,
|
| 515 |
+
shape=(seqlen_q, BLOCK_DMODEL),
|
| 516 |
+
strides=(stride_om, stride_on),
|
| 517 |
+
offsets=(start_m * BLOCK_M, 0),
|
| 518 |
+
block_shape=(BLOCK_M, BLOCK_DMODEL),
|
| 519 |
+
order=(1, 0),
|
| 520 |
+
)
|
| 521 |
+
acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=Out.type.element_ty)
|
| 522 |
+
# We still need to write 0s to the result
|
| 523 |
+
# tl.store(O_block_ptr,
|
| 524 |
+
# acc.to(Out.type.element_ty), boundary_check=(0,1))
|
| 525 |
+
# l_ptrs = L + off_z * HQ * MAX_SEQLENS_Q + off_h_q * MAX_SEQLENS_Q
|
| 526 |
+
# + offs_m
|
| 527 |
+
# We store inf to LSE, not -inf because in the bwd pass,
|
| 528 |
+
# we subtract this
|
| 529 |
+
# from qk which makes it -inf, such that exp(qk - inf) = 0
|
| 530 |
+
# for these masked blocks.
|
| 531 |
+
# l = tl.full([BLOCK_M], value=float("inf"), dtype=tl.float32)
|
| 532 |
+
# tl.store(l_ptrs, l)
|
| 533 |
+
# TODO: Should dropout and return encoded softmax be handled here?
|
| 534 |
+
return
|
| 535 |
+
|
| 536 |
+
# If MQA / GQA, set the K and V head offsets appropriately.
|
| 537 |
+
GROUP_SIZE: tl.constexpr = HQ // HK
|
| 538 |
+
off_h_k = off_h_q // GROUP_SIZE if GROUP_SIZE != 1 else off_h_q
|
| 539 |
+
|
| 540 |
+
n_extra_tokens = 0
|
| 541 |
+
if seqlen_k < BLOCK_N:
|
| 542 |
+
n_extra_tokens = BLOCK_N - seqlen_k
|
| 543 |
+
elif seqlen_k % BLOCK_N:
|
| 544 |
+
n_extra_tokens = seqlen_k % BLOCK_N
|
| 545 |
+
padded_head = ACTUAL_BLOCK_DMODEL != BLOCK_DMODEL
|
| 546 |
+
|
| 547 |
+
# Compute pointers for all the tensors used in this kernel.
|
| 548 |
+
q_offset = (off_z * stride_qz + off_h_q * stride_qh +
|
| 549 |
+
cu_seqlens_q_start * stride_qm)
|
| 550 |
+
Q_block_ptr = tl.make_block_ptr(
|
| 551 |
+
base=Q + q_offset,
|
| 552 |
+
shape=(seqlen_q, ACTUAL_BLOCK_DMODEL),
|
| 553 |
+
strides=(stride_qm, stride_qk),
|
| 554 |
+
offsets=(start_m * BLOCK_M, 0),
|
| 555 |
+
block_shape=(BLOCK_M, BLOCK_DMODEL),
|
| 556 |
+
order=(1, 0),
|
| 557 |
+
)
|
| 558 |
+
k_offset = (off_z * stride_kz + off_h_k * stride_kh +
|
| 559 |
+
cu_seqlens_k_start * stride_kn)
|
| 560 |
+
K_block_ptr = tl.make_block_ptr(
|
| 561 |
+
base=K + k_offset,
|
| 562 |
+
shape=(ACTUAL_BLOCK_DMODEL, seqlen_k),
|
| 563 |
+
strides=(stride_kk, stride_kn),
|
| 564 |
+
offsets=(0, 0),
|
| 565 |
+
block_shape=(BLOCK_DMODEL, BLOCK_N),
|
| 566 |
+
order=(0, 1),
|
| 567 |
+
)
|
| 568 |
+
v_offset = (off_z * stride_vz + off_h_k * stride_vh +
|
| 569 |
+
cu_seqlens_k_start * stride_vk)
|
| 570 |
+
V_block_ptr = tl.make_block_ptr(
|
| 571 |
+
base=V + v_offset,
|
| 572 |
+
shape=(seqlen_k, ACTUAL_BLOCK_DMODEL),
|
| 573 |
+
strides=(stride_vk, stride_vn),
|
| 574 |
+
offsets=(0, 0),
|
| 575 |
+
block_shape=(BLOCK_N, BLOCK_DMODEL),
|
| 576 |
+
order=(1, 0),
|
| 577 |
+
)
|
| 578 |
+
if BIAS_TYPE != 0:
|
| 579 |
+
bias_ptr = tl.make_block_ptr(
|
| 580 |
+
base=bias + off_h_q * stride_bh,
|
| 581 |
+
shape=(seqlen_q, seqlen_k),
|
| 582 |
+
strides=(stride_bm, stride_bn),
|
| 583 |
+
offsets=(start_m * BLOCK_M, 0),
|
| 584 |
+
block_shape=(BLOCK_M, BLOCK_N),
|
| 585 |
+
order=(1, 0),
|
| 586 |
+
)
|
| 587 |
+
else:
|
| 588 |
+
bias_ptr = None
|
| 589 |
+
if ENABLE_DROPOUT:
|
| 590 |
+
batch_philox_offset = philox_offset_base \
|
| 591 |
+
+ (off_z * HQ + off_h_q) \
|
| 592 |
+
* seqlen_q * seqlen_k
|
| 593 |
+
else:
|
| 594 |
+
batch_philox_offset = 0
|
| 595 |
+
# We can ask to return the dropout mask without actually doing any dropout.
|
| 596 |
+
# In this case, we return an invalid pointer so indicate the mask is not i
|
| 597 |
+
# valid.
|
| 598 |
+
# TODO: Fix encoded softmax. It currently uses just h_q in the base offset.
|
| 599 |
+
if RETURN_ENCODED_SOFTMAX:
|
| 600 |
+
encoded_softmax_block_ptr = tl.make_block_ptr(
|
| 601 |
+
base=encoded_softmax + off_h_q * seqlen_q * seqlen_k,
|
| 602 |
+
shape=(seqlen_q, seqlen_k),
|
| 603 |
+
strides=(seqlen_k, 1),
|
| 604 |
+
offsets=(start_m * BLOCK_M, 0),
|
| 605 |
+
block_shape=(BLOCK_M, BLOCK_N),
|
| 606 |
+
order=(1, 0),
|
| 607 |
+
)
|
| 608 |
+
else:
|
| 609 |
+
encoded_softmax_block_ptr = 0
|
| 610 |
+
# initialize pointer to m and l
|
| 611 |
+
m_i = tl.full([BLOCK_M], float("-inf"), dtype=tl.float32)
|
| 612 |
+
l_i = tl.full([BLOCK_M], 1.0, dtype=tl.float32)
|
| 613 |
+
acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)
|
| 614 |
+
# scale sm_scale by log_2(e) and use 2^x in the loop as we do not
|
| 615 |
+
# have native e^x support in HW.
|
| 616 |
+
qk_scale = sm_scale * 1.44269504089
|
| 617 |
+
# Q is loaded once at the beginning and shared by all N blocks.
|
| 618 |
+
q = load_fn(Q_block_ptr, True, padded_head, "zero")
|
| 619 |
+
if not USE_FP8:
|
| 620 |
+
q = (q * qk_scale).to(Q_block_ptr.type.element_ty)
|
| 621 |
+
acc_scale = 1.0
|
| 622 |
+
else:
|
| 623 |
+
qk_scale *= q_scale * k_scale
|
| 624 |
+
acc_scale = p_scale * v_scale
|
| 625 |
+
|
| 626 |
+
# Here we compute how many full and masked blocks we have.
|
| 627 |
+
padded_block_k = n_extra_tokens != 0
|
| 628 |
+
is_modulo_mn = not padded_block_k and (seqlen_q % BLOCK_M == 0)
|
| 629 |
+
if IS_CAUSAL:
|
| 630 |
+
# There are always at least BLOCK_M // BLOCK_N masked blocks.
|
| 631 |
+
# Additionally there might be one more due to dissimilar seqlens.
|
| 632 |
+
masked_blocks = BLOCK_M // BLOCK_N + (not is_modulo_mn)
|
| 633 |
+
else:
|
| 634 |
+
# Padding on Q does not need to be masked in the FA loop.
|
| 635 |
+
masked_blocks = padded_block_k
|
| 636 |
+
# if IS_CAUSAL, not is_modulo_mn does not always result in an additional
|
| 637 |
+
# block. In this case we might exceed n_blocks so pick the min.
|
| 638 |
+
masked_blocks = min(masked_blocks, n_blocks)
|
| 639 |
+
n_full_blocks = n_blocks - masked_blocks
|
| 640 |
+
block_min = 0
|
| 641 |
+
block_max = n_blocks * BLOCK_N
|
| 642 |
+
# Compute for full blocks. Here we set causal to false regardless of its
|
| 643 |
+
# value because there is no masking. Similarly we do not need padding.
|
| 644 |
+
if n_full_blocks > 0:
|
| 645 |
+
block_max = (n_blocks - masked_blocks) * BLOCK_N
|
| 646 |
+
acc, l_i, m_i = _attn_fwd_inner(
|
| 647 |
+
acc,
|
| 648 |
+
l_i,
|
| 649 |
+
m_i,
|
| 650 |
+
q,
|
| 651 |
+
K_block_ptr,
|
| 652 |
+
V_block_ptr,
|
| 653 |
+
start_m,
|
| 654 |
+
seqlen_k,
|
| 655 |
+
dropout_p,
|
| 656 |
+
philox_seed,
|
| 657 |
+
batch_philox_offset,
|
| 658 |
+
encoded_softmax_block_ptr,
|
| 659 |
+
# _, _, offs_n_causal, masked_blocks, n_extra_tokens, _
|
| 660 |
+
block_min,
|
| 661 |
+
block_max,
|
| 662 |
+
0,
|
| 663 |
+
0,
|
| 664 |
+
0,
|
| 665 |
+
bias_ptr,
|
| 666 |
+
# IS_CAUSAL, ....
|
| 667 |
+
False,
|
| 668 |
+
BLOCK_M,
|
| 669 |
+
BLOCK_DMODEL,
|
| 670 |
+
BLOCK_N,
|
| 671 |
+
offs_m,
|
| 672 |
+
offs_n,
|
| 673 |
+
# _, MASK_STEPS, ...
|
| 674 |
+
PRE_LOAD_V,
|
| 675 |
+
False,
|
| 676 |
+
ENABLE_DROPOUT,
|
| 677 |
+
RETURN_ENCODED_SOFTMAX,
|
| 678 |
+
padded_head,
|
| 679 |
+
USE_FP8,
|
| 680 |
+
qk_scale,
|
| 681 |
+
p_descale,
|
| 682 |
+
)
|
| 683 |
+
block_min = block_max
|
| 684 |
+
block_max = n_blocks * BLOCK_N
|
| 685 |
+
|
| 686 |
+
tl.debug_barrier()
|
| 687 |
+
# Remaining blocks, if any, are full / not masked.
|
| 688 |
+
if masked_blocks > 0:
|
| 689 |
+
offs_n_causal = offs_n + (seqlen_q - seqlen_k) if IS_CAUSAL else 0
|
| 690 |
+
K_block_ptr = tl.advance(K_block_ptr, (0, n_full_blocks * BLOCK_N))
|
| 691 |
+
V_block_ptr = tl.advance(V_block_ptr, (n_full_blocks * BLOCK_N, 0))
|
| 692 |
+
if bias_ptr is not None:
|
| 693 |
+
bias_ptr = tl.advance(bias_ptr, (0, n_full_blocks * BLOCK_N))
|
| 694 |
+
if RETURN_ENCODED_SOFTMAX:
|
| 695 |
+
encoded_softmax_block_ptr = tl.advance(encoded_softmax_block_ptr,
|
| 696 |
+
(0, n_full_blocks))
|
| 697 |
+
acc, l_i, m_i = _attn_fwd_inner(
|
| 698 |
+
acc,
|
| 699 |
+
l_i,
|
| 700 |
+
m_i,
|
| 701 |
+
q,
|
| 702 |
+
K_block_ptr,
|
| 703 |
+
V_block_ptr,
|
| 704 |
+
start_m,
|
| 705 |
+
seqlen_k,
|
| 706 |
+
dropout_p,
|
| 707 |
+
philox_seed,
|
| 708 |
+
batch_philox_offset,
|
| 709 |
+
encoded_softmax_block_ptr,
|
| 710 |
+
block_min,
|
| 711 |
+
block_max,
|
| 712 |
+
offs_n_causal,
|
| 713 |
+
masked_blocks,
|
| 714 |
+
n_extra_tokens,
|
| 715 |
+
bias_ptr,
|
| 716 |
+
IS_CAUSAL,
|
| 717 |
+
BLOCK_M,
|
| 718 |
+
BLOCK_DMODEL,
|
| 719 |
+
BLOCK_N,
|
| 720 |
+
offs_m,
|
| 721 |
+
offs_n,
|
| 722 |
+
# _, MASK_STEPS, ...
|
| 723 |
+
PRE_LOAD_V,
|
| 724 |
+
True,
|
| 725 |
+
ENABLE_DROPOUT,
|
| 726 |
+
RETURN_ENCODED_SOFTMAX,
|
| 727 |
+
padded_head,
|
| 728 |
+
USE_FP8,
|
| 729 |
+
qk_scale,
|
| 730 |
+
p_descale,
|
| 731 |
+
)
|
| 732 |
+
# epilogue
|
| 733 |
+
|
| 734 |
+
if USE_FP8:
|
| 735 |
+
acc *= acc_scale
|
| 736 |
+
acc = acc / l_i[:, None]
|
| 737 |
+
if ENABLE_DROPOUT:
|
| 738 |
+
acc = acc / (1 - dropout_p)
|
| 739 |
+
# If seqlen_q > seqlen_k but the delta is not a multiple of BLOCK_M,
|
| 740 |
+
# then we have one block with a row of all NaNs which come from computing
|
| 741 |
+
# softmax over a row of all -infs (-inf - inf = NaN). We check for that here
|
| 742 |
+
# and store 0s where there are NaNs as these rows should've been zeroed out.
|
| 743 |
+
end_m_idx = (start_m + 1) * BLOCK_M
|
| 744 |
+
start_m_idx = start_m * BLOCK_M
|
| 745 |
+
causal_start_idx = seqlen_q - seqlen_k
|
| 746 |
+
if USE_FP8_OUT:
|
| 747 |
+
acc *= o_descale
|
| 748 |
+
acc = tl.clamp(acc, FP8_MIN, FP8_MAX)
|
| 749 |
+
acc = acc.to(Out.type.element_ty)
|
| 750 |
+
if IS_CAUSAL: # noqa: SIM102
|
| 751 |
+
if causal_start_idx > start_m_idx and causal_start_idx < end_m_idx:
|
| 752 |
+
out_mask_boundary = tl.full((BLOCK_DMODEL, ),
|
| 753 |
+
causal_start_idx,
|
| 754 |
+
dtype=tl.int32)
|
| 755 |
+
mask_m_offsets = start_m_idx + tl.arange(0, BLOCK_M)
|
| 756 |
+
out_ptrs_mask = (mask_m_offsets[:, None]
|
| 757 |
+
>= out_mask_boundary[None, :])
|
| 758 |
+
z = tl.zeros((1, ), tl.float32)
|
| 759 |
+
acc = tl.where(out_ptrs_mask, acc, z.to(acc.type.element_ty))
|
| 760 |
+
# write back LSE
|
| 761 |
+
# l_ptrs = L + off_z * HQ * MAX_SEQLENS_Q + off_h_q * MAX_SEQLENS_Q + offs_m
|
| 762 |
+
# If seqlen_q not multiple of BLOCK_M, we need to mask out the last
|
| 763 |
+
# few rows. This is only true for the last M block. For others,
|
| 764 |
+
# overflow_size will be -ve
|
| 765 |
+
# overflow_size = end_m_idx - seqlen_q
|
| 766 |
+
# if overflow_size > 0:
|
| 767 |
+
# boundary = tl.full((BLOCK_M,), BLOCK_M - overflow_size, dtype=tl.int32)
|
| 768 |
+
# # This is a > check because mask being 0 blocks the store.
|
| 769 |
+
# l_ptrs_mask = boundary > tl.arange(0, BLOCK_M)
|
| 770 |
+
# tl.store(l_ptrs, m_i + tl.math.log2(l_i), mask=l_ptrs_mask)
|
| 771 |
+
# else:
|
| 772 |
+
# tl.store(l_ptrs, m_i + tl.math.log2(l_i))
|
| 773 |
+
|
| 774 |
+
# write back O
|
| 775 |
+
o_offset = (off_z * stride_oz + cu_seqlens_q_start * stride_om +
|
| 776 |
+
off_h_q * stride_oh)
|
| 777 |
+
O_block_ptr = tl.make_block_ptr(
|
| 778 |
+
base=Out + o_offset,
|
| 779 |
+
shape=(seqlen_q, ACTUAL_BLOCK_DMODEL),
|
| 780 |
+
strides=(stride_om, stride_on),
|
| 781 |
+
offsets=(start_m * BLOCK_M, 0),
|
| 782 |
+
block_shape=(BLOCK_M, BLOCK_DMODEL),
|
| 783 |
+
order=(1, 0),
|
| 784 |
+
)
|
| 785 |
+
# Need boundary check on this to make sure the padding from the
|
| 786 |
+
# Q and KV tensors in both dims are not part of what we store back.
|
| 787 |
+
# TODO: Do the boundary check optionally.
|
| 788 |
+
tl.store(O_block_ptr, acc, boundary_check=(0, 1))
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def check_args(
|
| 792 |
+
q,
|
| 793 |
+
k,
|
| 794 |
+
v,
|
| 795 |
+
o,
|
| 796 |
+
varlen=True,
|
| 797 |
+
max_seqlens=None,
|
| 798 |
+
cu_seqlens_q=None,
|
| 799 |
+
cu_seqlens_k=None,
|
| 800 |
+
):
|
| 801 |
+
assert q.dim() == k.dim() and q.dim() == v.dim()
|
| 802 |
+
if varlen:
|
| 803 |
+
assert q.dim() == 3
|
| 804 |
+
total_q, nheads_q, head_size = q.shape
|
| 805 |
+
total_k, nheads_k, _ = k.shape
|
| 806 |
+
assert cu_seqlens_q is not None
|
| 807 |
+
assert cu_seqlens_k is not None
|
| 808 |
+
assert len(cu_seqlens_q) == len(cu_seqlens_k)
|
| 809 |
+
else:
|
| 810 |
+
assert q.dim() == 4
|
| 811 |
+
batch, nheads_q, seqlen_q, head_size = q.shape
|
| 812 |
+
_, nheads_k, seqlen_k, _ = k.shape
|
| 813 |
+
assert max_seqlens > 0
|
| 814 |
+
assert k.shape == v.shape
|
| 815 |
+
assert q.shape[-1] == k.shape[-1] and q.shape[-1] == v.shape[-1]
|
| 816 |
+
# TODO: Change assert if we support qkl f8 and v f16
|
| 817 |
+
assert q.dtype == k.dtype and q.dtype == v.dtype
|
| 818 |
+
assert head_size <= 256
|
| 819 |
+
assert o.shape == q.shape
|
| 820 |
+
assert (nheads_q % nheads_k) == 0
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
class _attention(torch.autograd.Function):
|
| 824 |
+
|
| 825 |
+
@staticmethod
|
| 826 |
+
def forward(
|
| 827 |
+
ctx,
|
| 828 |
+
q,
|
| 829 |
+
k,
|
| 830 |
+
v,
|
| 831 |
+
o,
|
| 832 |
+
cu_seqlens_q,
|
| 833 |
+
cu_seqlens_k,
|
| 834 |
+
max_seqlens_q,
|
| 835 |
+
max_seqlens_k,
|
| 836 |
+
causal=False,
|
| 837 |
+
sm_scale=1.0,
|
| 838 |
+
bias=None,
|
| 839 |
+
fp8_scales=None,
|
| 840 |
+
fp8_out_scale=None,
|
| 841 |
+
):
|
| 842 |
+
if fp8_scales is not None:
|
| 843 |
+
use_fp8 = True
|
| 844 |
+
(q_scale, k_scale, v_scale, p_scale) = fp8_scales
|
| 845 |
+
float8 = current_platform.fp8_dtype()
|
| 846 |
+
|
| 847 |
+
def check_and_convert(t, scale):
|
| 848 |
+
if t.dtype != float8:
|
| 849 |
+
descale = 1.0 / scale
|
| 850 |
+
ts = (t * descale).clamp(min=float8_info.min,
|
| 851 |
+
max=float8_info.max)
|
| 852 |
+
return ts.to(float8)
|
| 853 |
+
else:
|
| 854 |
+
return t
|
| 855 |
+
|
| 856 |
+
q = check_and_convert(q, q_scale)
|
| 857 |
+
k = check_and_convert(k, k_scale)
|
| 858 |
+
v = check_and_convert(v, v_scale)
|
| 859 |
+
else:
|
| 860 |
+
use_fp8 = False
|
| 861 |
+
q_scale = k_scale = v_scale = p_scale = 1.0
|
| 862 |
+
|
| 863 |
+
if o is None:
|
| 864 |
+
o = torch.empty_like(q, dtype=v.dtype)
|
| 865 |
+
|
| 866 |
+
check_args(
|
| 867 |
+
q,
|
| 868 |
+
k,
|
| 869 |
+
v,
|
| 870 |
+
o,
|
| 871 |
+
varlen=True,
|
| 872 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 873 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 874 |
+
)
|
| 875 |
+
if True: # varlen
|
| 876 |
+
total_q, nheads_q, head_size = q.shape
|
| 877 |
+
total_k, nheads_k, _ = k.shape
|
| 878 |
+
batch = len(cu_seqlens_q) - 1
|
| 879 |
+
q_strides = (0, q.stride(1), q.stride(0), q.stride(2))
|
| 880 |
+
k_strides = (0, k.stride(1), k.stride(0), k.stride(2))
|
| 881 |
+
v_strides = (0, v.stride(1), v.stride(0), v.stride(2))
|
| 882 |
+
o_strides = (0, o.stride(1), o.stride(0), o.stride(2))
|
| 883 |
+
else:
|
| 884 |
+
batch, seqlen_q, nheads_q, head_size = q.shape
|
| 885 |
+
_, seqlen_k, nheads_k, _ = k.shape
|
| 886 |
+
q_strides = (q.stride(0), q.stride(2), q.stride(1), q.stride(3))
|
| 887 |
+
k_strides = (k.stride(0), k.stride(2), k.stride(1), k.stride(3))
|
| 888 |
+
v_strides = (v.stride(0), v.stride(2), v.stride(1), v.stride(3))
|
| 889 |
+
o_strides = (o.stride(0), o.stride(2), o.stride(1), o.stride(3))
|
| 890 |
+
|
| 891 |
+
# Get closest power of 2 over or equal to 32.
|
| 892 |
+
unpadded_head_dims = {32, 64, 128, 256}
|
| 893 |
+
if head_size not in unpadded_head_dims:
|
| 894 |
+
padded_d_model = None
|
| 895 |
+
for i in unpadded_head_dims:
|
| 896 |
+
if i > head_size:
|
| 897 |
+
padded_d_model = i
|
| 898 |
+
break
|
| 899 |
+
assert padded_d_model is not None
|
| 900 |
+
else:
|
| 901 |
+
padded_d_model = head_size
|
| 902 |
+
|
| 903 |
+
grid = lambda META: (
|
| 904 |
+
triton.cdiv(max_seqlens_q, META["BLOCK_M"]),
|
| 905 |
+
nheads_q,
|
| 906 |
+
batch,
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
encoded_softmax = None
|
| 910 |
+
|
| 911 |
+
# Seed the RNG so we get reproducible results for testing.
|
| 912 |
+
philox_seed = 0x1BF52
|
| 913 |
+
philox_offset = 0x1D4B42
|
| 914 |
+
|
| 915 |
+
if bias is not None:
|
| 916 |
+
bias_strides = (
|
| 917 |
+
bias.stride(0),
|
| 918 |
+
bias.stride(1),
|
| 919 |
+
bias.stride(2),
|
| 920 |
+
bias.stride(3),
|
| 921 |
+
)
|
| 922 |
+
else:
|
| 923 |
+
bias_strides = (0, 0, 0, 0)
|
| 924 |
+
|
| 925 |
+
p_descale = 1.0 / p_scale
|
| 926 |
+
o_descale = 1.0 / fp8_out_scale.item(
|
| 927 |
+
) if fp8_out_scale is not None else 1.0
|
| 928 |
+
|
| 929 |
+
arg_max_seqlens_q = 0 if on_gfx1x() else max_seqlens_q
|
| 930 |
+
arg_max_seqlens_k = 0 if on_gfx1x() else max_seqlens_k
|
| 931 |
+
|
| 932 |
+
attn_fwd[grid](
|
| 933 |
+
q,
|
| 934 |
+
k,
|
| 935 |
+
v,
|
| 936 |
+
bias,
|
| 937 |
+
sm_scale,
|
| 938 |
+
q_scale,
|
| 939 |
+
k_scale,
|
| 940 |
+
v_scale,
|
| 941 |
+
p_scale,
|
| 942 |
+
p_descale,
|
| 943 |
+
o_descale,
|
| 944 |
+
None,
|
| 945 |
+
o,
|
| 946 |
+
*q_strides,
|
| 947 |
+
*k_strides,
|
| 948 |
+
*v_strides,
|
| 949 |
+
*o_strides,
|
| 950 |
+
*bias_strides,
|
| 951 |
+
cu_seqlens_q,
|
| 952 |
+
cu_seqlens_k,
|
| 953 |
+
dropout_p=0.0,
|
| 954 |
+
philox_seed=philox_seed,
|
| 955 |
+
philox_offset_base=philox_offset,
|
| 956 |
+
encoded_softmax=encoded_softmax,
|
| 957 |
+
HQ=nheads_q,
|
| 958 |
+
HK=nheads_k,
|
| 959 |
+
ACTUAL_BLOCK_DMODEL=head_size,
|
| 960 |
+
MAX_SEQLENS_Q=arg_max_seqlens_q,
|
| 961 |
+
MAX_SEQLENS_K=arg_max_seqlens_k,
|
| 962 |
+
IS_CAUSAL=causal,
|
| 963 |
+
VARLEN=True,
|
| 964 |
+
BLOCK_DMODEL=padded_d_model,
|
| 965 |
+
BIAS_TYPE=0 if bias is None else 1,
|
| 966 |
+
ENABLE_DROPOUT=False,
|
| 967 |
+
RETURN_ENCODED_SOFTMAX=False,
|
| 968 |
+
USE_FP8=use_fp8,
|
| 969 |
+
USE_FP8_OUT=fp8_out_scale is not None,
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
ctx.grid = grid
|
| 973 |
+
ctx.sm_scale = sm_scale
|
| 974 |
+
ctx.BLOCK_DMODEL = head_size
|
| 975 |
+
ctx.causal = causal
|
| 976 |
+
ctx.dropout_p = 0.0
|
| 977 |
+
ctx.philox_seed = philox_seed
|
| 978 |
+
ctx.philox_offset = philox_offset
|
| 979 |
+
ctx.encoded_softmax = encoded_softmax
|
| 980 |
+
ctx.return_encoded_softmax = False
|
| 981 |
+
return o, encoded_softmax
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
triton_attention = _attention.apply
|