torch_sdpa.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. """ Attention layer with torch scaled_dot_product_attention
  2. and PagedAttention."""
  3. from dataclasses import dataclass
  4. from typing import Any, Dict, List, Optional, Tuple, Type
  5. import torch
  6. from torch.nn.functional import scaled_dot_product_attention
  7. from aphrodite.attention.backends.abstract import (AttentionBackend,
  8. AttentionImpl,
  9. AttentionMetadata,
  10. AttentionType)
  11. from aphrodite.attention.backends.utils import CommonMetadataBuilder
  12. from aphrodite.attention.ops.paged_attn import PagedAttentionMetadata
  13. from aphrodite.common.utils import is_cpu
  14. if is_cpu():
  15. try:
  16. from aphrodite.attention.ops.ipex_attn import PagedAttention
  17. except ImportError:
  18. from aphrodite.attention.ops.paged_attn import PagedAttention
  19. else:
  20. from aphrodite.attention.ops.paged_attn import PagedAttention
  21. class TorchSDPABackend(AttentionBackend):
  22. @staticmethod
  23. def get_name() -> str:
  24. return "torch-sdpa"
  25. @staticmethod
  26. def get_impl_cls() -> Type["TorchSDPABackendImpl"]:
  27. return TorchSDPABackendImpl
  28. @staticmethod
  29. def get_metadata_cls() -> Type["AttentionMetadata"]:
  30. return TorchSDPAMetadata
  31. @staticmethod
  32. def get_builder_cls() -> Type["TorchSDPAMetadataBuilder"]:
  33. return TorchSDPAMetadataBuilder
  34. @staticmethod
  35. def get_kv_cache_shape(
  36. num_blocks: int,
  37. block_size: int,
  38. num_kv_heads: int,
  39. head_size: int,
  40. ) -> Tuple[int, ...]:
  41. return PagedAttention.get_kv_cache_shape(num_blocks, block_size,
  42. num_kv_heads, head_size)
  43. @staticmethod
  44. def swap_blocks(
  45. src_kv_cache: torch.Tensor,
  46. dst_kv_cache: torch.Tensor,
  47. src_to_dst: torch.Tensor,
  48. ) -> None:
  49. PagedAttention.swap_blocks(src_kv_cache, dst_kv_cache, src_to_dst)
  50. @staticmethod
  51. def copy_blocks(
  52. kv_caches: List[torch.Tensor],
  53. src_to_dists: torch.Tensor,
  54. ) -> None:
  55. PagedAttention.copy_blocks(kv_caches, src_to_dists)
  56. @dataclass
  57. class TorchSDPAMetadata(AttentionMetadata, PagedAttentionMetadata):
  58. """Metadata for TorchSDPABackend.
  59. """
  60. # Currently, input sequences can only contain all prompts
  61. # or all decoding. True if all sequences are prompts.
  62. is_prompt: bool
  63. slot_mapping: torch.Tensor
  64. seq_lens: Optional[List[int]]
  65. def __post_init__(self):
  66. # Set during the execution of the first attention op.
  67. # It is a list because it is needed to set per prompt
  68. # when alibi slopes is used. It is because of the limitation
  69. # from xformer API.
  70. # will not appear in the __repr__ and __init__
  71. self.attn_bias: Optional[List[torch.Tensor]] = None
  72. @property
  73. def prefill_metadata(self) -> Optional["TorchSDPAMetadata"]:
  74. # Currently chunked prefill is not supported
  75. if self.num_decode_tokens == 0:
  76. assert self.num_prefills > 0
  77. return self
  78. return None
  79. @property
  80. def decode_metadata(self) -> Optional["TorchSDPAMetadata"]:
  81. # Currently chunked prefill is not supported
  82. if self.num_prefills > 0:
  83. assert self.num_decode_tokens == 0
  84. return None
  85. return self
  86. class TorchSDPAMetadataBuilder(CommonMetadataBuilder[TorchSDPAMetadata]):
  87. _metadata_cls = TorchSDPAMetadata
  88. class TorchSDPABackendImpl(AttentionImpl[TorchSDPAMetadata]):
  89. def __init__(
  90. self,
  91. num_heads: int,
  92. head_size: int,
  93. scale: float,
  94. num_kv_heads: int,
  95. alibi_slopes: Optional[List[float]],
  96. sliding_window: Optional[int],
  97. kv_cache_dtype: str,
  98. blocksparse_params: Optional[Dict[str, Any]] = None,
  99. logits_soft_cap: Optional[float] = None,
  100. ) -> None:
  101. if blocksparse_params is not None:
  102. raise ValueError(
  103. "Torch SPDA does not support block-sparse attention.")
  104. if logits_soft_cap is not None:
  105. raise ValueError("Torch SPDA does not support logits soft cap.")
  106. self.num_heads = num_heads
  107. self.head_size = head_size
  108. self.scale = float(scale)
  109. self.num_kv_heads = num_kv_heads
  110. if alibi_slopes is not None:
  111. alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
  112. self.alibi_slopes = alibi_slopes
  113. self.sliding_window = sliding_window
  114. self.kv_cache_dtype = kv_cache_dtype
  115. assert self.num_heads % self.num_kv_heads == 0
  116. self.num_queries_per_kv = self.num_heads // self.num_kv_heads
  117. self.need_mask = (self.alibi_slopes is not None
  118. or self.sliding_window is not None)
  119. supported_head_sizes = PagedAttention.get_supported_head_sizes()
  120. if head_size not in supported_head_sizes:
  121. raise ValueError(
  122. f"Head size {head_size} is not supported by PagedAttention. "
  123. f"Supported head sizes are: {supported_head_sizes}.")
  124. if kv_cache_dtype != "auto":
  125. raise NotImplementedError(
  126. "Torch SDPA backend does not support FP8 KV cache. "
  127. "Please use xFormers backend instead.")
  128. def forward(
  129. self,
  130. query: torch.Tensor,
  131. key: torch.Tensor,
  132. value: torch.Tensor,
  133. kv_cache: Optional[torch.Tensor],
  134. attn_metadata: TorchSDPAMetadata, # type: ignore
  135. k_scale: float = 1.0,
  136. v_scale: float = 1.0,
  137. attn_type: AttentionType = AttentionType.DECODER,
  138. ) -> torch.Tensor:
  139. """Forward pass with torch SDPA and PagedAttention.
  140. Args:
  141. query: shape = [num_tokens, num_heads * head_size]
  142. key: shape = [num_tokens, num_kv_heads * head_size]
  143. value: shape = [num_tokens, num_kv_heads * head_size]
  144. kv_cache = [2, num_blocks, block_size * num_kv_heads * head_size]
  145. attn_metadata: Metadata for attention.
  146. Returns:
  147. shape = [num_tokens, num_heads * head_size]
  148. """
  149. if attn_type != AttentionType.DECODER:
  150. raise NotImplementedError("Encoder self-attention and "
  151. "encoder/decoder cross-attention "
  152. "are not implemented for "
  153. "TorchSDPABackendImpl")
  154. assert k_scale == 1.0 and v_scale == 1.0
  155. num_tokens, hidden_size = query.shape
  156. # Reshape the query, key, and value tensors.
  157. query = query.view(-1, self.num_heads, self.head_size)
  158. key = key.view(-1, self.num_kv_heads, self.head_size)
  159. value = value.view(-1, self.num_kv_heads, self.head_size)
  160. if kv_cache is not None:
  161. key_cache, value_cache = PagedAttention.split_kv_cache(
  162. kv_cache, self.num_kv_heads, self.head_size)
  163. PagedAttention.write_to_paged_cache(key, value, key_cache,
  164. value_cache,
  165. attn_metadata.slot_mapping,
  166. self.kv_cache_dtype, k_scale,
  167. v_scale)
  168. if attn_metadata.is_prompt:
  169. assert attn_metadata.seq_lens is not None
  170. if (kv_cache is None or attn_metadata.block_tables.numel() == 0):
  171. if self.num_kv_heads != self.num_heads:
  172. key = key.repeat_interleave(self.num_queries_per_kv, dim=1)
  173. value = value.repeat_interleave(self.num_queries_per_kv,
  174. dim=1)
  175. if attn_metadata.attn_bias is None:
  176. if self.alibi_slopes is not None:
  177. att_masks = _make_alibi_bias(
  178. self.alibi_slopes, query.dtype,
  179. attn_metadata.seq_lens) # type: ignore
  180. elif self.sliding_window is not None:
  181. att_masks = _make_sliding_window_bias(
  182. attn_metadata.seq_lens, self.sliding_window,
  183. query.dtype) # type: ignore
  184. else:
  185. att_masks = [None] * len(attn_metadata.seq_lens)
  186. attn_metadata.attn_bias = att_masks
  187. query = query.movedim(0, query.dim() - 2)
  188. key = key.movedim(0, key.dim() - 2)
  189. value = value.movedim(0, value.dim() - 2)
  190. start = 0
  191. output = torch.empty(
  192. (num_tokens, self.num_heads, self.head_size),
  193. dtype=query.dtype)
  194. for seq_len, mask in zip(attn_metadata.seq_lens,
  195. attn_metadata.attn_bias):
  196. end = start + seq_len
  197. sub_out = scaled_dot_product_attention(
  198. query[None, :, start:end, :],
  199. key[None, :, start:end, :],
  200. value[None, :, start:end, :],
  201. attn_mask=mask,
  202. dropout_p=0.0,
  203. is_causal=not self.need_mask,
  204. scale=self.scale).squeeze(0).movedim(
  205. query.dim() - 2, 0)
  206. output[start:end, :, :] = sub_out
  207. start = end
  208. else:
  209. # prefix-enabled attention
  210. raise RuntimeError(
  211. "Torch SDPA backend doesn't support prefix decoding.")
  212. else:
  213. # Decoding run.
  214. output = PagedAttention.forward_decode(
  215. query,
  216. key_cache,
  217. value_cache,
  218. attn_metadata.block_tables,
  219. attn_metadata.seq_lens_tensor,
  220. attn_metadata.max_decode_seq_len,
  221. self.kv_cache_dtype,
  222. self.num_kv_heads,
  223. self.scale,
  224. self.alibi_slopes,
  225. k_scale,
  226. v_scale,
  227. )
  228. # Reshape the output tensor.
  229. return output.view(-1, self.num_heads * self.head_size)
  230. def _make_alibi_bias(
  231. alibi_slopes: torch.Tensor,
  232. dtype: torch.dtype,
  233. seq_lens: List[int],
  234. ) -> List[torch.Tensor]:
  235. attn_biases = []
  236. for seq_len in seq_lens:
  237. bias = torch.arange(seq_len, dtype=dtype)
  238. # NOTE: HF uses
  239. # `bias = bias[None, :].repeat(seq_len, 1)`
  240. # here. We find that both biases give the same results, but
  241. # the bias below more accurately follows the original ALiBi
  242. # paper.
  243. bias = bias[None, :] - bias[:, None]
  244. num_heads = alibi_slopes.shape[0]
  245. bias = bias[None, :].repeat((num_heads, 1, 1))
  246. bias.mul_(alibi_slopes[:, None, None]).unsqueeze_(0)
  247. inf_mask = torch.empty(
  248. (1, seq_len, seq_len),
  249. dtype=bias.dtype).fill_(-torch.inf).triu_(diagonal=1)
  250. attn_biases.append((bias + inf_mask).to(dtype))
  251. return attn_biases
  252. def _make_sliding_window_bias(
  253. seq_lens: List[int],
  254. window_size: Optional[int],
  255. dtype: torch.dtype,
  256. ) -> List[torch.Tensor]:
  257. attn_biases = []
  258. for seq_len in seq_lens:
  259. tensor = torch.full(
  260. (1, seq_len, seq_len),
  261. dtype=dtype,
  262. fill_value=1,
  263. )
  264. shift = 0
  265. mask = torch.tril(tensor, diagonal=shift).to(dtype) # type: ignore
  266. if window_size is not None:
  267. mask = torch.triu(mask, diagonal=shift - window_size + 1)
  268. mask = torch.log(mask)
  269. attn_biases.append(mask.to(dtype))
  270. return attn_biases