vllm.v1.attention.backends.flex_attention
Attention layer with FlexAttention.
create_block_mask_compiled module-attribute
¶
create_block_mask_compiled = compile(
create_block_mask,
fullgraph=True,
mode="reduce-overhead",
)
flex_attention_compiled module-attribute
¶
flex_attention_compiled = compile(
flex_attention, fullgraph=True
)
FlexAttentionBackend ¶
Bases: AttentionBackend
Source code in vllm/v1/attention/backends/flex_attention.py
get_builder_cls staticmethod
¶
get_builder_cls() -> type[FlexAttentionMetadataBuilder]
get_impl_cls staticmethod
¶
get_impl_cls() -> type[FlexAttentionImpl]
get_kv_cache_shape staticmethod
¶
get_metadata_cls staticmethod
¶
get_metadata_cls() -> type[AttentionMetadata]
get_supported_dtypes classmethod
¶
FlexAttentionImpl ¶
Bases: AttentionImpl
Source code in vllm/v1/attention/backends/flex_attention.py
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 |
|
__init__ ¶
__init__(
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
attn_type: AttentionType = DECODER,
kv_sharing_target_layer_name: Optional[str] = None,
**kwargs,
) -> None
Source code in vllm/v1/attention/backends/flex_attention.py
forward ¶
forward(
layer: Module,
query: Tensor,
key: Tensor,
value: Tensor,
kv_cache: Tensor,
attn_metadata: FlexAttentionMetadata,
output: Optional[Tensor] = None,
output_scale: Optional[Tensor] = None,
output_block_scale: Optional[Tensor] = None,
) -> Tensor
Forward pass with FLexAttention.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query | Tensor | shape = [num_tokens, num_heads, head_size] | required |
key | Tensor | shape = [num_tokens, num_kv_heads, head_size] | required |
value | Tensor | shape = [num_tokens, num_kv_heads, head_size] | required |
attn_metadata | FlexAttentionMetadata | Metadata for attention. | required |
Returns: shape = [num_tokens, num_heads * head_size]
Source code in vllm/v1/attention/backends/flex_attention.py
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 |
|
view_as_4d staticmethod
¶
FlexAttentionMetadata dataclass
¶
Source code in vllm/v1/attention/backends/flex_attention.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 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 |
|
logical_mask_mod class-attribute
instance-attribute
¶
logical_mask_mod: _mask_mod_signature = causal_mask_mod
transformed_score_mod class-attribute
instance-attribute
¶
transformed_score_mod: Optional[_score_mod_signature] = None
__init__ ¶
__init__(
causal: bool,
num_actual_tokens: int,
max_query_len: int,
query_start_loc: Tensor,
max_seq_len: int,
seq_lens: Tensor,
block_table: Tensor,
slot_mapping: Tensor,
use_cascade: bool,
common_prefix_len: int,
cu_prefix_query_lens: Optional[Tensor],
prefix_kv_lens: Optional[Tensor],
suffix_kv_lens: Optional[Tensor],
total_cache_tokens: int,
block_size: int,
max_possible_sequence_length: int,
num_reqs: int,
physical_to_logical: Tensor,
decode_offset: Tensor,
num_blocks_per_seq: Tensor,
num_input_tokens: int = 0,
block_mask: Optional[BlockMask] = None,
score_mod: Optional[_score_mod_signature] = None,
logical_mask_mod: _mask_mod_signature = causal_mask_mod,
doc_ids: Optional[Tensor] = None,
direct_build: bool = True,
q_block_size: int = 16,
kv_block_size: int = 16,
transformed_score_mod: Optional[
_score_mod_signature
] = None,
) -> None
__post_init__ ¶
Source code in vllm/v1/attention/backends/flex_attention.py
_build_block_mask_direct ¶
_build_block_mask_direct() -> BlockMask
Direct block mask construction for standard causal 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 (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
_convert_physical_to_logical ¶
_convert_physical_to_logical(
request_lookup: Tensor,
q_idx: Tensor,
physical_kv_idx: Tensor,
) -> tuple[Tensor, Tensor, Tensor]
Convert physical indices to logical indices for both query and kv.
NB is_within_lower_bound: do sequences start on block_boundaries?
Returns:
Type | Description |
---|---|
tuple[Tensor, Tensor, Tensor] | tuple of (is_valid, logical_q_idx, logical_kv_idx) |
Source code in vllm/v1/attention/backends/flex_attention.py
build_block_mask ¶
build_block_mask() -> BlockMask
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_causal_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_transformed_score_mod ¶
get_transformed_score_mod() -> Optional[
_score_mod_signature
]
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
FlexAttentionMetadataBuilder ¶
Bases: AttentionMetadataBuilder[FlexAttentionMetadata]
Source code in vllm/v1/attention/backends/flex_attention.py
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 |
|
kv_block_size instance-attribute
¶
kv_block_size: int = (
16 if is_torch_equal_or_newer("2.9.0.dev0") else 128
)
q_block_size instance-attribute
¶
q_block_size: int = (
16 if is_torch_equal_or_newer("2.9.0.dev0") else 128
)
__init__ ¶
__init__(
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: device,
)
Source code in vllm/v1/attention/backends/flex_attention.py
build ¶
build(
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> FlexAttentionMetadata
Source code in vllm/v1/attention/backends/flex_attention.py
reorder_batch ¶
reorder_batch(
input_batch: InputBatch,
scheduler_output: SchedulerOutput,
) -> bool
_offsets_to_doc_ids_tensor ¶
Source code in vllm/v1/attention/backends/flex_attention.py
causal_mask_mod ¶
get_kernel_options ¶
get_kernel_options(
query, block_m, block_n, use_direct_build: bool
) -> dict[str, Union[int, bool]]
Source code in vllm/v1/attention/backends/flex_attention.py
pad_to_multiple ¶
Source code in vllm/v1/attention/backends/flex_attention.py
physical_to_logical_mapping ¶
physical_to_logical_mapping(
block_table: Tensor,
seq_lens: Tensor,
block_size: int,
total_blocks: int,
) -> Tensor
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 first (minimum) 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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
block_table | Tensor | Tensor of shape [max_reqs, max_num_blocks] mapping logical blocks to physical locations. May contain garbage values in unused positions. | required |
seq_lens | Tensor | Tensor of sequence lengths for each request. Used to determine how many blocks are actually needed per sequence. | required |
block_size | int | Size of each block in tokens. Used with seq_lens to compute the number of valid blocks per sequence. | required |
total_blocks | int | Total number of physical blocks available | required |
Returns:
Type | Description |
---|---|
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
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 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 |
|
unique_static_unsorted ¶
unique_static_unsorted(
x: Tensor,
*,
M: int,
dim: int = -1,
ignored_val: int = 0,
pad_val: int = -1,
) -> Tensor
- 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]