| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | import torch |
| 4 | from transformers import PreTrainedConfig |
| 5 | |
| 6 | from vllm.config import ( |
| 7 | VllmConfig, |
| 8 | ) |
| 9 | from vllm.distributed.parallel_state import ( |
| 10 | get_tensor_model_parallel_rank, |
| 11 | get_tensor_model_parallel_world_size, |
| 12 | ) |
| 13 | from vllm.model_executor.custom_op import PluggableLayer |
| 14 | from vllm.model_executor.layers.mamba.abstract import MambaBase |
| 15 | from vllm.model_executor.layers.mamba.mamba_utils import ( |
| 16 | MambaStateDtypeCalculator, |
| 17 | MambaStateShapeCalculator, |
| 18 | ) |
| 19 | from vllm.model_executor.models.utils import extract_layer_index |
| 20 | from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum |
| 21 | |
| 22 | |
| 23 | class LinearAttention(PluggableLayer, MambaBase): |
| 24 | """Base class for Linear attention layer.""" |
| 25 | |
| 26 | def __init__( |
| 27 | self, config: PreTrainedConfig, vllm_config: VllmConfig, prefix: str = "" |
| 28 | ): |
| 29 | super().__init__() |
| 30 | self.layer_idx = extract_layer_index(prefix) |
| 31 | self.prefix = prefix |
| 32 | self.model_config = vllm_config.model_config |
| 33 | self.cache_config = vllm_config.cache_config |
| 34 | self.quant_config = vllm_config.quant_config |
| 35 | |
| 36 | self.BLOCK = getattr(config, "block", 256) |
| 37 | self.hidden_size = config.hidden_size |
| 38 | self.num_heads = config.num_attention_heads |
| 39 | self.num_hidden_layers = config.num_hidden_layers |
| 40 | self.head_dim = ( |
| 41 | config.head_dim |
| 42 | if hasattr(config, "head_dim") |
| 43 | else config.hidden_size // self.num_heads |
| 44 | ) |
| 45 | self.hidden_inner_size = self.head_dim * self.num_heads |
| 46 | |
| 47 | self.tp_size = get_tensor_model_parallel_world_size() |
| 48 | self.tp_rank = get_tensor_model_parallel_rank() |
| 49 | assert self.num_heads % self.tp_size == 0 |
| 50 | |
| 51 | @property |
| 52 | def mamba_type(self) -> MambaAttentionBackendEnum: |
| 53 | return MambaAttentionBackendEnum.LINEAR |
| 54 | |
| 55 | def get_state_dtype(self) -> tuple[torch.dtype]: |
| 56 | assert self.model_config is not None |
| 57 | assert self.cache_config is not None |
| 58 | return MambaStateDtypeCalculator.linear_attention_state_dtype( |
| 59 | self.model_config.dtype, |
| 60 | self.cache_config.mamba_cache_dtype, |
| 61 | ) |
| 62 | |
| 63 | def get_state_shape(self) -> tuple[tuple[int, int, int], ...]: |
| 64 | return MambaStateShapeCalculator.linear_attention_state_shape( |
| 65 | num_heads=self.num_heads, tp_size=self.tp_size, head_dim=self.head_dim |
| 66 | ) |