vllm.v1.attention.backends.flex_attention ¶
Attention layer with FlexAttention.
Classes:
-
BlockSparsityHint–This prunes KV blocks from the BlockMask before the flex_attention kernel
-
FlexAttentionBackend– -
FlexAttentionImpl– -
FlexAttentionMetadata–
Functions:
-
physical_to_logical_mapping–Creates an inverse mapping from physical block locations to logical indices.
-
unique_static_unsorted–- Keeps the first occurrence of each non-zero value while preserving order,
BlockSparsityHint ¶
Bases: NamedTuple
This prunes KV blocks from the BlockMask before the flex_attention kernel is invoked, so that blocks that are fully masked never get loaded. Use this with custom mask_mods that are sparse to avoid the kernel iterating over all KV blocks unnecessarily.
Attributes:
-
hint_fn(_block_sparsity_hint_signature) –(q_block_idx [num_tokens, 1], kv_block_idx [1, num_kv_blocks], block_size int) -> bool Tensor [num_tokens, num_kv_blocks]. Returns True for block pairs that may contain non-masked elements.
Source code in vllm/v1/attention/backends/flex_attention.py
FlexAttentionBackend ¶
Bases: AttentionBackend
Methods:
-
supports_attn_type–FlexAttention supports both decoder and encoder-only attention.
-
supports_mm_prefix–FlexAttention supports full attention for image tokens.
Source code in vllm/v1/attention/backends/flex_attention.py
supports_attn_type(attn_type) classmethod ¶
FlexAttention supports both decoder and encoder-only attention.
FlexAttentionImpl ¶
Bases: AttentionImpl
Methods:
-
forward–Forward pass with FLexAttention.
-
view_as_4d–View a 3d tensor as 4D.
Source code in vllm/v1/attention/backends/flex_attention.py
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 | |
forward(layer, query, key, value, kv_cache, attn_metadata, output, output_scale=None, output_block_scale=None) ¶
Forward pass with FLexAttention.
Parameters:
-
(query¶Tensor) –shape = [num_tokens, num_heads, head_size]
-
(key¶Tensor) –shape = [num_tokens, num_kv_heads, head_size]
-
(value¶Tensor) –shape = [num_tokens, num_kv_heads, head_size]
-
(kv_cache¶Tensor) –shape = [num_blocks, 2, block_size, num_kv_heads, head_size]
-
(attn_metadata¶FlexAttentionMetadata) –Metadata for attention.
Returns: shape = [num_tokens, num_heads * head_size]
Source code in vllm/v1/attention/backends/flex_attention.py
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 | |
view_as_4d(tensor) staticmethod ¶
View a 3d tensor as 4D.
FlexAttentionMetadata dataclass ¶
Methods:
-
get_bidirectional_mask_mod–Creates the encoder mask_mod function for FlexAttention.
-
get_paged_mask_mod–Creates the mask_mod function for FlexAttention.
-
get_prefix_lm_mask_mod–Creates the prefix LM mask_mod function for FlexAttention.
-
get_rswa_mask_mod–Creates the Reference Sliding Window Attention (R-SWA) mask_mod.
-
get_sliding_window_mask_mod–Creates the sliding window mask_mod function for FlexAttention.
-
get_transformed_score_mod–Creates the transformed score_mod function for FlexAttention.
Source code in vllm/v1/attention/backends/flex_attention.py
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 | |
_build_block_mask_direct() ¶
Direct block mask construction for paged KV cache attention.
This method constructs the block mask directly using BlockMask.from_kv_blocks which is much more efficient than the generic create_block_mask approach.
The direct path works as follows: 1. For each query token, fetch blocks from block_table using max_seq_len and exclude out of sliding window blocks if needed. (this fetches more blocks than needed for shorter sequences) 2. Group query tokens into chunks of q_block_size 3. For each group, deduplicate the blocks using unique_static_unsorted 4. Create BlockMask using the deduplicated block indices
Over-estimation occurs when a group of q_block_size tokens contains multiple sequence IDs (doc_ids). In this case, we fetch ALL blocks for each sequence represented in the group, even though individual query tokens may only need a subset of those blocks based on causal masking and their position.
Source code in vllm/v1/attention/backends/flex_attention.py
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 | |
_convert_physical_to_logical(request_lookup, q_idx, physical_kv_idx) ¶
Convert physical indices to logical indices for both query and kv.
NB is_within_lower_bound: do sequences start on block_boundaries?
Returns:
Source code in vllm/v1/attention/backends/flex_attention.py
get_bidirectional_mask_mod() ¶
Creates the encoder mask_mod function for FlexAttention.
Since the encoder bidirectional attention doesn't run with KV cache, this function creates a mask based on the packed query sequences.
Source code in vllm/v1/attention/backends/flex_attention.py
get_paged_mask_mod() ¶
Creates the mask_mod function for FlexAttention.
This function creates the combined mask mod function that handles
- The paged attention block mapping
- The mapping from packed query sequences to logical query entries
It also by defaults adds the decoding offset to the query indices. With this info we create the "logical" indices that are passed to mask_mod functions. This allows mask mod functions to be agnostic to layout of the query and key/value tensors.
Source code in vllm/v1/attention/backends/flex_attention.py
get_prefix_lm_mask_mod() ¶
Creates the prefix LM mask_mod function for FlexAttention.
Source code in vllm/v1/attention/backends/flex_attention.py
get_rswa_mask_mod() ¶
Creates the Reference Sliding Window Attention (R-SWA) mask_mod.
R-SWA keeps the whole prefix (image + prompt tokens, i.e. logical index < prefix_len) globally visible while generated tokens additionally attend a fixed sliding window of recent tokens. This term is combined with the base causal mask via logical AND, so it only ever removes far-away generated tokens that fall outside the window and outside the prefix.
Source code in vllm/v1/attention/backends/flex_attention.py
get_sliding_window_mask_mod() ¶
Creates the sliding window mask_mod function for FlexAttention.
Note that the sliding window mask here is bidirectional, we need to mask it with the bidirectional/causal mask for encoder/decoder.
Source code in vllm/v1/attention/backends/flex_attention.py
get_transformed_score_mod() ¶
Creates the transformed score_mod function for FlexAttention.
This function wraps the user's score_mod to handle physical-to-logical index conversion, similar to how get_mask_mod works for mask functions.
Source code in vllm/v1/attention/backends/flex_attention.py
physical_to_logical_mapping(block_table, seq_lens, block_size, total_blocks) ¶
Creates an inverse mapping from physical block locations to logical indices.
The original block_table maps from logical blocks to physical locations:
Logical to Physical (Original block_table): ┌───────────────────────────────────────────┐ │ Request 0: │ │ │ │ Logical Blocks: 0 1 2 3 4 5 6 7 │ │ │ │ │ │ │ │ │ │ │ │ v v v v v v v v │ │ Physical Blocks: 3 5 1 7 4 2 0 6 │ └───────────────────────────────────────────┘
This function creates the inverse mapping:
Physical to Logical (Inverse mapping): ┌───────────────────────────────────────────┐ │ Request 0: │ │ │ │ Physical Blocks: 0 1 2 3 4 5 6 7 │ │ │ │ │ │ │ │ │ │ │ │ v v v v v v v v │ │ Logical Blocks: 6 2 5 0 4 1 7 3 │ └───────────────────────────────────────────┘
If multiple logical blocks map to the same physical block, this function returns the latest (maximum) logical block index.
If a physical block is not mapped to by any logical block, its value in the result will be -1.
IMPORTANT: Garbage Value Protection ──────────────────────────────────── The block_table tensor may contain garbage values in unused positions (beyond the actual sequence length). For example, if a sequence only needs 3 blocks but the table has space for 8:
block_table[0] = [10, 25, 7, 999, 1234, 888, ...]
^^^^^^^^^^^^^^^^^^^^
garbage values
These garbage values can cause issues because: 1. They may map to valid physical blocks by coincidence 2. The scatter_ operation will assign them logical indices 3. Later attention computations may incorrectly access these blocks
To prevent this, we use seq_lens and block_size to mask out unused entries, ensuring only valid block references are processed.
IMPORTANT: Reused physical blocks (sliding-window / hybrid attention) ──────────────────────────────────────────────────────────────────── For some attention types, physical cache blocks can be reused over time. This can cause the same physical block id to appear multiple times in a row of block_table at different logical block indices. In that case, only the latest logical block index corresponds to the current contents of that physical block. Therefore, the inverse mapping must pick the maximum logical block index for each physical block id.
Parameters:
-
(block_table¶Tensor) –Tensor of shape [max_reqs, max_num_blocks] mapping logical blocks to physical locations. May contain garbage values in unused positions.
-
(seq_lens¶Tensor) –Tensor of sequence lengths for each request. Used to determine how many blocks are actually needed per sequence.
-
(block_size¶int) –Size of each block in tokens. Used with seq_lens to compute the number of valid blocks per sequence.
-
(total_blocks¶int) –Total number of physical blocks available
Returns:
-
Tensor–A tensor of shape [max_reqs, total_blocks] where each entry
-
Tensor–physical_to_logical[req_id, physical_block] contains the logical
-
Tensor–block index for that physical block, or -1 if unused.
Source code in vllm/v1/attention/backends/flex_attention.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
unique_static_unsorted(x, *, M, dim=-1, ignored_val=0, pad_val=-1) ¶
- Keeps the first occurrence of each non-zero value while preserving order, then left-packs those uniques and fills the rest with
pad_val. - Returns (packed, keep_mask) with the same shape as
x. - Requires that all values be in the range [0, M]
- Skips ignored_val
Works on CPU or GPU, no Python loops, O(B·N) time / O(B·M) memory.
Example: x =[3, 1, 0, 1, 2], M=3, ignored_val=0 => [3, 1, 2, -1, -1]