sdpa.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. """ Attention layer with torch scaled_dot_product_attention
  2. and PagedAttention."""
  3. from dataclasses import dataclass
  4. from typing import 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 (
  8. AttentionBackend,
  9. AttentionImpl,
  10. AttentionMetadata,
  11. AttentionMetadataPerStage,
  12. )
  13. from aphrodite.attention.ops.paged_attn import (
  14. PagedAttention,
  15. PagedAttentionMetadata,
  16. )
  17. class TorchSDPABackend(AttentionBackend):
  18. @staticmethod
  19. def get_impl_cls() -> Type["TorchSDPABackendImpl"]:
  20. return TorchSDPABackendImpl
  21. @staticmethod
  22. def make_metadata(*args, **kwargs) -> "TorchSDPAMetadata":
  23. return TorchSDPAMetadata(*args, **kwargs)
  24. @staticmethod
  25. def get_kv_cache_shape(
  26. num_blocks: int,
  27. block_size: int,
  28. num_kv_heads: int,
  29. head_size: int,
  30. ) -> Tuple[int, ...]:
  31. return PagedAttention.get_kv_cache_shape(num_blocks, block_size,
  32. num_kv_heads, head_size)
  33. @staticmethod
  34. def swap_blocks(
  35. src_kv_cache: torch.Tensor,
  36. dst_kv_cache: torch.Tensor,
  37. src_to_dst: Dict[int, int],
  38. ) -> None:
  39. PagedAttention.swap_blocks(src_kv_cache, dst_kv_cache, src_to_dst)
  40. @staticmethod
  41. def copy_blocks(
  42. kv_caches: List[torch.Tensor],
  43. src_to_dists: Dict[int, List[int]],
  44. ) -> None:
  45. PagedAttention.copy_blocks(kv_caches, src_to_dists)
  46. @dataclass
  47. class TorchSDPAMetadata(AttentionMetadata, PagedAttentionMetadata,
  48. AttentionMetadataPerStage):
  49. """Metadata for TorchSDPABackend.
  50. """
  51. # Currently, input sequences can only contain all prompts
  52. # or all decoding. True if all sequences are prompts.
  53. is_prompt: bool
  54. slot_mapping: torch.Tensor
  55. prompt_lens: Optional[List[int]]
  56. def __post_init__(self):
  57. # Set during the execution of the first attention op.
  58. # It is a list because it is needed to set per prompt
  59. # when alibi slopes is used. It is because of the limitation
  60. # from xformer API.
  61. # will not appear in the __repr__ and __init__
  62. self.attn_bias: Optional[List[torch.Tensor]] = None
  63. class TorchSDPABackendImpl(AttentionImpl):
  64. def __init__(
  65. self,
  66. num_heads: int,
  67. head_size: int,
  68. scale: float,
  69. num_kv_heads: Optional[int] = None,
  70. alibi_slopes: Optional[List[float]] = None,
  71. sliding_window: Optional[int] = None,
  72. ) -> None:
  73. self.num_heads = num_heads
  74. self.head_size = head_size
  75. self.scale = float(scale)
  76. self.num_kv_heads = num_heads if num_kv_heads is None else num_kv_heads
  77. self.sliding_window = sliding_window
  78. if alibi_slopes is not None:
  79. assert len(alibi_slopes) == num_heads
  80. alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
  81. self.alibi_slopes = alibi_slopes
  82. self.need_mask = (self.alibi_slopes is not None
  83. or self.sliding_window is not None)
  84. assert self.num_heads % self.num_kv_heads == 0
  85. self.num_queries_per_kv = self.num_heads // self.num_kv_heads
  86. suppored_head_sizes = PagedAttention.get_supported_head_sizes()
  87. if head_size not in suppored_head_sizes:
  88. raise ValueError(
  89. f"Head size {head_size} is not supported by PagedAttention. "
  90. f"Supported head sizes are: {suppored_head_sizes}.")
  91. def forward(
  92. self,
  93. query: torch.Tensor,
  94. key: torch.Tensor,
  95. value: torch.Tensor,
  96. kv_cache: Optional[torch.Tensor],
  97. attn_metadata: TorchSDPAMetadata,
  98. kv_scale: float,
  99. ) -> torch.Tensor:
  100. """Forward pass with torch SDPA and PagedAttention.
  101. Args:
  102. query: shape = [num_tokens, num_heads * head_size]
  103. key: shape = [num_tokens, num_kv_heads * head_size]
  104. value: shape = [num_tokens, num_kv_heads * head_size]
  105. kv_cache = [2, num_blocks, block_size * num_kv_heads * head_size]
  106. attn_metadata: Metadata for attention.
  107. Returns:
  108. shape = [num_tokens, num_heads * head_size]
  109. """
  110. num_tokens, hidden_size = query.shape
  111. # Reshape the query, key, and value tensors.
  112. query = query.view(-1, self.num_heads, self.head_size)
  113. key = key.view(-1, self.num_kv_heads, self.head_size)
  114. value = value.view(-1, self.num_kv_heads, self.head_size)
  115. if kv_cache is not None:
  116. key_cache, value_cache = PagedAttention.split_kv_cache(
  117. kv_cache, self.num_kv_heads, self.head_size)
  118. PagedAttention.write_to_paged_cache(key, value, key_cache,
  119. value_cache,
  120. attn_metadata.slot_mapping,
  121. attn_metadata.kv_cache_dtype,
  122. kv_scale)
  123. if attn_metadata.is_prompt:
  124. if (kv_cache is None or attn_metadata.block_tables.numel() == 0):
  125. if self.num_kv_heads != self.num_heads:
  126. key = key.repeat_interleave(self.num_queries_per_kv, dim=1)
  127. value = value.repeat_interleave(self.num_queries_per_kv,
  128. dim=1)
  129. if attn_metadata.attn_bias is None:
  130. if self.alibi_slopes is not None:
  131. att_masks = _make_alibi_bias(
  132. self.alibi_slopes, query.dtype,
  133. attn_metadata.prompt_lens) # type: ignore
  134. elif self.sliding_window is not None:
  135. att_masks = _make_sliding_window_bias(
  136. attn_metadata.prompt_lens, self.sliding_window,
  137. query.dtype) # type: ignore
  138. else:
  139. att_masks = [None] * len(attn_metadata.prompt_lens)
  140. attn_metadata.attn_bias = att_masks
  141. query = query.movedim(0, query.dim() - 2)
  142. key = key.movedim(0, key.dim() - 2)
  143. value = value.movedim(0, value.dim() - 2)
  144. start = 0
  145. output = torch.empty(
  146. (num_tokens, self.num_heads, self.head_size),
  147. dtype=query.dtype)
  148. for prompt_len, mask in zip(attn_metadata.prompt_lens,
  149. attn_metadata.attn_bias):
  150. end = start + prompt_len
  151. sub_out = scaled_dot_product_attention(
  152. query[:, start:end, :],
  153. key[:, start:end, :],
  154. value[:, start:end, :],
  155. attn_mask=mask,
  156. dropout_p=0.0,
  157. is_causal=not self.need_mask,
  158. scale=self.scale).movedim(query.dim() - 2, 0)
  159. output[start:end, :, :] = sub_out
  160. start = end
  161. else:
  162. # prefix-enabled attention
  163. raise RuntimeError(
  164. "Torch SDPA backend doesn't support prefix decoding.")
  165. else:
  166. # Decoding run.
  167. output = PagedAttention.forward_decode(
  168. query,
  169. key_cache,
  170. value_cache,
  171. attn_metadata.block_tables,
  172. attn_metadata.context_lens,
  173. attn_metadata.max_context_len,
  174. attn_metadata.kv_cache_dtype,
  175. self.num_kv_heads,
  176. self.scale,
  177. self.alibi_slopes,
  178. kv_scale,
  179. )
  180. # Reshape the output tensor.
  181. return output.view(-1, self.num_heads * self.head_size)
  182. def _make_alibi_bias(
  183. alibi_slopes: torch.Tensor,
  184. dtype: torch.dtype,
  185. prompt_lens: List[int],
  186. ) -> List[torch.Tensor]:
  187. attn_biases = []
  188. for prompt_len in prompt_lens:
  189. bias = torch.arange(prompt_len, dtype=dtype)
  190. # NOTE: HF uses
  191. # `bias = bias[None, :].repeat(prompt_len, 1)`
  192. # here. We find that both biases give the same results, but
  193. # the bias below more accurately follows the original ALiBi
  194. # paper.
  195. bias = bias[None, :] - bias[:, None]
  196. num_heads = alibi_slopes.shape[0]
  197. bias = bias[None, :].repeat((num_heads, 1, 1))
  198. bias.mul_(alibi_slopes[:, None, None])
  199. inf_mask = torch.empty(
  200. (1, prompt_len, prompt_len),
  201. dtype=bias.dtype).fill_(-torch.inf).triu_(diagonal=1)
  202. attn_biases.append((bias + inf_mask).to(dtype))
  203. return attn_biases
  204. def _make_sliding_window_bias(
  205. prompt_lens: List[int],
  206. window_size: Optional[int],
  207. dtype: torch.dtype,
  208. ) -> List[torch.Tensor]:
  209. attn_biases = []
  210. for prompt_len in prompt_lens:
  211. tensor = torch.full(
  212. (1, prompt_len, prompt_len),
  213. dtype=dtype,
  214. fill_value=1,
  215. )
  216. shift = 0
  217. mask = torch.tril(tensor, diagonal=shift).to(dtype) # type: ignore
  218. if window_size is not None:
  219. mask = torch.triu(mask, diagonal=shift - window_size + 1)
  220. mask = torch.log(mask)
  221. attn_biases.append(mask.to(dtype))
  222. return attn_biases