test_attention.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import random
  2. from typing import List, Optional, Tuple
  3. import pytest
  4. import torch
  5. from xformers import ops as xops
  6. from xformers.ops.fmha.attn_bias import BlockDiagonalCausalMask
  7. from aphrodite import _custom_ops as ops
  8. from aphrodite.common.utils import get_max_shared_memory_bytes, is_hip
  9. from tests.kernels.utils import opcheck
  10. from .allclose_default import get_default_atol, get_default_rtol
  11. FLOAT32_BYTES = torch.finfo(torch.float).bits // 8
  12. # This will change depending on the compute capability.
  13. # - 512 as a buffer
  14. MAX_SEQ_LEN = get_max_shared_memory_bytes() // FLOAT32_BYTES - 512
  15. # There may not be enough gpu memory due to large NUM_BLOCKS.
  16. # Reduce NUM_BLOCKS when it happens.
  17. NUM_BLOCKS = 4321 # Arbitrary values for testing
  18. PARTITION_SIZE = 512
  19. # flshattF and tritonflashattF supported: {torch.float16, torch.bfloat16}
  20. DTYPES = [torch.half, torch.bfloat16, torch.float
  21. ] if not is_hip() else [torch.half, torch.bfloat16]
  22. NUM_GEN_SEQS = [7] # Arbitrary values for testing
  23. NUM_PREFILL_SEQS = [3] # Arbitrary values for testing
  24. NUM_HEADS = [(40, 40), (64, 8)] # Arbitrary values for testing
  25. # FlashAttention forward only supports head dimension at most 128
  26. # https://github.com/ROCmSoftwarePlatform/flash-attention/blob/3d2b6f5d037782cc2c906909a46fb7e2e1b48b25/csrc/flash_attn_rocm/flash_api.cpp#L62
  27. HEAD_SIZES = [64, 80, 96, 112, 120, 128, 192, 256
  28. ] if not is_hip() else [64, 80, 96, 112, 128]
  29. BLOCK_SIZES = [16, 32]
  30. USE_ALIBI = [False, True]
  31. KV_CACHE_DTYPE = ["auto", "fp8"]
  32. SEEDS = [0]
  33. CUDA_DEVICES = [
  34. f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)
  35. ]
  36. def ref_masked_attention(
  37. query: torch.Tensor,
  38. key: torch.Tensor,
  39. value: torch.Tensor,
  40. scale: float,
  41. attn_mask: Optional[torch.Tensor] = None,
  42. ) -> torch.Tensor:
  43. attn_weights = scale * torch.einsum("qhd,khd->hqk", query, key).float()
  44. if attn_mask is not None:
  45. attn_weights = attn_weights + attn_mask.float()
  46. attn_weights = torch.softmax(attn_weights, dim=-1).to(value.dtype)
  47. out = torch.einsum("hqk,khd->qhd", attn_weights, value)
  48. return out
  49. def ref_single_query_cached_kv_attention(
  50. output: torch.Tensor,
  51. query: torch.Tensor,
  52. num_queries_per_kv: int,
  53. key_cache: torch.Tensor,
  54. value_cache: torch.Tensor,
  55. block_tables: torch.Tensor,
  56. seq_lens: torch.Tensor,
  57. scale: float,
  58. alibi_slopes: Optional[torch.Tensor],
  59. ) -> None:
  60. num_query_heads = query.shape[1]
  61. num_kv_heads = value_cache.shape[1]
  62. head_size = value_cache.shape[2]
  63. block_size = value_cache.shape[3]
  64. num_seqs = query.shape[0]
  65. block_tables_lst = block_tables.cpu().tolist()
  66. seq_lens_lst = seq_lens.cpu().tolist()
  67. for i in range(num_seqs):
  68. q = query[i].unsqueeze(0)
  69. block_table = block_tables_lst[i]
  70. seq_len = int(seq_lens_lst[i])
  71. keys_lst: List[torch.Tensor] = []
  72. values_lst: List[torch.Tensor] = []
  73. for j in range(seq_len):
  74. block_number = int(block_table[j // block_size])
  75. block_offset = j % block_size
  76. k = key_cache[block_number, :, :, block_offset, :]
  77. k = k.reshape(num_kv_heads, head_size)
  78. keys_lst.append(k)
  79. v = value_cache[block_number, :, :, block_offset]
  80. values_lst.append(v)
  81. keys = torch.stack(keys_lst, dim=0)
  82. values = torch.stack(values_lst, dim=0)
  83. if num_queries_per_kv > 1:
  84. # Handle MQA and GQA
  85. keys = torch.repeat_interleave(keys, num_queries_per_kv, dim=1)
  86. values = torch.repeat_interleave(values, num_queries_per_kv, dim=1)
  87. alibi_bias = None
  88. if alibi_slopes is not None:
  89. # Create the ALiBi bias used in the paged attention kernel.
  90. position_ids = torch.arange(seq_len).int()
  91. alibi_bias = (position_ids - seq_len + 1).float()
  92. alibi_bias = alibi_slopes.view(-1, 1, 1) * alibi_bias.view(
  93. 1, 1, -1)
  94. out = ref_masked_attention(q, keys, values, scale, alibi_bias)
  95. out = out.view(num_query_heads, head_size)
  96. output[i].copy_(out, non_blocking=True)
  97. @pytest.mark.parametrize("version", ["v1", "v2"])
  98. @pytest.mark.parametrize("num_seqs", NUM_GEN_SEQS)
  99. @pytest.mark.parametrize("num_heads", NUM_HEADS)
  100. @pytest.mark.parametrize("head_size", HEAD_SIZES)
  101. @pytest.mark.parametrize("use_alibi", USE_ALIBI)
  102. @pytest.mark.parametrize("block_size", BLOCK_SIZES)
  103. @pytest.mark.parametrize("dtype", DTYPES)
  104. @pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE)
  105. @pytest.mark.parametrize("seed", SEEDS)
  106. @pytest.mark.parametrize("device", CUDA_DEVICES)
  107. def test_paged_attention(
  108. kv_cache_factory,
  109. version: str,
  110. num_seqs: int,
  111. num_heads: Tuple[int, int],
  112. head_size: int,
  113. use_alibi: bool,
  114. block_size: int,
  115. dtype: torch.dtype,
  116. kv_cache_dtype: str,
  117. seed: int,
  118. device: str,
  119. ) -> None:
  120. if kv_cache_dtype == "fp8" and head_size % 16:
  121. pytest.skip()
  122. random.seed(seed)
  123. torch.random.manual_seed(seed)
  124. if torch.cuda.is_available():
  125. torch.cuda.manual_seed(seed)
  126. torch.set_default_device(device)
  127. scale = float(1.0 / (head_size**0.5))
  128. num_query_heads, num_kv_heads = num_heads
  129. query = torch.empty(num_seqs, num_query_heads, head_size, dtype=dtype)
  130. query.uniform_(-scale, scale)
  131. assert num_query_heads % num_kv_heads == 0
  132. num_queries_per_kv = num_query_heads // num_kv_heads
  133. alibi_slopes = None
  134. if use_alibi:
  135. alibi_slopes = torch.randn(num_query_heads, dtype=torch.float)
  136. seq_lens = [random.randint(1, MAX_SEQ_LEN) for _ in range(num_seqs)]
  137. seq_lens[-1] = MAX_SEQ_LEN
  138. max_seq_len = max(seq_lens)
  139. seq_lens = torch.tensor(seq_lens, dtype=torch.int)
  140. # Create the block tables.
  141. max_num_blocks_per_seq = (max_seq_len + block_size - 1) // block_size
  142. block_tables_lst: List[List[int]] = []
  143. for _ in range(num_seqs):
  144. block_table = [
  145. random.randint(0, NUM_BLOCKS - 1)
  146. for _ in range(max_num_blocks_per_seq)
  147. ]
  148. block_tables_lst.append(block_table)
  149. block_tables = torch.tensor(block_tables_lst, dtype=torch.int)
  150. # Create the KV caches.
  151. key_caches, value_caches = kv_cache_factory(NUM_BLOCKS, block_size, 1,
  152. num_kv_heads, head_size,
  153. kv_cache_dtype, dtype, seed,
  154. device)
  155. key_cache, value_cache = key_caches[0], value_caches[0]
  156. # Using default kv_scale
  157. k_scale = v_scale = 1.0
  158. # Call the paged attention kernel.
  159. output = torch.empty_like(query)
  160. if version == "v1":
  161. ops.paged_attention_v1(
  162. output,
  163. query,
  164. key_cache,
  165. value_cache,
  166. num_kv_heads,
  167. scale,
  168. block_tables,
  169. seq_lens,
  170. block_size,
  171. max_seq_len,
  172. alibi_slopes,
  173. kv_cache_dtype,
  174. k_scale,
  175. v_scale,
  176. )
  177. opcheck(torch.ops._C.paged_attention_v1,
  178. (output, query, key_cache, value_cache, num_kv_heads, scale,
  179. block_tables, seq_lens, block_size, max_seq_len, alibi_slopes,
  180. kv_cache_dtype, k_scale, v_scale, 0, 0, 0, 64, 0),
  181. cond=(head_size == HEAD_SIZES[0]))
  182. elif version == "v2":
  183. num_partitions = ((max_seq_len + PARTITION_SIZE - 1) // PARTITION_SIZE)
  184. assert PARTITION_SIZE % block_size == 0
  185. num_seqs, num_heads, head_size = output.shape
  186. tmp_output = torch.empty(
  187. size=(num_seqs, num_heads, num_partitions, head_size),
  188. dtype=output.dtype,
  189. )
  190. exp_sums = torch.empty(
  191. size=(num_seqs, num_heads, num_partitions),
  192. dtype=torch.float32,
  193. )
  194. max_logits = torch.empty_like(exp_sums)
  195. ops.paged_attention_v2(
  196. output,
  197. exp_sums,
  198. max_logits,
  199. tmp_output,
  200. query,
  201. key_cache,
  202. value_cache,
  203. num_kv_heads,
  204. scale,
  205. block_tables,
  206. seq_lens,
  207. block_size,
  208. max_seq_len,
  209. alibi_slopes,
  210. kv_cache_dtype,
  211. k_scale,
  212. v_scale,
  213. )
  214. opcheck(torch.ops._C.paged_attention_v2,
  215. (output, exp_sums, max_logits, tmp_output, query, key_cache,
  216. value_cache, num_kv_heads, scale, block_tables, seq_lens,
  217. block_size, max_seq_len, alibi_slopes, kv_cache_dtype,
  218. k_scale, v_scale, 0, 0, 0, 64, 0),
  219. cond=(head_size == HEAD_SIZES[0]))
  220. else:
  221. raise AssertionError(f"Unknown version: {version}")
  222. # Run the reference implementation.
  223. if kv_cache_dtype == "fp8":
  224. # Convert cache data back to dtype.
  225. x = 16 // torch.tensor([], dtype=dtype).element_size()
  226. key_cache_shape = (NUM_BLOCKS, num_kv_heads, head_size // x,
  227. block_size, x)
  228. dequantized_key_cache = torch.empty(size=key_cache_shape,
  229. dtype=dtype,
  230. device=device)
  231. ops.convert_fp8(dequantized_key_cache, key_cache)
  232. key_cache = dequantized_key_cache
  233. value_cache_shape = value_cache.shape
  234. dequantized_value_cache = torch.empty(size=value_cache_shape,
  235. dtype=dtype,
  236. device=device)
  237. ops.convert_fp8(dequantized_value_cache, value_cache)
  238. value_cache = dequantized_value_cache
  239. ref_output = torch.empty_like(query)
  240. ref_single_query_cached_kv_attention(
  241. ref_output,
  242. query,
  243. num_queries_per_kv,
  244. key_cache,
  245. value_cache,
  246. block_tables,
  247. seq_lens,
  248. scale,
  249. alibi_slopes,
  250. )
  251. # NOTE(woosuk): Due to the kernel-level differences in the two
  252. # implementations, there is a small numerical difference in the two
  253. # outputs. Thus, we use a relaxed tolerance for the test.
  254. atol = get_default_atol(output) if is_hip() else 1e-3
  255. rtol = get_default_rtol(output) if is_hip() else 1e-5
  256. # NOTE(zhaoyang): FP8 KV Cache will introduce quantization error,
  257. # so we use a relaxed tolerance for the test.
  258. atol, rtol = 1e-3, 1e-5
  259. if kv_cache_dtype == "fp8":
  260. atol, rtol = 1e-2, 1e-5
  261. torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol)
  262. def ref_multi_query_kv_attention(
  263. cu_seq_lens: List[int],
  264. query: torch.Tensor,
  265. key: torch.Tensor,
  266. value: torch.Tensor,
  267. scale: float,
  268. dtype: torch.dtype,
  269. ) -> torch.Tensor:
  270. num_seqs = len(cu_seq_lens) - 1
  271. ref_outputs: List[torch.Tensor] = []
  272. for i in range(num_seqs):
  273. start_idx = cu_seq_lens[i]
  274. end_idx = cu_seq_lens[i + 1]
  275. seq_len = end_idx - start_idx
  276. # Create attention mask.
  277. attn_mask = torch.triu(torch.ones(seq_len, seq_len, dtype=dtype),
  278. diagonal=1)
  279. attn_mask = attn_mask * torch.finfo(dtype).min
  280. attn_mask = attn_mask.to(dtype=dtype)
  281. ref_output = ref_masked_attention(
  282. query[start_idx:end_idx],
  283. key[start_idx:end_idx],
  284. value[start_idx:end_idx],
  285. scale,
  286. attn_mask=attn_mask,
  287. )
  288. ref_outputs.append(ref_output)
  289. return torch.cat(ref_outputs, dim=0)
  290. # TODO(woosuk): Add tests for USE_ALIBI=True.
  291. @pytest.mark.parametrize("num_seqs", NUM_PREFILL_SEQS)
  292. @pytest.mark.parametrize("num_heads", NUM_HEADS)
  293. @pytest.mark.parametrize("head_size", HEAD_SIZES)
  294. @pytest.mark.parametrize("dtype", DTYPES)
  295. @pytest.mark.parametrize("seed", SEEDS)
  296. @pytest.mark.parametrize("device", CUDA_DEVICES)
  297. @torch.inference_mode()
  298. def test_multi_query_kv_attention(
  299. num_seqs: int,
  300. num_heads: Tuple[int, int],
  301. head_size: int,
  302. dtype: torch.dtype,
  303. seed: int,
  304. device: str,
  305. ) -> None:
  306. random.seed(seed)
  307. torch.random.manual_seed(seed)
  308. if torch.cuda.is_available():
  309. torch.cuda.manual_seed(seed)
  310. torch.set_default_device(device)
  311. # MAX_SEQ_LEN sometimes causes OOM in the reference implementation.
  312. # As the xformers library is already tested with its own tests, we can use
  313. # a smaller MAX_SEQ_LEN here.
  314. max_len = min(MAX_SEQ_LEN, 4096)
  315. seq_lens = random.sample(range(1, max_len), num_seqs)
  316. num_tokens = sum(seq_lens)
  317. scale = float(1.0 / (head_size**0.5))
  318. num_query_heads, num_kv_heads = num_heads
  319. qkv = torch.empty(num_tokens,
  320. num_query_heads + 2 * num_kv_heads,
  321. head_size,
  322. dtype=dtype)
  323. qkv.uniform_(-scale, scale)
  324. query, key, value = qkv.split(
  325. [num_query_heads, num_kv_heads, num_kv_heads], dim=1)
  326. num_queries_per_kv = num_query_heads // num_kv_heads
  327. if num_queries_per_kv > 1:
  328. # Handle MQA and GQA
  329. key = torch.repeat_interleave(key, num_queries_per_kv, dim=1)
  330. value = torch.repeat_interleave(value, num_queries_per_kv, dim=1)
  331. attn_bias = BlockDiagonalCausalMask.from_seqlens(seq_lens)
  332. output = xops.memory_efficient_attention_forward(
  333. query.unsqueeze(0),
  334. key.unsqueeze(0),
  335. value.unsqueeze(0),
  336. attn_bias=attn_bias,
  337. p=0.0,
  338. scale=scale,
  339. )
  340. output = output.squeeze(0)
  341. cu_seq_lens = [0]
  342. for seq_len in seq_lens:
  343. cu_seq_lens.append(cu_seq_lens[-1] + seq_len)
  344. ref_output = ref_multi_query_kv_attention(
  345. cu_seq_lens,
  346. query,
  347. key,
  348. value,
  349. scale,
  350. dtype,
  351. )
  352. atol = get_default_atol(output) if is_hip() else 1e-3
  353. rtol = get_default_rtol(output) if is_hip() else 1e-5
  354. torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol)