|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | +"""Utility functions for attention-related v1 tests.""" |
| 4 | + |
| 5 | +from dataclasses import dataclass |
| 6 | + |
| 7 | +import pytest |
| 8 | +import torch |
| 9 | + |
| 10 | +from vllm.config import VllmConfig |
| 11 | +from vllm.v1.attention.backends.utils import CommonAttentionMetadata |
| 12 | +from vllm.v1.kv_cache_interface import FullAttentionSpec |
| 13 | + |
| 14 | + |
| 15 | +@dataclass |
| 16 | +class BatchSpec: |
| 17 | + """Specification for a batch configuration (workload shape only).""" |
| 18 | + batch_size: int |
| 19 | + seq_lens: list[int] |
| 20 | + query_lens: list[int] |
| 21 | + |
| 22 | + name: str = "unnamed" |
| 23 | + |
| 24 | + def __post_init__(self): |
| 25 | + assert len(self.seq_lens) == self.batch_size |
| 26 | + assert len(self.query_lens) == self.batch_size |
| 27 | + |
| 28 | + def compute_num_tokens(self): |
| 29 | + return sum(self.seq_lens) |
| 30 | + |
| 31 | + |
| 32 | +def create_common_attn_metadata( |
| 33 | + batch_spec: BatchSpec, |
| 34 | + block_size: int, |
| 35 | + device: torch.device, |
| 36 | + max_block_idx: int = 1000) -> CommonAttentionMetadata: |
| 37 | + """Create CommonAttentionMetadata from a BatchSpec and ModelParams.""" |
| 38 | + # Create query start locations |
| 39 | + query_start_loc = torch.zeros(batch_spec.batch_size + 1, |
| 40 | + dtype=torch.int32, |
| 41 | + device=device) |
| 42 | + query_start_loc[1:] = torch.tensor(batch_spec.query_lens, |
| 43 | + dtype=torch.int32, |
| 44 | + device=device).cumsum(0) |
| 45 | + query_start_loc_cpu = query_start_loc.cpu() |
| 46 | + num_tokens = batch_spec.compute_num_tokens() |
| 47 | + |
| 48 | + # Create sequence lengths |
| 49 | + seq_lens = torch.tensor(batch_spec.seq_lens, |
| 50 | + dtype=torch.int32, |
| 51 | + device=device) |
| 52 | + seq_lens_cpu = seq_lens.cpu() |
| 53 | + |
| 54 | + # Create computed tokens (assume all tokens are computed for simplicity) |
| 55 | + num_computed_tokens_cpu = seq_lens_cpu.clone() |
| 56 | + |
| 57 | + # Create block table (random for testing) |
| 58 | + max_blocks = max(batch_spec.seq_lens) // block_size + 1 |
| 59 | + block_table_tensor = torch.randint(0, |
| 60 | + max_block_idx, |
| 61 | + (batch_spec.batch_size, max_blocks), |
| 62 | + dtype=torch.int32, |
| 63 | + device=device) |
| 64 | + |
| 65 | + # Create slot mapping |
| 66 | + slot_mapping = torch.randint(0, |
| 67 | + max_block_idx, (num_tokens, ), |
| 68 | + dtype=torch.int64, |
| 69 | + device=device) |
| 70 | + |
| 71 | + # Calculate max query length |
| 72 | + max_query_len = max(batch_spec.query_lens) |
| 73 | + |
| 74 | + return CommonAttentionMetadata( |
| 75 | + query_start_loc=query_start_loc, |
| 76 | + query_start_loc_cpu=query_start_loc_cpu, |
| 77 | + seq_lens=seq_lens, |
| 78 | + seq_lens_cpu=seq_lens_cpu, |
| 79 | + num_computed_tokens_cpu=num_computed_tokens_cpu, |
| 80 | + num_reqs=batch_spec.batch_size, |
| 81 | + num_actual_tokens=num_tokens, |
| 82 | + max_query_len=max_query_len, |
| 83 | + block_table_tensor=block_table_tensor, |
| 84 | + slot_mapping=slot_mapping, |
| 85 | + ) |
| 86 | + |
| 87 | + |
| 88 | +def get_attention_backend(backend_name: str): |
| 89 | + """Set up attention backend classes for testing. |
| 90 | + |
| 91 | + Args: |
| 92 | + backend_name: Name of the backend ("flash_attn", "flashinfer", etc.) |
| 93 | + vllm_config: VllmConfig instance |
| 94 | + |
| 95 | + Returns: |
| 96 | + Tuple of (backend_builder_class, backend_impl_class) |
| 97 | + """ |
| 98 | + backend_map = { |
| 99 | + "flash_attn": |
| 100 | + ("vllm.v1.attention.backends.flash_attn", "FlashAttentionBackend"), |
| 101 | + "flashinfer": |
| 102 | + ("vllm.v1.attention.backends.flashinfer", "FlashInferBackend"), |
| 103 | + "flex_attention": |
| 104 | + ("vllm.v1.attention.backends.flex_attention", "FlexAttentionBackend"), |
| 105 | + } |
| 106 | + |
| 107 | + if backend_name not in backend_map: |
| 108 | + raise ValueError(f"Unknown backend: {backend_name}") |
| 109 | + |
| 110 | + module_name, backend_class_name = backend_map[backend_name] |
| 111 | + |
| 112 | + try: |
| 113 | + import importlib |
| 114 | + module = importlib.import_module(module_name) |
| 115 | + backend_class = getattr(module, backend_class_name) |
| 116 | + return backend_class.get_builder_cls(), backend_class.get_impl_cls() |
| 117 | + except ImportError as e: |
| 118 | + pytest.skip(f"{backend_name} not available: {e}") |
| 119 | + |
| 120 | + |
| 121 | +def create_standard_kv_cache_spec( |
| 122 | + vllm_config: VllmConfig) -> FullAttentionSpec: |
| 123 | + """Create a FullAttentionSpec from ModelParams only.""" |
| 124 | + return FullAttentionSpec( |
| 125 | + block_size=vllm_config.cache_config.block_size, |
| 126 | + num_kv_heads=vllm_config.model_config.get_num_attention_heads( |
| 127 | + vllm_config.parallel_config), |
| 128 | + head_size=vllm_config.model_config.get_head_size(), |
| 129 | + dtype=vllm_config.model_config.dtype, |
| 130 | + use_mla=vllm_config.model_config.use_mla, |
| 131 | + sliding_window=vllm_config.model_config.get_sliding_window(), |
| 132 | + ) |
0 commit comments