flash_attn.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. """Attention layer with FlashAttention."""
  2. from dataclasses import dataclass
  3. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type
  4. import torch
  5. from aphrodite import _custom_ops as ops
  6. from aphrodite.attention.backends.abstract import (AttentionBackend,
  7. AttentionImpl,
  8. AttentionMetadata,
  9. AttentionMetadataBuilder,
  10. AttentionType)
  11. from aphrodite.attention.backends.utils import (PAD_SLOT_ID,
  12. compute_slot_mapping,
  13. compute_slot_mapping_start_idx,
  14. is_block_tables_empty)
  15. from aphrodite.common.utils import async_tensor_h2d, make_tensor_with_pad
  16. if TYPE_CHECKING:
  17. from aphrodite.task_handler.model_runner import ModelInputForGPUBuilder
  18. from aphrodite_flash_attn import (
  19. flash_attn_varlen_func as _flash_attn_varlen_func)
  20. from aphrodite_flash_attn import (
  21. flash_attn_with_kvcache as _flash_attn_with_kvcache)
  22. @torch.library.custom_op("aphrodite::flash_attn_varlen_func", mutates_args=[])
  23. def flash_attn_varlen_func(
  24. q: torch.Tensor,
  25. k: torch.Tensor,
  26. v: torch.Tensor,
  27. cu_seqlens_q: torch.Tensor,
  28. cu_seqlens_k: torch.Tensor,
  29. max_seqlen_q: int,
  30. max_seqlen_k: int,
  31. softmax_scale: Optional[float] = None,
  32. causal: bool = False,
  33. window_size: Optional[List[int]] = None,
  34. softcap: float = 0.0,
  35. alibi_slopes: Optional[torch.Tensor] = None,
  36. block_table: Optional[torch.Tensor] = None,
  37. ) -> torch.Tensor:
  38. # custom op does not support tuple input
  39. real_window_size: Tuple[int, int]
  40. if window_size is None:
  41. real_window_size = (-1, -1)
  42. else:
  43. assert len(window_size) == 2
  44. real_window_size = (window_size[0], window_size[1])
  45. return _flash_attn_varlen_func(
  46. q=q,
  47. k=k,
  48. v=v,
  49. cu_seqlens_q=cu_seqlens_q,
  50. cu_seqlens_k=cu_seqlens_k,
  51. max_seqlen_q=max_seqlen_q,
  52. max_seqlen_k=max_seqlen_k,
  53. softmax_scale=softmax_scale,
  54. causal=causal,
  55. window_size=real_window_size,
  56. softcap=softcap,
  57. alibi_slopes=alibi_slopes,
  58. block_table=block_table,
  59. )
  60. @flash_attn_varlen_func.register_fake # type: ignore
  61. def _(
  62. q: torch.Tensor,
  63. k: torch.Tensor,
  64. v: torch.Tensor,
  65. cu_seqlens_q: torch.Tensor,
  66. cu_seqlens_k: torch.Tensor,
  67. max_seqlen_q: int,
  68. max_seqlen_k: int,
  69. softmax_scale: Optional[float] = None,
  70. causal: bool = False,
  71. window_size: Optional[List[int]] = None,
  72. softcap: float = 0.0,
  73. alibi_slopes: Optional[torch.Tensor] = None,
  74. block_table: Optional[torch.Tensor] = None,
  75. ) -> torch.Tensor:
  76. return torch.empty_like(q)
  77. @torch.library.custom_op("aphrodite::flash_attn_with_kvcache", mutates_args=[])
  78. def flash_attn_with_kvcache(
  79. decode_query: torch.Tensor,
  80. key_cache: torch.Tensor,
  81. value_cache: torch.Tensor,
  82. cache_seqlens: Optional[torch.Tensor] = None,
  83. block_table: Optional[torch.Tensor] = None,
  84. softmax_scale: Optional[float] = None,
  85. causal: bool = False,
  86. alibi_slopes: Optional[torch.Tensor] = None,
  87. softcap: float = 0.0,
  88. ) -> torch.Tensor:
  89. return _flash_attn_with_kvcache(
  90. decode_query,
  91. key_cache,
  92. value_cache,
  93. cache_seqlens=cache_seqlens,
  94. block_table=block_table,
  95. softmax_scale=softmax_scale,
  96. causal=causal,
  97. alibi_slopes=alibi_slopes,
  98. softcap=softcap,
  99. )
  100. @flash_attn_with_kvcache.register_fake # type: ignore
  101. def _(
  102. decode_query: torch.Tensor,
  103. key_cache: torch.Tensor,
  104. value_cache: torch.Tensor,
  105. cache_seqlens: Optional[torch.Tensor] = None,
  106. block_table: Optional[torch.Tensor] = None,
  107. softmax_scale: Optional[float] = None,
  108. causal: bool = False,
  109. alibi_slopes: Optional[torch.Tensor] = None,
  110. softcap: float = 0.0,
  111. ) -> torch.Tensor:
  112. return torch.empty_like(decode_query)
  113. class FlashAttentionBackend(AttentionBackend):
  114. @staticmethod
  115. def get_supported_head_sizes() -> List[int]:
  116. return [32, 64, 96, 128, 160, 192, 224, 256]
  117. @staticmethod
  118. def get_name() -> str:
  119. return "flash-attn"
  120. @staticmethod
  121. def get_impl_cls() -> Type["FlashAttentionImpl"]:
  122. return FlashAttentionImpl
  123. @staticmethod
  124. def get_metadata_cls() -> Type["AttentionMetadata"]:
  125. return FlashAttentionMetadata
  126. @staticmethod
  127. def get_builder_cls() -> Type["FlashAttentionMetadataBuilder"]:
  128. return FlashAttentionMetadataBuilder
  129. @staticmethod
  130. def get_kv_cache_shape(
  131. num_blocks: int,
  132. block_size: int,
  133. num_kv_heads: int,
  134. head_size: int,
  135. ) -> Tuple[int, ...]:
  136. if block_size % 16 != 0:
  137. raise ValueError("Block size must be a multiple of 16.")
  138. return (2, num_blocks, block_size, num_kv_heads, head_size)
  139. @staticmethod
  140. def swap_blocks(
  141. src_kv_cache: torch.Tensor,
  142. dst_kv_cache: torch.Tensor,
  143. src_to_dst: torch.Tensor,
  144. ) -> None:
  145. src_key_cache = src_kv_cache[0]
  146. dst_key_cache = dst_kv_cache[0]
  147. ops.swap_blocks(src_key_cache, dst_key_cache, src_to_dst)
  148. src_value_cache = src_kv_cache[1]
  149. dst_value_cache = dst_kv_cache[1]
  150. ops.swap_blocks(src_value_cache, dst_value_cache, src_to_dst)
  151. @staticmethod
  152. def copy_blocks(
  153. kv_caches: List[torch.Tensor],
  154. src_to_dists: torch.Tensor,
  155. ) -> None:
  156. key_caches = [kv_cache[0] for kv_cache in kv_caches]
  157. value_caches = [kv_cache[1] for kv_cache in kv_caches]
  158. ops.copy_blocks(key_caches, value_caches, src_to_dists)
  159. @dataclass
  160. class FlashAttentionMetadata(AttentionMetadata):
  161. """Metadata for FlashAttentionBackend.
  162. NOTE: Any python object stored here is not updated when it is
  163. cuda-graph replayed. If you have values that need to be changed
  164. dynamically, it should be stored in tensor. The tensor has to be
  165. updated from `CUDAGraphRunner.forward` API.
  166. """
  167. # (batch_size,). The sequence length per sequence. Sequence length means
  168. # the computed tokens + new tokens None if it is a decoding.
  169. seq_lens: Optional[List[int]]
  170. # seq_lens stored as a tensor.
  171. seq_lens_tensor: Optional[torch.Tensor]
  172. # NOTE: Definition of context_len, query_len, and seq_len.
  173. # |---------- N-1 iteration --------|
  174. # |---------------- N iteration ---------------------|
  175. # |- tokenA -|......................|-- newTokens ---|
  176. # |---------- context_len ----------|
  177. # |-------------------- seq_len ----------------------|
  178. # |-- query_len ---|
  179. # Maximum query length in the batch. None for decoding.
  180. max_query_len: Optional[int]
  181. # Maximum sequence length among prefill batch. 0 if there are decoding
  182. # requests only.
  183. max_prefill_seq_len: int
  184. # Maximum sequence length among decode batch. 0 if there are prefill
  185. # requests only.
  186. max_decode_seq_len: int
  187. # (batch_size + 1,). The cumulative subquery lengths of the sequences in
  188. # the batch, used to index into subquery. E.g., if the subquery length
  189. # is [4, 6], it is [0, 4, 10].
  190. query_start_loc: Optional[torch.Tensor]
  191. # (batch_size + 1,). The cumulative sequence lengths of the sequences in
  192. # the batch, used to index into sequence. E.g., if the sequence length is
  193. # [4, 6], it is [0, 4, 10].
  194. seq_start_loc: Optional[torch.Tensor]
  195. # (batch_size,) A tensor of context lengths (tokens that are computed
  196. # so far).
  197. context_lens_tensor: Optional[torch.Tensor]
  198. # (batch_size, max_blocks_per_seq).
  199. # Block addresses per sequence. (Seq id -> list of physical block)
  200. # E.g., [0, 1, 2] means tokens are stored in 0th, 1st, and 2nd blocks
  201. # in the kv cache. Each block can contain up to block_size tokens.
  202. # 2nd dimensions are padded up to max_blocks_per_seq if it is cuda-graph
  203. # captured.
  204. block_tables: Optional[torch.Tensor]
  205. # Whether or not if cuda graph is enabled.
  206. # Cuda-graph is currently enabled for decoding only.
  207. # TODO: Move `use_cuda_graph` out since it's unrelated to attention.
  208. use_cuda_graph: bool
  209. _cached_prefill_metadata: Optional["FlashAttentionMetadata"] = None
  210. _cached_decode_metadata: Optional["FlashAttentionMetadata"] = None
  211. @property
  212. def prefill_metadata(self) -> Optional["FlashAttentionMetadata"]:
  213. if self.num_prefills == 0:
  214. return None
  215. if self._cached_prefill_metadata is not None:
  216. return self._cached_prefill_metadata
  217. assert self.seq_lens is not None
  218. assert self.seq_lens_tensor is not None
  219. assert self.query_start_loc is not None
  220. assert self.context_lens_tensor is not None
  221. assert self.block_tables is not None
  222. assert self.seq_start_loc is not None
  223. self._cached_prefill_metadata = FlashAttentionMetadata(
  224. num_prefills=self.num_prefills,
  225. num_prefill_tokens=self.num_prefill_tokens,
  226. num_decode_tokens=0,
  227. slot_mapping=self.slot_mapping[:self.num_prefill_tokens],
  228. seq_lens=self.seq_lens[:self.num_prefills],
  229. seq_lens_tensor=self.seq_lens_tensor[:self.num_prefills],
  230. max_query_len=self.max_query_len,
  231. max_prefill_seq_len=self.max_prefill_seq_len,
  232. max_decode_seq_len=0,
  233. query_start_loc=self.query_start_loc[:self.num_prefills + 1],
  234. seq_start_loc=self.seq_start_loc[:self.num_prefills + 1],
  235. context_lens_tensor=self.context_lens_tensor[:self.num_prefills],
  236. block_tables=self.block_tables[:self.num_prefills],
  237. use_cuda_graph=False,
  238. )
  239. return self._cached_prefill_metadata
  240. @property
  241. def decode_metadata(self) -> Optional["FlashAttentionMetadata"]:
  242. if self.num_decode_tokens == 0:
  243. return None
  244. if self._cached_decode_metadata is not None:
  245. return self._cached_decode_metadata
  246. assert self.block_tables is not None
  247. assert self.seq_lens_tensor is not None
  248. self._cached_decode_metadata = FlashAttentionMetadata(
  249. num_prefills=0,
  250. num_prefill_tokens=0,
  251. num_decode_tokens=self.num_decode_tokens,
  252. slot_mapping=self.slot_mapping[self.num_prefill_tokens:],
  253. seq_lens=None,
  254. seq_lens_tensor=self.seq_lens_tensor[self.num_prefills:],
  255. max_query_len=None,
  256. max_prefill_seq_len=0,
  257. max_decode_seq_len=self.max_decode_seq_len,
  258. query_start_loc=None,
  259. seq_start_loc=None,
  260. context_lens_tensor=None,
  261. block_tables=self.block_tables[self.num_prefills:],
  262. use_cuda_graph=self.use_cuda_graph,
  263. )
  264. return self._cached_decode_metadata
  265. def advance_step(self, num_seqs: int, num_queries: int):
  266. """
  267. Update metadata in-place to advance one decode step.
  268. """
  269. # GPU in-place update is currently called separately through
  270. # custom_ops.advance_step(). See draft_model_runner.
  271. # TODO: Move this logic to the backend.
  272. # When using cudagraph, the num_seqs is padded to the next captured
  273. # batch sized, but num_queries tracks the actual number of requests in
  274. # the batch. For --enforce-eager mode, num_seqs == num_queries
  275. if num_seqs != num_queries:
  276. assert num_seqs > num_queries
  277. assert self.use_cuda_graph
  278. assert self.num_prefills == 0
  279. assert self.num_prefill_tokens == 0
  280. assert self.num_decode_tokens == num_seqs
  281. assert self.slot_mapping.shape == (num_seqs, )
  282. assert self.seq_lens is not None
  283. assert len(self.seq_lens) == num_seqs
  284. assert self.seq_lens_tensor is not None
  285. assert self.seq_lens_tensor.shape == (num_seqs, )
  286. assert self.max_query_len == 1
  287. assert self.max_prefill_seq_len == 0
  288. assert self.max_decode_seq_len == max(self.seq_lens)
  289. assert self.query_start_loc is not None
  290. assert self.query_start_loc.shape == (num_queries + 1, )
  291. assert self.seq_start_loc is not None
  292. assert self.seq_start_loc.shape == (num_seqs + 1, )
  293. assert self.context_lens_tensor is not None
  294. assert self.context_lens_tensor.shape == (num_queries, )
  295. assert self.block_tables is not None
  296. assert self.block_tables.shape[0] == num_seqs
  297. # Update query lengths. Note that we update only queries and not seqs,
  298. # since tensors may be padded due to captured cuda graph batch size
  299. for i in range(num_queries):
  300. self.seq_lens[i] += 1
  301. self.max_decode_seq_len = max(self.seq_lens)
  302. class FlashAttentionMetadataBuilder(
  303. AttentionMetadataBuilder[FlashAttentionMetadata]):
  304. def __init__(self, input_builder: "ModelInputForGPUBuilder"):
  305. self.slot_mapping: List[int] = []
  306. self.prefill_seq_lens: List[int] = []
  307. self.context_lens: List[int] = []
  308. self.block_tables: List[List[int]] = []
  309. self.curr_seq_lens: List[int] = []
  310. self.num_prefills = 0
  311. self.num_prefill_tokens = 0
  312. self.num_decode_tokens = 0
  313. self.has_prefix_cache_hit = False
  314. self.input_builder = input_builder
  315. self.runner = input_builder.runner
  316. self.sliding_window = input_builder.sliding_window
  317. self.block_size = input_builder.block_size
  318. self.use_v2_block_manager = (
  319. input_builder.scheduler_config.use_v2_block_manager)
  320. def _add_seq_group(
  321. self, inter_data: "ModelInputForGPUBuilder.InterDataForSeqGroup",
  322. chunked_prefill_enabled: bool, prefix_cache_hit: bool):
  323. """Add a sequence group to the metadata. Specifically update/append
  324. 1. context length.
  325. 2. block table.
  326. 3. slot mapping.
  327. """
  328. is_prompt = inter_data.is_prompt
  329. block_tables = inter_data.block_tables
  330. for (seq_id, token_len, seq_len, curr_seq_len, query_len, context_len,
  331. curr_sliding_window_block) in zip(
  332. inter_data.seq_ids, [len(t) for t in inter_data.input_tokens],
  333. inter_data.orig_seq_lens, inter_data.seq_lens,
  334. inter_data.query_lens, inter_data.context_lens,
  335. inter_data.curr_sliding_window_blocks):
  336. self.context_lens.append(context_len)
  337. if is_prompt:
  338. self.num_prefills += 1
  339. self.num_prefill_tokens += token_len
  340. self.prefill_seq_lens.append(seq_len)
  341. else:
  342. assert query_len == 1, (
  343. "seq_len: {}, context_len: {}, query_len: {}".format(
  344. seq_len, context_len, query_len))
  345. self.num_decode_tokens += query_len
  346. self.curr_seq_lens.append(curr_seq_len)
  347. # Compute block table.
  348. # TODO: Combine chunked prefill and prefix caching by
  349. # only allowing multiple of block_size chunk size.
  350. # NOTE: This only works for oooooooxxx style attention.
  351. block_table = []
  352. if prefix_cache_hit:
  353. # NOTE: For flash-attn, the block table should
  354. # include the entries for the incoming prefill tokens.
  355. block_table = block_tables[seq_id]
  356. elif ((chunked_prefill_enabled or not is_prompt)
  357. and block_tables is not None):
  358. if curr_sliding_window_block == 0:
  359. block_table = block_tables[seq_id]
  360. else:
  361. block_table = block_tables[seq_id][
  362. -curr_sliding_window_block:]
  363. self.block_tables.append(block_table)
  364. # Compute slot mapping.
  365. is_profile_run = is_block_tables_empty(block_tables)
  366. start_idx = compute_slot_mapping_start_idx(
  367. is_prompt, query_len, context_len, self.sliding_window,
  368. self.use_v2_block_manager)
  369. compute_slot_mapping(is_profile_run, self.slot_mapping, seq_id,
  370. seq_len, context_len, start_idx,
  371. self.block_size, inter_data.block_tables)
  372. def build(self, seq_lens: List[int], query_lens: List[int],
  373. cuda_graph_pad_size: int, batch_size: int):
  374. """Build attention metadata with on-device tensors.
  375. Args:
  376. seq_lens: The maybe padded sequence lengths of the input sequences.
  377. query_lens: The query lengths of the input sequences.
  378. cuda_graph_pad_size: The padding size for cuda graph.
  379. -1 if cuda graph is not used.
  380. batch_size: The maybe padded batch size.
  381. """
  382. prefix_cache_hit = any([
  383. inter_data.prefix_cache_hit
  384. for inter_data in self.input_builder.inter_data_list
  385. ])
  386. for inter_data in self.input_builder.inter_data_list:
  387. self._add_seq_group(inter_data,
  388. self.input_builder.chunked_prefill_enabled,
  389. prefix_cache_hit)
  390. device = self.runner.device
  391. use_captured_graph = cuda_graph_pad_size != -1
  392. max_query_len = max(query_lens)
  393. max_prefill_seq_len = max(self.prefill_seq_lens, default=0)
  394. max_decode_seq_len = max(self.curr_seq_lens, default=0)
  395. num_decode_tokens = self.num_decode_tokens
  396. if use_captured_graph:
  397. self.slot_mapping.extend([PAD_SLOT_ID] * cuda_graph_pad_size)
  398. self.block_tables.extend([] * cuda_graph_pad_size)
  399. num_decode_tokens = batch_size
  400. # The shape of graph_block_tables is
  401. # [max batch size, max context len // block size].
  402. input_block_tables = self.runner.graph_block_tables[:batch_size]
  403. for i, block_table in enumerate(self.block_tables):
  404. if block_table:
  405. input_block_tables[i, :len(block_table)] = block_table
  406. block_tables = torch.from_numpy(input_block_tables).to(
  407. device=device, non_blocking=True)
  408. else:
  409. block_tables = make_tensor_with_pad(
  410. self.block_tables,
  411. pad=0,
  412. dtype=torch.int,
  413. device=device,
  414. )
  415. assert max_query_len > 0, ("query_lens: {}".format(query_lens))
  416. assert device is not None
  417. context_lens_tensor = async_tensor_h2d(self.context_lens, torch.int,
  418. device, self.runner.pin_memory)
  419. seq_lens_tensor = async_tensor_h2d(seq_lens, torch.int, device,
  420. self.runner.pin_memory)
  421. query_lens_tensor = async_tensor_h2d(query_lens, torch.long, device,
  422. self.runner.pin_memory)
  423. slot_mapping_tensor = async_tensor_h2d(self.slot_mapping, torch.long,
  424. device, self.runner.pin_memory)
  425. query_start_loc = torch.zeros(query_lens_tensor.shape[0] + 1,
  426. dtype=torch.int32,
  427. device=device)
  428. seq_start_loc = torch.zeros(seq_lens_tensor.shape[0] + 1,
  429. dtype=torch.int32,
  430. device=device)
  431. torch.cumsum(seq_lens_tensor,
  432. dim=0,
  433. dtype=seq_start_loc.dtype,
  434. out=seq_start_loc[1:])
  435. torch.cumsum(query_lens_tensor,
  436. dim=0,
  437. dtype=query_start_loc.dtype,
  438. out=query_start_loc[1:])
  439. return FlashAttentionMetadata(
  440. num_prefills=self.num_prefills,
  441. slot_mapping=slot_mapping_tensor,
  442. num_prefill_tokens=self.num_prefill_tokens,
  443. num_decode_tokens=num_decode_tokens,
  444. seq_lens=seq_lens,
  445. seq_lens_tensor=seq_lens_tensor,
  446. max_query_len=max_query_len,
  447. max_prefill_seq_len=max_prefill_seq_len,
  448. max_decode_seq_len=max_decode_seq_len,
  449. query_start_loc=query_start_loc,
  450. seq_start_loc=seq_start_loc,
  451. context_lens_tensor=context_lens_tensor,
  452. block_tables=block_tables,
  453. use_cuda_graph=use_captured_graph,
  454. )
  455. class FlashAttentionImpl(AttentionImpl):
  456. """
  457. If the input tensors contain prompt tokens, the layout is as follows:
  458. |<--------------- num_prefill_tokens ----------------->|
  459. |<--prefill_0-->|<--prefill_1-->|...|<--prefill_N-1--->|
  460. Otherwise, the layout is as follows:
  461. |<----------------- num_decode_tokens ------------------>|
  462. |<--decode_0-->|..........|<--decode_M-1-->|<--padding-->|
  463. Generation tokens can contain padding when cuda-graph is used.
  464. Currently, prompt tokens don't contain any padding.
  465. The prompts might have different lengths, while the generation tokens
  466. always have length 1.
  467. If chunked prefill is enabled, prefill tokens and decode tokens can be
  468. batched together in a flattened 1D query.
  469. |<----- num_prefill_tokens ---->|<------- num_decode_tokens --------->|
  470. |<-prefill_0->|...|<-prefill_N-1->|<--decode_0-->|...|<--decode_M-1-->|
  471. Currently, cuda graph is disabled for chunked prefill, meaning there's no
  472. padding between prefill and decode tokens.
  473. """
  474. def __init__(
  475. self,
  476. num_heads: int,
  477. head_size: int,
  478. scale: float,
  479. num_kv_heads: int,
  480. alibi_slopes: Optional[List[float]],
  481. sliding_window: Optional[int],
  482. kv_cache_dtype: str,
  483. blocksparse_params: Optional[Dict[str, Any]] = None,
  484. logits_soft_cap: Optional[float] = None,
  485. ) -> None:
  486. if blocksparse_params is not None:
  487. raise ValueError(
  488. "FlashAttention does not support block-sparse attention.")
  489. self.num_heads = num_heads
  490. self.head_size = head_size
  491. self.scale = float(scale)
  492. self.num_kv_heads = num_kv_heads
  493. if alibi_slopes is not None:
  494. alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
  495. self.alibi_slopes = alibi_slopes
  496. self.sliding_window = ((sliding_window, sliding_window)
  497. if sliding_window is not None else (-1, -1))
  498. self.kv_cache_dtype = kv_cache_dtype
  499. if logits_soft_cap is None:
  500. # In flash-attn, setting logits_soft_cap as 0 means no soft cap.
  501. logits_soft_cap = 0
  502. self.logits_soft_cap = logits_soft_cap
  503. assert self.num_heads % self.num_kv_heads == 0
  504. self.num_queries_per_kv = self.num_heads // self.num_kv_heads
  505. if sliding_window is not None:
  506. # NOTE: flash-attn's sliding window does not work with
  507. # paged KV cache.
  508. raise ValueError(
  509. "Sliding window is not supported in FlashAttention.")
  510. support_head_sizes = FlashAttentionBackend.get_supported_head_sizes()
  511. if head_size not in support_head_sizes:
  512. raise ValueError(
  513. f"Head size {head_size} is not supported by FlashAttention. "
  514. f"Supported head sizes are: {support_head_sizes}.")
  515. def forward(
  516. self,
  517. query: torch.Tensor,
  518. key: torch.Tensor,
  519. value: torch.Tensor,
  520. kv_cache: torch.Tensor,
  521. attn_metadata: FlashAttentionMetadata,
  522. k_scale: float = 1.0,
  523. v_scale: float = 1.0,
  524. attn_type: AttentionType = AttentionType.DECODER,
  525. ) -> torch.Tensor:
  526. """Forward pass with FlashAttention.
  527. Args:
  528. query: shape = [num_tokens, num_heads * head_size]
  529. key: shape = [num_tokens, num_kv_heads * head_size]
  530. value: shape = [num_tokens, num_kv_heads * head_size]
  531. kv_cache = [2, num_blocks, block_size, num_kv_heads, head_size]
  532. attn_metadata: Metadata for attention.
  533. Returns:
  534. shape = [num_tokens, num_heads * head_size]
  535. """
  536. if attn_type != AttentionType.DECODER:
  537. raise NotImplementedError("Encoder self-attention and "
  538. "encoder/decoder cross-attention "
  539. "are not implemented for "
  540. "FlashAttentionImpl")
  541. # NOTE: FlashAttention does not support FP8 KV cache.
  542. assert k_scale == 1.0 and v_scale == 1.0, (
  543. "key/v_scale is not supported in FlashAttention.")
  544. num_tokens, hidden_size = query.shape
  545. # Reshape the query, key, and value tensors.
  546. query = query.view(-1, self.num_heads, self.head_size)
  547. key = key.view(-1, self.num_kv_heads, self.head_size)
  548. value = value.view(-1, self.num_kv_heads, self.head_size)
  549. if kv_cache is not None:
  550. key_cache = kv_cache[0]
  551. value_cache = kv_cache[1]
  552. # Reshape the input keys and values and store them in the cache.
  553. # If kv_cache is not provided, the new key and value tensors are
  554. # not cached. This happens during the initial memory profiling run.
  555. ops.reshape_and_cache_flash(
  556. key,
  557. value,
  558. key_cache,
  559. value_cache,
  560. attn_metadata.slot_mapping.flatten(),
  561. self.kv_cache_dtype,
  562. k_scale,
  563. v_scale,
  564. )
  565. num_prefill_tokens = attn_metadata.num_prefill_tokens
  566. num_decode_tokens = attn_metadata.num_decode_tokens
  567. assert key.shape[0] == num_prefill_tokens + num_decode_tokens
  568. assert value.shape[0] == num_prefill_tokens + num_decode_tokens
  569. output = torch.empty_like(query)
  570. # Query for decode. KV is not needed because it is already cached.
  571. decode_query = query[num_prefill_tokens:]
  572. # QKV for prefill.
  573. query = query[:num_prefill_tokens]
  574. key = key[:num_prefill_tokens]
  575. value = value[:num_prefill_tokens]
  576. assert query.shape[0] == num_prefill_tokens
  577. assert decode_query.shape[0] == num_decode_tokens
  578. if prefill_meta := attn_metadata.prefill_metadata:
  579. # Prompt run.
  580. if (kv_cache is None or prefill_meta.block_tables is None
  581. or prefill_meta.block_tables.numel() == 0):
  582. # normal attention
  583. # When block_tables are not filled, it means q and k are the
  584. # prompt, and they have the same length.
  585. out = torch.ops.aphrodite.flash_attn_varlen_func(
  586. q=query,
  587. k=key,
  588. v=value,
  589. cu_seqlens_q=prefill_meta.seq_start_loc,
  590. cu_seqlens_k=prefill_meta.seq_start_loc,
  591. max_seqlen_q=prefill_meta.max_prefill_seq_len,
  592. max_seqlen_k=prefill_meta.max_prefill_seq_len,
  593. softmax_scale=self.scale,
  594. causal=True,
  595. window_size=self.sliding_window,
  596. alibi_slopes=self.alibi_slopes,
  597. softcap=self.logits_soft_cap,
  598. )
  599. assert output[:num_prefill_tokens].shape == out.shape
  600. output[:num_prefill_tokens] = out
  601. else:
  602. # prefix-enabled attention
  603. assert prefill_meta.seq_lens is not None
  604. max_seq_len = max(prefill_meta.seq_lens)
  605. output[:
  606. num_prefill_tokens] = torch.ops.aphrodite.flash_attn_varlen_func( # noqa
  607. q=query,
  608. k=key_cache,
  609. v=value_cache,
  610. cu_seqlens_q=prefill_meta.query_start_loc,
  611. max_seqlen_q=prefill_meta.max_query_len,
  612. cu_seqlens_k=prefill_meta.seq_start_loc,
  613. max_seqlen_k=max_seq_len,
  614. softmax_scale=self.scale,
  615. causal=True,
  616. alibi_slopes=self.alibi_slopes,
  617. block_table=prefill_meta.block_tables,
  618. softcap=self.logits_soft_cap,
  619. )
  620. if decode_meta := attn_metadata.decode_metadata:
  621. # Decoding run.
  622. output[
  623. num_prefill_tokens:] = torch.ops.aphrodite.flash_attn_with_kvcache( # noqa
  624. decode_query.unsqueeze(1),
  625. key_cache,
  626. value_cache,
  627. block_table=decode_meta.block_tables,
  628. cache_seqlens=decode_meta.seq_lens_tensor,
  629. softmax_scale=self.scale,
  630. causal=True,
  631. alibi_slopes=self.alibi_slopes,
  632. softcap=self.logits_soft_cap,
  633. ).squeeze(1)
  634. # Reshape the output tensor.
  635. return output.view(num_tokens, hidden_size)