ipex_attn.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 aphrodite._ipex_ops import ipex_ops
  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 (PagedAttention,
  13. PagedAttentionMetadata)
  14. _PARTITION_SIZE = 512
  15. class IpexAttnBackend(AttentionBackend):
  16. @staticmethod
  17. def get_name() -> str:
  18. return "ipex-attn"
  19. @staticmethod
  20. def get_impl_cls() -> Type["IpexAttnBackendImpl"]:
  21. return IpexAttnBackendImpl
  22. @staticmethod
  23. def get_metadata_cls() -> Type["IpexAttnMetadata"]:
  24. return IpexAttnMetadata
  25. @staticmethod
  26. def get_builder_cls() -> Type["IpexAttnMetadataBuilder"]:
  27. return IpexAttnMetadataBuilder
  28. @staticmethod
  29. def get_kv_cache_shape(
  30. num_blocks: int,
  31. block_size: int,
  32. num_kv_heads: int,
  33. head_size: int,
  34. ) -> Tuple[int, ...]:
  35. return PagedAttention.get_kv_cache_shape(num_blocks, block_size,
  36. num_kv_heads, head_size)
  37. @staticmethod
  38. def swap_blocks(
  39. src_kv_cache: torch.Tensor,
  40. dst_kv_cache: torch.Tensor,
  41. src_to_dst: torch.Tensor,
  42. ) -> None:
  43. PagedAttention.swap_blocks(src_kv_cache, dst_kv_cache, src_to_dst)
  44. @staticmethod
  45. def copy_blocks(
  46. kv_caches: List[torch.Tensor],
  47. src_to_dists: torch.Tensor,
  48. ) -> None:
  49. PagedAttention.copy_blocks(kv_caches, src_to_dists)
  50. @dataclass
  51. class IpexAttnMetadata(AttentionMetadata, PagedAttentionMetadata):
  52. """Metadata for IpexAttnBackend.
  53. """
  54. # Currently, input sequences can only contain all prompts
  55. # or all decoding. True if all sequences are prompts.
  56. is_prompt: bool
  57. slot_mapping: torch.Tensor
  58. seq_lens: Optional[List[int]]
  59. seqlen_q: Optional[torch.Tensor]
  60. max_seqlen: Optional[int]
  61. def __post_init__(self):
  62. # Set during the execution of the first attention op.
  63. # It is a list because it is needed to set per prompt
  64. # when alibi slopes is used. It is because of the limitation
  65. # from xformer API.
  66. # will not appear in the __repr__ and __init__
  67. self.attn_bias: Optional[List[torch.Tensor]] = None
  68. @property
  69. def prefill_metadata(self) -> Optional["IpexAttnMetadata"]:
  70. # Currently chunked prefill is not supported
  71. if self.num_decode_tokens == 0:
  72. assert self.num_prefills > 0
  73. return self
  74. return None
  75. @property
  76. def decode_metadata(self) -> Optional["IpexAttnMetadata"]:
  77. # Currently chunked prefill is not supported
  78. if self.num_prefills > 0:
  79. assert self.num_decode_tokens == 0
  80. return None
  81. return self
  82. class IpexAttnMetadataBuilder(CommonMetadataBuilder[IpexAttnMetadata]):
  83. _metadata_cls = IpexAttnMetadata
  84. class IpexAttnBackendImpl(AttentionImpl[IpexAttnMetadata]):
  85. def __init__(
  86. self,
  87. num_heads: int,
  88. head_size: int,
  89. scale: float,
  90. num_kv_heads: int,
  91. alibi_slopes: Optional[List[float]],
  92. sliding_window: Optional[int],
  93. kv_cache_dtype: str,
  94. blocksparse_params: Optional[Dict[str, Any]] = None,
  95. logits_soft_cap: Optional[float] = None,
  96. ) -> None:
  97. if blocksparse_params is not None:
  98. raise ValueError(
  99. "IPEX backend does not support block-sparse attention.")
  100. if logits_soft_cap is not None:
  101. raise ValueError("IPEX backend does not support logits_soft_cap.")
  102. self.num_heads = num_heads
  103. self.head_size = head_size
  104. self.scale = float(scale)
  105. self.num_kv_heads = num_kv_heads
  106. if alibi_slopes is not None:
  107. alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
  108. self.alibi_slopes = alibi_slopes
  109. self.sliding_window = sliding_window
  110. self.kv_cache_dtype = kv_cache_dtype
  111. assert self.num_heads % self.num_kv_heads == 0
  112. self.num_queries_per_kv = self.num_heads // self.num_kv_heads
  113. self.need_mask = (self.alibi_slopes is not None
  114. or self.sliding_window is not None)
  115. supported_head_sizes = PagedAttention.get_supported_head_sizes()
  116. if head_size not in supported_head_sizes:
  117. raise ValueError(
  118. f"Head size {head_size} is not supported by PagedAttention. "
  119. f"Supported head sizes are: {supported_head_sizes}.")
  120. if kv_cache_dtype != "auto":
  121. raise NotImplementedError(
  122. "IPEX backend does not support FP8 KV cache. "
  123. "Please use xFormers backend instead.")
  124. def split_kv_cache(
  125. self,
  126. kv_cache: torch.Tensor,
  127. num_kv_heads: int,
  128. head_size: int,
  129. ) -> Tuple[torch.Tensor, torch.Tensor]:
  130. x = 1
  131. num_blocks = kv_cache.shape[1]
  132. key_cache = kv_cache[0]
  133. key_cache = key_cache.view(num_blocks, num_kv_heads, head_size // x,
  134. -1, x)
  135. value_cache = kv_cache[1]
  136. value_cache = value_cache.view(num_blocks, num_kv_heads, head_size, -1)
  137. return key_cache, value_cache
  138. def forward(
  139. self,
  140. query: torch.Tensor,
  141. key: torch.Tensor,
  142. value: torch.Tensor,
  143. kv_cache: Optional[torch.Tensor],
  144. attn_metadata: IpexAttnMetadata, # type: ignore
  145. k_scale: float = 1.0,
  146. v_scale: float = 1.0,
  147. attn_type: AttentionType = AttentionType.DECODER,
  148. ) -> torch.Tensor:
  149. """Forward pass with IPEX varlen_attention and PagedAttention.
  150. Args:
  151. query: shape = [num_tokens, num_heads * head_size]
  152. key: shape = [num_tokens, num_kv_heads * head_size]
  153. value: shape = [num_tokens, num_kv_heads * head_size]
  154. kv_cache = [2, num_blocks, block_size * num_kv_heads * head_size]
  155. attn_metadata: Metadata for attention.
  156. Returns:
  157. shape = [num_tokens, num_heads * head_size]
  158. """
  159. assert k_scale == 1.0 and v_scale == 1.0
  160. if attn_type != AttentionType.DECODER:
  161. raise NotImplementedError("Encoder self-attention and "
  162. "encoder/decoder cross-attention "
  163. "are not implemented for "
  164. "IpexAttnBackendImpl")
  165. num_tokens, hidden_size = query.shape
  166. # Reshape the query, key, and value tensors.
  167. query = query.view(-1, self.num_heads, self.head_size)
  168. key = key.view(-1, self.num_kv_heads, self.head_size)
  169. value = value.view(-1, self.num_kv_heads, self.head_size)
  170. if kv_cache is not None:
  171. key_cache, value_cache = self.split_kv_cache(
  172. kv_cache, self.num_kv_heads, self.head_size)
  173. ipex_ops.reshape_and_cache(
  174. key,
  175. value,
  176. key_cache,
  177. value_cache,
  178. attn_metadata.slot_mapping.flatten(),
  179. self.kv_cache_dtype,
  180. k_scale,
  181. v_scale,
  182. )
  183. if attn_metadata.is_prompt:
  184. assert attn_metadata.seq_lens is not None
  185. if (kv_cache is None or attn_metadata.block_tables.numel() == 0):
  186. if self.num_kv_heads != self.num_heads:
  187. key = key.repeat_interleave(self.num_queries_per_kv, dim=1)
  188. value = value.repeat_interleave(self.num_queries_per_kv,
  189. dim=1)
  190. if attn_metadata.attn_bias is None:
  191. if self.alibi_slopes is not None:
  192. att_masks = _make_alibi_bias(
  193. self.alibi_slopes, query.dtype,
  194. attn_metadata.seq_lens) # type: ignore
  195. elif self.sliding_window is not None:
  196. att_masks = _make_sliding_window_bias(
  197. attn_metadata.seq_lens, self.sliding_window,
  198. query.dtype) # type: ignore
  199. else:
  200. att_masks = _make_sliding_window_bias(
  201. attn_metadata.seq_lens, None, dtype=query.dtype)
  202. attn_metadata.attn_bias = att_masks
  203. output = torch.empty(
  204. (num_tokens, self.num_heads, self.head_size),
  205. dtype=query.dtype,
  206. device=query.device)
  207. ipex_ops.varlen_attention(query,
  208. key,
  209. value,
  210. output,
  211. attn_metadata.seqlen_q,
  212. attn_metadata.seqlen_q,
  213. attn_metadata.max_seqlen,
  214. attn_metadata.max_seqlen,
  215. pdropout=0.0,
  216. softmax_scale=self.scale,
  217. zero_tensors=False,
  218. is_causal=True,
  219. return_softmax=False,
  220. gen_=None)
  221. else:
  222. # prefix-enabled attention
  223. raise RuntimeError(
  224. "IPEX backend doesn't support prefix decoding.")
  225. else:
  226. # Decoding run.
  227. max_seq_len = attn_metadata.max_decode_seq_len
  228. output = torch.empty_like(query)
  229. block_size = value_cache.shape[3]
  230. num_seqs, num_heads, head_size = query.shape
  231. max_num_partitions = ((max_seq_len + _PARTITION_SIZE - 1) //
  232. _PARTITION_SIZE)
  233. # NOTE: We use a simple heuristic to decide whether to use
  234. # PagedAttention V1 or V2. If the number of partitions is 1, we use
  235. # V1 to avoid the overhead of reduction. Also, if the number of
  236. # sequences or heads is large, we use V1 since there is enough work
  237. # to parallelize.
  238. # TODO: Tune this heuristic.
  239. # For context len > 8192, use V2 kernel to avoid shared memory
  240. # shortage.
  241. use_v1 = (max_seq_len <= 8192 and
  242. (max_num_partitions == 1 or num_seqs * num_heads > 512))
  243. if use_v1:
  244. # Run PagedAttention V1.
  245. ipex_ops.paged_attention_v1(
  246. output,
  247. query,
  248. key_cache,
  249. value_cache,
  250. self.num_kv_heads,
  251. self.scale,
  252. attn_metadata.block_tables,
  253. attn_metadata.seq_lens_tensor,
  254. block_size,
  255. max_seq_len,
  256. self.alibi_slopes,
  257. self.kv_cache_dtype,
  258. k_scale,
  259. v_scale,
  260. )
  261. else:
  262. # Run PagedAttention V2.
  263. assert _PARTITION_SIZE % block_size == 0
  264. tmp_output = torch.empty(
  265. size=(num_seqs, num_heads, max_num_partitions, head_size),
  266. dtype=output.dtype,
  267. device=output.device,
  268. )
  269. exp_sums = torch.empty(
  270. size=(num_seqs, num_heads, max_num_partitions),
  271. dtype=torch.float32,
  272. device=output.device,
  273. )
  274. max_logits = torch.empty_like(exp_sums)
  275. ipex_ops.paged_attention_v2(
  276. output,
  277. exp_sums,
  278. max_logits,
  279. tmp_output,
  280. query,
  281. key_cache,
  282. value_cache,
  283. self.num_kv_heads,
  284. self.scale,
  285. attn_metadata.block_tables,
  286. attn_metadata.seq_lens_tensor,
  287. block_size,
  288. max_seq_len,
  289. self.alibi_slopes,
  290. self.kv_cache_dtype,
  291. k_scale,
  292. v_scale,
  293. )
  294. # Reshape the output tensor.
  295. return output.view(-1, self.num_heads * self.head_size)
  296. def _make_alibi_bias(
  297. alibi_slopes: torch.Tensor,
  298. dtype: torch.dtype,
  299. seq_lens: List[int],
  300. ) -> List[torch.Tensor]:
  301. attn_biases = []
  302. for seq_len in seq_lens:
  303. bias = torch.arange(seq_len, dtype=dtype, device=alibi_slopes.device)
  304. # NOTE: HF uses
  305. # `bias = bias[None, :].repeat(seq_len, 1)`
  306. # here. We find that both biases give the same results, but
  307. # the bias below more accurately follows the original ALiBi
  308. # paper.
  309. bias = bias[None, :] - bias[:, None]
  310. num_heads = alibi_slopes.shape[0]
  311. bias = bias[None, :].repeat((num_heads, 1, 1))
  312. bias.mul_(alibi_slopes[:, None, None])
  313. inf_mask = torch.empty(
  314. (1, seq_len, seq_len),
  315. dtype=bias.dtype,
  316. device=alibi_slopes.device).fill_(-torch.inf).triu_(diagonal=1)
  317. attn_biases.append((bias + inf_mask).to(dtype))
  318. return attn_biases
  319. def _make_sliding_window_bias(
  320. seq_lens: List[int],
  321. window_size: Optional[int],
  322. dtype: torch.dtype,
  323. ) -> List[torch.Tensor]:
  324. attn_biases = []
  325. for seq_len in seq_lens:
  326. tensor = torch.full(
  327. (1, seq_len, seq_len),
  328. dtype=dtype,
  329. fill_value=1,
  330. )
  331. shift = 0
  332. mask = torch.tril(tensor, diagonal=shift).to(dtype) # type: ignore
  333. if window_size is not None:
  334. mask = torch.triu(mask, diagonal=shift - window_size + 1)
  335. mask = torch.log(mask)
  336. attn_biases.append(mask.to(dtype))
  337. return attn_biases