ipex_attn.py 14 KB

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