| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import math |
| 5 | from collections.abc import Callable |
| 6 | |
| 7 | import torch |
| 8 | import torch.nn.functional as F |
| 9 | from einops import rearrange |
| 10 | |
| 11 | from vllm.config import get_current_vllm_config |
| 12 | from vllm.forward_context import ForwardContext, get_forward_context |
| 13 | from vllm.model_executor.custom_op import PluggableLayer |
| 14 | from vllm.model_executor.layers.lightning_attn import ( |
| 15 | lightning_attention, |
| 16 | linear_decode_forward_triton, |
| 17 | ) |
| 18 | from vllm.model_executor.layers.linear import ColumnParallelLinear, RowParallelLinear |
| 19 | from vllm.model_executor.layers.mamba.linear.base import LinearAttention |
| 20 | from vllm.model_executor.layers.minimax_rms_norm import MiniMaxText01RMSNormTP |
| 21 | from vllm.utils.torch_utils import direct_register_custom_op |
| 22 | from vllm.v1.attention.backend import AttentionMetadata |
| 23 | from vllm.v1.attention.backends.linear_attn import LinearAttentionMetadata |
| 24 | |
| 25 | |
| 26 | def clear_linear_attention_cache_for_new_sequences( |
| 27 | kv_cache: torch.Tensor, |
| 28 | state_indices_tensor: torch.Tensor, |
| 29 | attn_metadata: LinearAttentionMetadata, |
| 30 | ) -> None: |
| 31 | num_prefills = getattr(attn_metadata, "num_prefills", 0) |
| 32 | if num_prefills <= 0: |
| 33 | return |
| 34 | |
| 35 | num_decode_tokens = getattr(attn_metadata, "num_decode_tokens", 0) |
| 36 | for prefill_idx in range(num_prefills): |
| 37 | q_start = attn_metadata.query_start_loc[num_decode_tokens + prefill_idx] |
| 38 | q_end = attn_metadata.query_start_loc[num_decode_tokens + prefill_idx + 1] |
| 39 | query_len = q_end - q_start |
| 40 | context_len = ( |
| 41 | attn_metadata.seq_lens[num_decode_tokens + prefill_idx] - query_len |
| 42 | ) |
| 43 | if context_len == 0: |
| 44 | block_to_clear = state_indices_tensor[num_decode_tokens + prefill_idx] |
| 45 | kv_cache[block_to_clear, ...] = 0 |
| 46 | |
| 47 | |
| 48 | def linear_attention_decode( |
| 49 | q: torch.Tensor, |
| 50 | k: torch.Tensor, |
| 51 | v: torch.Tensor, |
| 52 | kv_cache: torch.Tensor, |
| 53 | slope_rate: torch.Tensor, |
| 54 | state_indices_tensor: torch.Tensor, |
| 55 | q_start: int = 0, |
| 56 | q_end: int | None = None, |
| 57 | slot_start: int = 0, |
| 58 | slot_end: int | None = None, |
| 59 | block_size: int = 32, |
| 60 | ) -> torch.Tensor: |
| 61 | q = q[q_start:q_end].unsqueeze(2).contiguous() |
| 62 | k = k[q_start:q_end].unsqueeze(2).contiguous() |
| 63 | v = v[q_start:q_end].unsqueeze(2).contiguous() |
| 64 | slot_id = state_indices_tensor[slot_start:slot_end] |
| 65 | return linear_decode_forward_triton( |
| 66 | q, k, v, kv_cache, slope_rate, slot_id, block_size |
| 67 | ) |
| 68 | |
| 69 | |
| 70 | def linear_attention_prefill_and_mix( |
| 71 | q: torch.Tensor, |
| 72 | k: torch.Tensor, |
| 73 | v: torch.Tensor, |
| 74 | kv_cache: torch.Tensor, |
| 75 | state_indices_tensor: torch.Tensor, |
| 76 | attn_metadata: LinearAttentionMetadata, |
| 77 | slope_rate: torch.Tensor, |
| 78 | block_size: int, |
| 79 | decode_fn: Callable[..., torch.Tensor], |
| 80 | prefix_fn: Callable[..., torch.Tensor], |
| 81 | layer_idx: int | None = None, |
| 82 | ) -> torch.Tensor: |
| 83 | hidden = [] |
| 84 | for _prefill_idx in range(getattr(attn_metadata, "num_prefills", 0)): |
| 85 | if _prefill_idx >= len(attn_metadata.query_start_loc): |
| 86 | break |
| 87 | if _prefill_idx >= len(state_indices_tensor): |
| 88 | break |
| 89 | offset = attn_metadata.num_decode_tokens |
| 90 | _start = attn_metadata.query_start_loc[offset + _prefill_idx] |
| 91 | _end = attn_metadata.query_start_loc[offset + _prefill_idx + 1] |
| 92 | slot_id = state_indices_tensor[offset + _prefill_idx] |
| 93 | qs = q[_start:_end].transpose(0, 1).contiguous() |
| 94 | ks = k[_start:_end].transpose(0, 1).contiguous() |
| 95 | vs = v[_start:_end].transpose(0, 1).contiguous() |
| 96 | slice_layer_cache = kv_cache[slot_id, ...] |
| 97 | out_slice = prefix_fn( |
| 98 | qs, |
| 99 | ks, |
| 100 | vs, |
| 101 | slice_layer_cache, |
| 102 | slope_rate, |
| 103 | block_size, |
| 104 | layer_idx=layer_idx, |
| 105 | ) |
| 106 | hidden.append(out_slice.contiguous()) |
| 107 | |
| 108 | if attn_metadata.num_decode_tokens > 0: |
| 109 | hidden_decode = decode_fn( |
| 110 | q, k, v, kv_cache, state_indices_tensor, attn_metadata |
| 111 | ) |
| 112 | hidden.insert(0, hidden_decode) |
| 113 | |
| 114 | if not hidden: |
| 115 | return torch.empty((0, q.size(-1)), device=q.device, dtype=q.dtype) |
| 116 | |
| 117 | hidden = torch.concat(hidden, dim=0).contiguous() |
| 118 | return hidden |
| 119 | |
| 120 | |
| 121 | class MiniMaxText01LinearKernel: |
| 122 | @staticmethod |
| 123 | def jit_linear_forward_prefix( |
| 124 | q: torch.Tensor, |
| 125 | k: torch.Tensor, |
| 126 | v: torch.Tensor, |
| 127 | kv_caches: torch.Tensor, |
| 128 | slope_rate: torch.Tensor, |
| 129 | block_size: int, |
| 130 | layer_idx: int | None = None, |
| 131 | **kwargs, |
| 132 | ) -> torch.Tensor: |
| 133 | slope_rate = slope_rate.to(torch.float32) |
| 134 | should_pad_dim = q.dim() == 3 |
| 135 | if should_pad_dim: |
| 136 | q = q.unsqueeze(0) |
| 137 | k = k.unsqueeze(0) |
| 138 | v = v.unsqueeze(0) |
| 139 | b, h, n, d = q.shape |
| 140 | e = d |
| 141 | kv_history = kv_caches.reshape(1, h, d, e).contiguous() |
| 142 | output, kv_history = lightning_attention( |
| 143 | q, k, v, slope_rate, block_size=block_size, kv_history=kv_history |
| 144 | ) |
| 145 | kv_caches.copy_(kv_history[:, :, -1, :, :].reshape(h, d, e)) |
| 146 | assert output.shape[0] == 1, "batch size must be 1" |
| 147 | return rearrange(output.squeeze(0), "h n d -> n (h d)") |
| 148 | |
| 149 | |
| 150 | @PluggableLayer.register("minimax_text_01_attention") |
| 151 | class MiniMaxText01LinearAttention(LinearAttention): |
| 152 | def __init__( |
| 153 | self, |
| 154 | config, |
| 155 | vllm_config, |
| 156 | prefix: str = "linear_attn", |
| 157 | ) -> None: |
| 158 | super().__init__(config, vllm_config, prefix) |
| 159 | |
| 160 | self.tp_heads = self.num_heads // self.tp_size |
| 161 | self.qkv_size = self.num_heads * self.head_dim |
| 162 | self.tp_hidden = self.head_dim * self.tp_heads |
| 163 | |
| 164 | self.qkv_proj = ColumnParallelLinear( |
| 165 | self.hidden_size, |
| 166 | self.hidden_inner_size * 3, |
| 167 | bias=False, |
| 168 | quant_config=self.quant_config, |
| 169 | prefix=f"{prefix}.qkv_proj", |
| 170 | ) |
| 171 | self.output_gate = ColumnParallelLinear( |
| 172 | self.hidden_size, |
| 173 | self.hidden_inner_size, |
| 174 | bias=False, |
| 175 | quant_config=self.quant_config, |
| 176 | prefix=f"{prefix}.output_gate", |
| 177 | ) |
| 178 | self.out_proj = RowParallelLinear( |
| 179 | self.hidden_inner_size, |
| 180 | self.hidden_size, |
| 181 | bias=False, |
| 182 | quant_config=self.quant_config, |
| 183 | prefix=f"{prefix}.out_proj", |
| 184 | ) |
| 185 | self.norm = MiniMaxText01RMSNormTP( |
| 186 | self.hidden_inner_size, |
| 187 | eps=1e-5, |
| 188 | ) |
| 189 | |
| 190 | slope_rate = MiniMaxText01LinearAttention._build_slope_tensor(self.num_heads) |
| 191 | if self.num_hidden_layers <= 1: |
| 192 | self.slope_rate = slope_rate * (1 + 1e-5) |
| 193 | else: |
| 194 | self.slope_rate = slope_rate * ( |
| 195 | 1 - self.layer_idx / (self.num_hidden_layers - 1) + 1e-5 |
| 196 | ) |
| 197 | self.tp_slope = self.slope_rate[ |
| 198 | self.tp_rank * self.tp_heads : (self.tp_rank + 1) * self.tp_heads |
| 199 | ].contiguous() |
| 200 | |
| 201 | compilation_config = get_current_vllm_config().compilation_config |
| 202 | if prefix in compilation_config.static_forward_context: |
| 203 | raise ValueError(f"Duplicate layer name: {prefix}") |
| 204 | compilation_config.static_forward_context[prefix] = self |
| 205 | |
| 206 | @staticmethod |
| 207 | def weight_direct_load(param: torch.Tensor, loaded_weight: torch.Tensor) -> None: |
| 208 | assert param.size() == loaded_weight.size() |
| 209 | param.data.copy_(loaded_weight) |
| 210 | return |
| 211 | |
| 212 | @staticmethod |
| 213 | def _build_slope_tensor(n_attention_heads: int): |
| 214 | def get_slopes(n): |
| 215 | def get_slopes_power_of_2(n): |
| 216 | start = 2 ** (-(2 ** -(math.log2(n) - 3))) |
| 217 | ratio = start |
| 218 | return [start * ratio**i for i in range(n)] |
| 219 | |
| 220 | if math.log2(n).is_integer(): |
| 221 | return get_slopes_power_of_2(n) |
| 222 | else: |
| 223 | closest_power_of_2 = 2 ** math.floor(math.log2(n)) |
| 224 | return ( |
| 225 | get_slopes_power_of_2(closest_power_of_2) |
| 226 | + get_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2] |
| 227 | ) |
| 228 | |
| 229 | slopes = torch.tensor( |
| 230 | get_slopes(n_attention_heads), dtype=torch.float32 |
| 231 | ).reshape(n_attention_heads, 1, 1) |
| 232 | return slopes |
| 233 | |
| 234 | def _prefill_and_mix_infer( |
| 235 | self, q, k, v, kv_cache, state_indices_tensor, attn_metadata |
| 236 | ): |
| 237 | return linear_attention_prefill_and_mix( |
| 238 | q=q, |
| 239 | k=k, |
| 240 | v=v, |
| 241 | kv_cache=kv_cache, |
| 242 | state_indices_tensor=state_indices_tensor, |
| 243 | attn_metadata=attn_metadata, |
| 244 | slope_rate=self.tp_slope, |
| 245 | block_size=self.BLOCK, |
| 246 | decode_fn=self._decode_infer, |
| 247 | prefix_fn=MiniMaxText01LinearKernel.jit_linear_forward_prefix, |
| 248 | layer_idx=self.layer_idx, |
| 249 | ) |
| 250 | |
| 251 | def _decode_infer(self, q, k, v, kv_cache, state_indices_tensor, attn_metadata): |
| 252 | hidden = linear_attention_decode( |
| 253 | q, |
| 254 | k, |
| 255 | v, |
| 256 | kv_cache, |
| 257 | self.tp_slope, |
| 258 | state_indices_tensor, |
| 259 | q_start=0, |
| 260 | q_end=attn_metadata.num_decode_tokens, |
| 261 | slot_start=0, |
| 262 | slot_end=attn_metadata.num_decodes, |
| 263 | block_size=32, |
| 264 | ) |
| 265 | return hidden |
| 266 | |
| 267 | def forward( |
| 268 | self, hidden_states: torch.Tensor, output: torch.Tensor, positions: torch.Tensor |
| 269 | ) -> None: |
| 270 | torch.ops.vllm.linear_attention( |
| 271 | hidden_states, |
| 272 | output, |
| 273 | positions, |
| 274 | self.prefix, |
| 275 | ) |
| 276 | |
| 277 | def _forward( |
| 278 | self, hidden_states: torch.Tensor, output: torch.Tensor, positions: torch.Tensor |
| 279 | ) -> None: |
| 280 | forward_context = get_forward_context() |
| 281 | attn_metadata_raw = forward_context.attn_metadata |
| 282 | attn_metadata: AttentionMetadata | None = None |
| 283 | if attn_metadata_raw is not None: |
| 284 | assert isinstance(attn_metadata_raw, dict) |
| 285 | attn_metadata = attn_metadata_raw.get(self.prefix) |
| 286 | if attn_metadata is not None: |
| 287 | assert isinstance(attn_metadata, LinearAttentionMetadata) |
| 288 | num_actual_tokens = ( |
| 289 | attn_metadata.num_prefill_tokens + attn_metadata.num_decode_tokens |
| 290 | ) |
| 291 | else: |
| 292 | num_actual_tokens = hidden_states.shape[0] |
| 293 | |
| 294 | qkv, _ = self.qkv_proj(hidden_states[:num_actual_tokens]) |
| 295 | qkv32 = qkv.to(torch.float32) |
| 296 | qkvact = torch.nn.functional.silu(qkv32) |
| 297 | qkvact = qkvact.view((qkv.shape[0], self.tp_heads, -1)) |
| 298 | q, k, v = torch.split(qkvact, [self.head_dim] * 3, dim=-1) |
| 299 | if attn_metadata is not None: |
| 300 | kv_cache = self.kv_cache[0] |
| 301 | state_indices_tensor = attn_metadata.state_indices_tensor |
| 302 | clear_linear_attention_cache_for_new_sequences( |
| 303 | kv_cache, state_indices_tensor, attn_metadata |
| 304 | ) |
| 305 | |
| 306 | decode_only = getattr(attn_metadata, "num_prefills", 0) == 0 |
| 307 | if attn_metadata is None: |
| 308 | hidden = torch.empty( |
| 309 | (q.shape[0], q.shape[1] * q.shape[2]), device=q.device, dtype=q.dtype |
| 310 | ) |
| 311 | else: |
| 312 | if not decode_only: |
| 313 | hidden = self._prefill_and_mix_infer( |
| 314 | q, k, v, kv_cache, state_indices_tensor, attn_metadata |
| 315 | ) |
| 316 | else: |
| 317 | hidden = self._decode_infer( |
| 318 | q, k, v, kv_cache, state_indices_tensor, attn_metadata |
| 319 | ) |
| 320 | hidden = self.norm._forward(hidden) |
| 321 | gate, _ = self.output_gate(hidden_states[:num_actual_tokens]) |
| 322 | hidden = F.sigmoid(gate) * hidden |
| 323 | hidden = hidden.to(hidden_states.dtype) |
| 324 | |
| 325 | output[:num_actual_tokens], _ = self.out_proj(hidden) |
| 326 | |
| 327 | |
| 328 | def linear_attention( |
| 329 | hidden_states: torch.Tensor, |
| 330 | output: torch.Tensor, |
| 331 | positions: torch.Tensor, |
| 332 | layer_name: str, |
| 333 | ) -> None: |
| 334 | forward_context: ForwardContext = get_forward_context() |
| 335 | self = forward_context.no_compile_layers[layer_name] |
| 336 | self._forward(hidden_states=hidden_states, output=output, positions=positions) |
| 337 | |
| 338 | |
| 339 | direct_register_custom_op( |
| 340 | op_name="linear_attention", |
| 341 | op_func=linear_attention, |
| 342 | mutates_args=["output"], |
| 343 | ) |