Skip to content

vllm.v1.attention.backends.rocm_aiter_fa

Attention layer with AiterFlashAttention.

Classes:

AiterFlashAttentionBackend

Bases: AttentionBackend

Methods:

  • customize_spec –

    Validate the block size the ROCm gather kernels require, and under

  • supports_attn_type –

    ENCODER_DECODER is not supported because the prefill path uses

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
class AiterFlashAttentionBackend(AttentionBackend):
    supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]

    @classmethod
    def supports_sink(cls) -> bool:
        return True

    supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
        "auto",
        "float16",
        "bfloat16",
        "fp8",
        "fp8_e4m3",
        "fp8_e5m2",
    ]

    @classmethod
    def supports_attn_type(cls, attn_type: str) -> bool:
        """ENCODER_DECODER is not supported because the prefill path uses
        flash_attn_varlen_func with cu_seqlens_k set to decoder
        query_start_loc (not encoder seq lens) and causal=True, both of
        which are incorrect for cross-attention layers.
        """
        return attn_type in (AttentionType.DECODER,)

    @staticmethod
    def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
        return [16, 32]

    @classmethod
    def get_supported_head_sizes(cls) -> list[int]:
        return [64, 128, 256]

    forward_includes_kv_cache_update: bool = False
    # External KV writers produce the packed layout, not the shuffle layout.
    supports_kv_cache_update_bypass: bool = (
        not rocm_aiter_ops.is_shuffle_kv_cache_enabled()
    )

    @staticmethod
    def get_name() -> str:
        return "FLASH_ATTN"

    @classmethod
    def supports_sliding_window(cls) -> bool:
        return True

    @staticmethod
    def get_impl_cls() -> type["AiterFlashAttentionImpl"]:
        return AiterFlashAttentionImpl

    @staticmethod
    def get_builder_cls() -> type["AiterFlashAttentionMetadataBuilder"]:
        return AiterFlashAttentionMetadataBuilder

    @classmethod
    def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
        """Validate the block size the ROCm gather kernels require, and under
        the shuffle layout publish K and V as two head slots.

        The shuffle read/write kernels rearrange a whole `head_size x
        block_size` tile per side, so each side needs its own contiguous run
        in the page. Packed into the content dim they interleave per token
        instead, which no layout can undo.
        """
        # block_size == 1 is the per-token page-size probe (see
        # Platform.get_page_size_bytes); real blocks must be gatherable in
        # 16-token units by the ROCm kernel.
        if spec.block_size != 1 and spec.block_size % 16 != 0:
            raise ValueError("Block size must be a multiple of 16.")
        if not rocm_aiter_ops.is_shuffle_kv_cache_enabled():
            return spec
        if spec.state_content_bytes is not None:
            return spec
        assert spec.head_size == spec.head_size_v, (
            "Separate K/V head slots require symmetric K/V head sizes."
        )
        return replace(
            spec,
            num_head_slots=2,
            state_content_bytes=spec.num_kv_heads
            * spec.head_size
            * get_dtype_size(spec.dtype),
        )

    @classmethod
    def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
        if rocm_aiter_ops.is_shuffle_kv_cache_enabled():
            # pa_fwd_asm strides between pages by a whole dense page, so the two
            # head slots customize_spec publishes have to be separate planes
            # spanning every block: H outermost. Under LBHNC the slots alternate
            # block by block, doubling the stride the kernel assumes. LBHNC
            # stays listed for models whose mixed HNC shapes need a
            # block-compact layout; those read K/V by stride instead.
            return (KVCacheLayout.LHBNC, KVCacheLayout.LBHNC)
        # K and V come out of the content dim as transposed views rather than
        # copies, so the head dim may sit on either side of the block dim, but
        # the layer must stay outermost.
        return (KVCacheLayout.LBHNC, KVCacheLayout.LHBNC)

    @classmethod
    def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
        from vllm.platforms.rocm import get_cdna_version

        # DeviceCapability is currently created using torch.cuda.get_device_capability()
        # which is known to be buggy on rocm systems. on CDNA uses amd-smi which is
        # more reliable.
        return get_cdna_version() > 2

    @classmethod
    def supports_non_causal(cls) -> bool:
        return True

customize_spec(spec) classmethod

Validate the block size the ROCm gather kernels require, and under the shuffle layout publish K and V as two head slots.

The shuffle read/write kernels rearrange a whole head_size x block_size tile per side, so each side needs its own contiguous run in the page. Packed into the content dim they interleave per token instead, which no layout can undo.

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
@classmethod
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
    """Validate the block size the ROCm gather kernels require, and under
    the shuffle layout publish K and V as two head slots.

    The shuffle read/write kernels rearrange a whole `head_size x
    block_size` tile per side, so each side needs its own contiguous run
    in the page. Packed into the content dim they interleave per token
    instead, which no layout can undo.
    """
    # block_size == 1 is the per-token page-size probe (see
    # Platform.get_page_size_bytes); real blocks must be gatherable in
    # 16-token units by the ROCm kernel.
    if spec.block_size != 1 and spec.block_size % 16 != 0:
        raise ValueError("Block size must be a multiple of 16.")
    if not rocm_aiter_ops.is_shuffle_kv_cache_enabled():
        return spec
    if spec.state_content_bytes is not None:
        return spec
    assert spec.head_size == spec.head_size_v, (
        "Separate K/V head slots require symmetric K/V head sizes."
    )
    return replace(
        spec,
        num_head_slots=2,
        state_content_bytes=spec.num_kv_heads
        * spec.head_size
        * get_dtype_size(spec.dtype),
    )

supports_attn_type(attn_type) classmethod

ENCODER_DECODER is not supported because the prefill path uses flash_attn_varlen_func with cu_seqlens_k set to decoder query_start_loc (not encoder seq lens) and causal=True, both of which are incorrect for cross-attention layers.

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
@classmethod
def supports_attn_type(cls, attn_type: str) -> bool:
    """ENCODER_DECODER is not supported because the prefill path uses
    flash_attn_varlen_func with cu_seqlens_k set to decoder
    query_start_loc (not encoder seq lens) and causal=True, both of
    which are incorrect for cross-attention layers.
    """
    return attn_type in (AttentionType.DECODER,)

AiterFlashAttentionExtendKernel

Bases: VllmJitKernel['AiterFlashAttentionExtendKernel.CompileKey']

Warm the AITER varlen kernels that only an extend step reaches.

An extend is a prefill over cached tokens: a chunked-prefill continuation or a prefix-cache hit. AiterFlashAttentionImpl.extend_forward attends the new tokens causally and each gathered context chunk non-causally, both returning the LSE so merge_attn_states can combine them. A new prompt makes one causal call without the LSE, so it never selects these variants. AITER builds a module per variant on first use, which otherwise stalls the first request that needs one.

Sliding-window layers are skipped: their extend step runs the same windowed, LSE-free call as a new prompt.

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
class AiterFlashAttentionExtendKernel(
    VllmJitKernel["AiterFlashAttentionExtendKernel.CompileKey"]
):
    """Warm the AITER varlen kernels that only an extend step reaches.

    An extend is a prefill over cached tokens: a chunked-prefill continuation
    or a prefix-cache hit. `AiterFlashAttentionImpl.extend_forward` attends the
    new tokens causally and each gathered context chunk non-causally, both
    returning the LSE so `merge_attn_states` can combine them. A new prompt
    makes one causal call without the LSE, so it never selects these variants.
    AITER builds a module per variant on first use, which otherwise stalls the
    first request that needs one.

    Sliding-window layers are skipped: their extend step runs the same
    windowed, LSE-free call as a new prompt.
    """

    # AITER treats `max_seqlen_q == 1` as decode and drops `causal`, so the
    # warmup query must be longer than one token to select the causal variant.
    NUM_REQS = 2
    QUERY_LEN = 16
    CONTEXT_LEN = 64

    @dataclass(frozen=True)
    class CompileKey:
        dtype: torch.dtype
        head_dim: int
        qhead_per_kvhead: int
        causal: bool
        has_alibi: bool
        has_sinks: bool

    def get_warmup_keys(  # type: ignore[override]
        self,
        *,
        dtype: torch.dtype,
        head_dim: int,
        num_qo_heads: int,
        num_kv_heads: int,
        sliding_window: tuple[int, int],
        has_alibi: bool,
        has_sinks: bool,
    ) -> list[CompileKey]:
        if sliding_window[0] != -1:
            return []

        def key(causal: bool, has_sinks: bool):
            return self.CompileKey(
                dtype=dtype,
                head_dim=head_dim,
                qhead_per_kvhead=num_qo_heads // num_kv_heads,
                causal=causal,
                has_alibi=has_alibi,
                has_sinks=has_sinks,
            )

        # `extend_forward` passes the sinks to the causal call only, so each
        # context chunk's LSE does not count them twice on merge.
        return [key(True, has_sinks), key(False, False)]

    def compile(self, compile_key: CompileKey) -> None:
        device = torch.device(current_platform.device_type)
        heads = compile_key.qhead_per_kvhead
        # The causal call attends the new tokens alone; the non-causal call
        # attends a gathered context chunk longer than the query.
        key_len = self.QUERY_LEN if compile_key.causal else self.CONTEXT_LEN

        def lens(length: int) -> torch.Tensor:
            return torch.arange(
                0,
                (self.NUM_REQS + 1) * length,
                length,
                dtype=torch.int32,
                device=device,
            )

        def tokens(length: int, num_heads: int) -> torch.Tensor:
            return torch.zeros(
                (self.NUM_REQS * length, num_heads, compile_key.head_dim),
                dtype=compile_key.dtype,
                device=device,
            )

        rocm_aiter_ops.flash_attn_varlen_func(
            q=tokens(self.QUERY_LEN, heads),
            k=tokens(key_len, 1),
            v=tokens(key_len, 1),
            cu_seqlens_q=lens(self.QUERY_LEN),
            cu_seqlens_k=lens(key_len),
            max_seqlen_q=self.QUERY_LEN,
            max_seqlen_k=key_len,
            # Must match the serving calls: AITER names the module after a zero
            # min_seqlen_q, so a nonzero value here builds a module serving never uses.
            min_seqlen_q=0,
            dropout_p=0.0,
            softmax_scale=compile_key.head_dim**-0.5,
            causal=compile_key.causal,
            window_size=(-1, -1),
            alibi_slopes=(
                torch.ones(heads, dtype=torch.float32, device=device)
                if compile_key.has_alibi
                else None
            ),
            return_lse=True,
            sink_ptr=(
                torch.zeros(heads, dtype=torch.float32, device=device)
                if compile_key.has_sinks
                else None
            ),
        )
        torch.accelerator.synchronize()
        self._compiled_cache[compile_key] = True

AiterFlashAttentionImpl

Bases: AttentionImpl

Methods:

  • forward –

    Forward pass with AiterFlashAttention.

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
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
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
class AiterFlashAttentionImpl(AttentionImpl):
    _kv_view_cache: (
        tuple[
            torch.Tensor,
            int,
            tuple[torch.Tensor, torch.Tensor],
            tuple[torch.Tensor, torch.Tensor],
        ]
        | None
    ) = None

    def __init__(
        self,
        num_heads: int,
        head_size: int,
        scale: float,
        num_kv_heads: int,
        alibi_slopes: list[float] | None,
        sliding_window: int | None,
        kv_cache_dtype: str,
        logits_soft_cap: float | None = None,
        attn_type: AttentionType = AttentionType.DECODER,
        kv_sharing_target_layer_name: int | None = None,
        sinks: torch.Tensor | None = None,
    ) -> None:
        self.num_heads = num_heads
        self.head_size = head_size
        self.scale = float(scale)
        self.num_kv_heads = num_kv_heads
        if alibi_slopes is not None:
            alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32)
        self.alibi_slopes = alibi_slopes
        if sliding_window is None:
            self.sliding_window = (-1, -1)
        else:
            self.sliding_window = (sliding_window - 1, 0)
        self.kv_cache_dtype = kv_cache_dtype
        if logits_soft_cap is None:
            # In flash-attn, setting logits_soft_cap as 0 means no soft cap.
            logits_soft_cap = 0.0
        self.logits_soft_cap = logits_soft_cap
        self.kv_sharing_target_layer_name = kv_sharing_target_layer_name
        self.sinks = sinks

        assert self.num_heads % self.num_kv_heads == 0
        self.num_queries_per_kv = self.num_heads // self.num_kv_heads

        self._fast_verify = _uses_fast_verify(
            get_current_vllm_config_or_none(), kv_cache_dtype
        ) and rocm_gqa_verify.supports_layer(
            num_heads,
            num_kv_heads,
            head_size,
            self.alibi_slopes,
            sinks,
            self.logits_soft_cap,
        )

        if attn_type != AttentionType.DECODER:
            raise NotImplementedError(
                "Only decoder self-attention is supported for "
                "AiterFlashAttentionImpl. ENCODER_DECODER is not supported "
                "because the prefill path uses cu_seqlens_k set to decoder "
                "query_start_loc with causal=True, which is incorrect for "
                "cross-attention."
            )

    def _get_kv_cache_descales(
        self,
        layer: AttentionLayer,
        num_decodes: int,
    ) -> tuple[torch.Tensor | None, torch.Tensor | None]:
        # AITER treats non-null descales as an instruction to dequantize.
        if not is_quantized_kv_cache(self.kv_cache_dtype):
            return None, None
        descale_shape = (num_decodes, self.num_kv_heads)
        return (
            layer._k_scale.expand(descale_shape),
            layer._v_scale.expand(descale_shape),
        )

    def extend_for_sliding_window(
        self,
        attn_metadata: AiterFlashAttentionMetadata,
        query: torch.Tensor,
        key_cache,
        value_cache,
        output: torch.Tensor,
        cu_seqlens_q: torch.Tensor,
        max_seqlen_q: int,
        block_table: torch.Tensor,
        k_scale: float,
        v_scale: float,
    ):
        assert attn_metadata.extend_metadata is not None
        assert attn_metadata.extend_metadata.chunk_context_metadata is not None
        chunked_metadata = attn_metadata.extend_metadata.chunk_context_metadata
        swa_metadata = chunked_metadata.swa_metadata
        assert swa_metadata is not None
        swa_cu_seqlens = swa_metadata.swa_cu_seqlens
        swa_seq_starts = swa_metadata.swa_seq_starts
        swa_token_to_batch = swa_metadata.swa_token_to_batch
        swa_max_seqlens = swa_metadata.swa_max_seqlens
        swa_total_tokens = swa_metadata.swa_total_tokens
        key_fetched, value_fetched = (
            swa_metadata.swa_workspace[0],
            swa_metadata.swa_workspace[1],
        )
        cp_mha_gather_cache(
            key_cache=key_cache,
            value_cache=value_cache,
            key=key_fetched,
            value=value_fetched,
            block_tables=block_table,
            k_scales=k_scale,
            v_scales=v_scale,
            cu_seqlens_kv=swa_cu_seqlens,
            token_to_batch=swa_token_to_batch,
            seq_starts=swa_seq_starts,
            dequant=is_quantized_kv_cache(self.kv_cache_dtype),
            kv_cache_layout="NHD",
            total_tokens=swa_total_tokens,
        )

        rocm_aiter_ops.flash_attn_varlen_func(
            q=query,
            k=key_fetched,
            v=value_fetched,
            cu_seqlens_q=cu_seqlens_q,
            cu_seqlens_k=swa_cu_seqlens,
            max_seqlen_q=max_seqlen_q,
            max_seqlen_k=swa_max_seqlens,
            min_seqlen_q=0,
            dropout_p=0.0,
            softmax_scale=self.scale,
            causal=True,
            window_size=self.sliding_window,
            alibi_slopes=self.alibi_slopes,
            return_lse=False,
            out=output,
            sink_ptr=self.sinks,
        )

    def extend_forward(
        self,
        attn_metadata: AiterFlashAttentionMetadata,
        query: torch.Tensor,
        key: torch.Tensor,
        value: torch.Tensor,
        key_cache: torch.Tensor,
        value_cache: torch.Tensor,
        output: torch.Tensor,
        cu_seqlens_q: torch.Tensor,
        max_seqlen_q: int,
        max_seqlen_k: int,
        block_table: torch.Tensor,
        slot_mapping: torch.Tensor,
        k_scale: torch.Tensor,
        v_scale: torch.Tensor,
    ):
        if self.sliding_window[0] != -1:
            self.extend_for_sliding_window(
                attn_metadata,
                query,
                key_cache,
                value_cache,
                output,
                cu_seqlens_q,
                max_seqlen_q,
                block_table,
                k_scale,
                v_scale,
            )
            return
        out, lse = rocm_aiter_ops.flash_attn_varlen_func(
            q=query,
            k=key,
            v=value,
            cu_seqlens_q=cu_seqlens_q,
            cu_seqlens_k=cu_seqlens_q,
            max_seqlen_q=max_seqlen_q,
            max_seqlen_k=max_seqlen_q,
            min_seqlen_q=0,
            dropout_p=0.0,
            softmax_scale=self.scale,
            causal=True,
            window_size=self.sliding_window,
            alibi_slopes=self.alibi_slopes,
            return_lse=True,
            sink_ptr=self.sinks,
        )
        assert attn_metadata.extend_metadata is not None
        chunk_context_metadata = attn_metadata.extend_metadata.chunk_context_metadata
        num_chunks = chunk_context_metadata.num_chunks
        workspace = chunk_context_metadata.workspace
        cu_seqlens_kv = chunk_context_metadata.cu_seq_lens_chunk
        max_seqlens = chunk_context_metadata.max_seq_lens
        chunk_starts = chunk_context_metadata.chunk_starts
        token_to_batch = chunk_context_metadata.token_to_batch
        total_token_per_batch = chunk_context_metadata.total_token_per_batch
        key_fetched, value_fetched = workspace[0], workspace[1]
        chunked_output = None
        chunked_lse = None
        for chunk_idx in range(num_chunks):
            cp_mha_gather_cache(
                key_cache=key_cache,
                value_cache=value_cache,
                key=key_fetched,
                value=value_fetched,
                block_tables=block_table,
                k_scales=k_scale,
                v_scales=v_scale,
                cu_seqlens_kv=cu_seqlens_kv[chunk_idx],
                token_to_batch=token_to_batch[chunk_idx],
                seq_starts=chunk_starts[chunk_idx],
                dequant=is_quantized_kv_cache(self.kv_cache_dtype),
                kv_cache_layout="SHUFFLE"
                if rocm_aiter_ops.is_shuffle_kv_cache_enabled()
                else "NHD",
                total_tokens=total_token_per_batch[chunk_idx],
            )

            suf_out, suf_lse = rocm_aiter_ops.flash_attn_varlen_func(
                q=query,
                k=key_fetched,
                v=value_fetched,
                cu_seqlens_q=cu_seqlens_q,
                cu_seqlens_k=cu_seqlens_kv[chunk_idx],
                max_seqlen_q=max_seqlen_q,
                max_seqlen_k=max_seqlens[chunk_idx],
                min_seqlen_q=0,
                dropout_p=0.0,
                softmax_scale=self.scale,
                causal=False,
                window_size=self.sliding_window,
                alibi_slopes=self.alibi_slopes,
                return_lse=True,
                # The causal call above already adds the sink to each query's
                # LSE; adding it per context chunk would overcount it on merge.
                sink_ptr=None,
            )
            if chunked_output is None:
                chunked_output = suf_out
                chunked_lse = suf_lse
            else:
                tmp_output = torch.empty_like(out)
                tmp_lse = torch.empty_like(lse)
                merge_attn_states(
                    output=tmp_output,
                    output_lse=tmp_lse,
                    prefix_output=chunked_output,
                    prefix_lse=chunked_lse,
                    suffix_output=suf_out,
                    suffix_lse=suf_lse,
                )
                chunked_output = tmp_output
                chunked_lse = tmp_lse

        merge_attn_states(
            output=output,
            prefix_output=chunked_output,
            prefix_lse=chunked_lse,
            suffix_output=out,
            suffix_lse=lse,
        )

    def forward(
        self,
        layer: torch.nn.Module,
        query: torch.Tensor,
        key: torch.Tensor | None,
        value: torch.Tensor | None,
        kv_cache: torch.Tensor,
        attn_metadata: AiterFlashAttentionMetadata,
        output: torch.Tensor,
        output_scale: torch.Tensor | None = None,
        output_block_scale: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """Forward pass with AiterFlashAttention.

        Args:
            layer: The attention layer, providing the q/k/v quantization scales.
            query: shape = [num_tokens, num_heads, head_size]
            key: shape = [num_tokens, num_kv_heads, head_size]
            value: shape = [num_tokens, num_kv_heads, head_size]
            kv_cache: shape =
                [num_blocks, 2, block_size, num_kv_heads, head_size]
            attn_metadata: Metadata for attention.
            output: Tensor that the attention result is written into.
            output_scale: Scale for fused output quantization; not supported
                by this backend.
            output_block_scale: Block scale for fused output quantization;
                not supported by this backend.

        Returns:
            shape = [num_tokens, num_heads * head_size]
        NOTE: FP8 quantization, flash-attn expect the size of
              {q,k,v}_descale to be (num_sequences, num_kv_heads).
              We use torch's .expand() to avoid duplicating values

        """
        if output_scale is not None or output_block_scale is not None:
            raise NotImplementedError(
                "fused output quantization is not yet supported "
                "for AiterFlashAttentionImpl"
            )

        if attn_metadata is None:
            # Profiling run.
            return output.fill_(0)

        # IMPORTANT!
        # NOTE(woosuk): With piece-wise CUDA graphs, this method is
        # executed in eager-mode PyTorch. Thus, we need to be careful
        # about any CPU overhead in this method. For example, `view`
        # and `slice` (or `[:n]`) operations are surprisingly slow even
        # in the case they do not invoke any GPU ops.
        # Minimize the PyTorch ops in this method as much as possible.
        # Whenever making a change in this method, please benchmark the
        # performance to make sure it does not introduce any overhead.
        num_actual_tokens = attn_metadata.num_actual_tokens

        key_cache, value_cache = self._split_kv_cache(kv_cache, use_typed=True)

        # decode:extend:prefill
        query = query[:num_actual_tokens]
        if key is not None:
            key = key[:num_actual_tokens]
        if value is not None:
            value = value[:num_actual_tokens]

        output_actual_tokens = output[:num_actual_tokens]

        num_decodes = attn_metadata.num_decodes
        num_prefills = attn_metadata.num_prefills
        num_extends = attn_metadata.num_extends

        num_decode_tokens = attn_metadata.num_decode_tokens
        num_extend_tokens = attn_metadata.num_extend_tokens
        if (self.kv_sharing_target_layer_name is not None or key is None) and (
            num_prefills > 0 or num_extends > 0
        ):
            # Shared layers project only Q. Fetch the new K/V tokens from the
            # target cache for the direct prefill and extend suffix kernels.
            shared = attn_metadata.kv_sharing_metadata
            assert shared is not None
            key, value = shared.workspace[:, :num_actual_tokens].unbind(0)
            cp_mha_gather_cache(
                key_cache=key_cache,
                value_cache=value_cache,
                key=key[num_decode_tokens:],
                value=value[num_decode_tokens:],
                block_tables=attn_metadata.block_table[num_decodes:],
                k_scales=layer._k_scale,
                v_scales=layer._v_scale,
                cu_seqlens_kv=shared.query_start_loc,
                token_to_batch=shared.token_to_batch,
                seq_starts=shared.seq_starts,
                dequant=is_quantized_kv_cache(self.kv_cache_dtype),
                kv_cache_layout="SHUFFLE"
                if rocm_aiter_ops.is_shuffle_kv_cache_enabled()
                else "NHD",
                total_tokens=num_actual_tokens - num_decode_tokens,
            )
        # calculate for pure prefills
        if num_prefills > 0:
            assert attn_metadata.prefill_metadata is not None
            assert key is not None and value is not None

            prefill_query = query[num_decode_tokens + num_extend_tokens :]
            prefill_key = key[num_decode_tokens + num_extend_tokens :]
            prefill_value = value[num_decode_tokens + num_extend_tokens :]

            rocm_aiter_ops.flash_attn_varlen_func(
                q=prefill_query,
                k=prefill_key,
                v=prefill_value,
                cu_seqlens_q=attn_metadata.prefill_metadata.query_start_loc,
                cu_seqlens_k=attn_metadata.prefill_metadata.query_start_loc,
                max_seqlen_q=attn_metadata.prefill_metadata.max_query_len,
                max_seqlen_k=attn_metadata.prefill_metadata.max_seq_len,
                min_seqlen_q=0,
                dropout_p=0.0,
                softmax_scale=self.scale,
                causal=attn_metadata.causal,
                window_size=self.sliding_window,
                alibi_slopes=self.alibi_slopes,
                out=output_actual_tokens[num_decode_tokens + num_extend_tokens :],
                sink_ptr=self.sinks,
            )

        # calculate for extends
        if num_extends > 0:
            assert attn_metadata.extend_metadata is not None
            assert key is not None and value is not None
            extend_tokens_slice = slice(
                num_decode_tokens, num_decode_tokens + num_extend_tokens
            )
            extend_queries = query[extend_tokens_slice]
            extend_keys = key[extend_tokens_slice]
            extend_values = value[extend_tokens_slice]
            extend_outputs = output[extend_tokens_slice]
            k_scale = layer._k_scale
            v_scale = layer._v_scale
            self.extend_forward(
                attn_metadata=attn_metadata,
                query=extend_queries,
                key=extend_keys,
                value=extend_values,
                key_cache=key_cache,
                value_cache=value_cache,
                output=extend_outputs,
                cu_seqlens_q=attn_metadata.extend_metadata.query_start_loc,
                max_seqlen_q=attn_metadata.extend_metadata.max_query_len,
                max_seqlen_k=attn_metadata.extend_metadata.max_seq_len,
                block_table=attn_metadata.block_table[
                    num_decodes : num_decodes + num_extends
                ],
                slot_mapping=attn_metadata.slot_mapping[
                    num_decodes : num_decodes + num_extends
                ],
                k_scale=k_scale,
                v_scale=v_scale,
            )

        # calculate for decodes
        if num_decodes > 0:
            assert attn_metadata.decode_metadata is not None
            decode_max_query_len = attn_metadata.decode_metadata.max_query_len

            if (
                self._fast_verify
                and attn_metadata.causal
                and rocm_gqa_verify.fast_verify(
                    query,
                    key_cache,
                    value_cache,
                    output,
                    attn_metadata,
                    num_decodes,
                    num_decode_tokens,
                    decode_max_query_len,
                    self.scale,
                    self.sliding_window[0] + 1,
                    layer,
                    attn_metadata.decode_metadata.verify_map,
                )
            ):
                return output

            # Use unified_attention for the decodes the paged kernels can't
            # take: sliding window, sinks, or a multi-token batch
            # (pa_fwd_asm and paged_attention_v1 don't support sinks).
            # Single-token SWA decode on the trimmed block table is ~2x
            # faster on the paged kernel than unified_attention.
            decode_md = attn_metadata.decode_metadata
            use_swa_paged = (
                self.sliding_window[0] != -1
                and decode_max_query_len == 1
                and self.sinks is None
                and self.alibi_slopes is None
                and decode_md.swa_block_table is not None
                and self.head_size >= 64
                and not rocm_aiter_ops.is_shuffle_kv_cache_enabled()
            )
            if (
                (self.sliding_window[0] != -1 and not use_swa_paged)
                or decode_max_query_len > 1
                or self.sinks is not None
            ):
                k_descale, v_descale = self._get_kv_cache_descales(layer, num_decodes)
                assert not rocm_aiter_ops.is_shuffle_kv_cache_enabled(), (
                    "Shuffle KV cache layout is not supported with sliding "
                    "window, sinks, or speculative decoding (multi-token decode)."
                )
                if not attn_metadata.causal:
                    from aiter.ops.triton.attention.mha_v3 import (
                        flash_attn_with_kvcache,
                    )

                    decode_query = query[:num_decode_tokens].reshape(
                        num_decodes,
                        decode_max_query_len,
                        query.shape[1],
                        query.shape[2],
                    )
                    decode_out = flash_attn_with_kvcache(
                        q=decode_query,
                        k_cache=key_cache,
                        v_cache=value_cache,
                        cache_seqlens=attn_metadata.seq_lens[:num_decodes],
                        softmax_scale=self.scale,
                        causal=attn_metadata.causal,
                        window_size=self.sliding_window,
                        softcap=self.logits_soft_cap,
                        q_descale=None,
                        k_descale=k_descale,
                        v_descale=v_descale,
                        page_table=attn_metadata.block_table[:num_decodes],
                    )
                    output[:num_decode_tokens].copy_(
                        decode_out.reshape(
                            num_decode_tokens,
                            query.shape[1],
                            query.shape[2],
                        )
                    )
                else:
                    # Non-uniform query lengths can appear in real serving
                    # traffic (e.g. mixed datasets). Fall back to varlen
                    # unified_attention instead of asserting.
                    from aiter.ops.triton.unified_attention import (
                        unified_attention,
                    )

                    unified_attention(
                        q=query[:num_decode_tokens],
                        k=key_cache,
                        v=value_cache,
                        out=output[:num_decode_tokens],
                        cu_seqlens_q=attn_metadata.query_start_loc[: num_decodes + 1],
                        max_seqlen_q=decode_max_query_len,
                        seqused_k=attn_metadata.seq_lens[:num_decodes],
                        max_seqlen_k=attn_metadata.max_seq_len,
                        softmax_scale=self.scale,
                        causal=True,
                        alibi_slopes=self.alibi_slopes,
                        window_size=self.sliding_window,
                        block_table=attn_metadata.block_table[:num_decodes],
                        softcap=self.logits_soft_cap,
                        q_descale=None,
                        k_descale=k_descale,
                        v_descale=v_descale,
                        sinks=self.sinks,
                    )
                return

            # The ll4mi kernel in paged_attention_v1 requires
            # HEAD_SIZE >= 16 * NWARPS (= 64 on ROCm with NWARPS=4).
            # For smaller head sizes or sliding window attention,
            # fall back to the unified_attention triton kernel which
            # handles both correctly.
            _MIN_HEAD_SIZE_FOR_LL4MI = 64
            use_unified_attention = self.head_size < _MIN_HEAD_SIZE_FOR_LL4MI

            if use_unified_attention:
                k_descale, v_descale = self._get_kv_cache_descales(layer, num_decodes)
                assert not rocm_aiter_ops.is_shuffle_kv_cache_enabled(), (
                    "unified_attention fallback with shuffle layout "
                    "is not supported yet."
                )
                from aiter.ops.triton.unified_attention import (
                    unified_attention,
                )

                decode_cu_seqlens_q = attn_metadata.query_start_loc[: num_decodes + 1]
                unified_attention(
                    q=query[:num_decode_tokens],
                    k=key_cache,
                    v=value_cache,
                    out=output[:num_decode_tokens],
                    cu_seqlens_q=decode_cu_seqlens_q,
                    max_seqlen_q=1,
                    seqused_k=attn_metadata.seq_lens[:num_decodes],
                    max_seqlen_k=attn_metadata.max_seq_len,
                    softmax_scale=self.scale,
                    causal=True,
                    alibi_slopes=self.alibi_slopes,
                    window_size=self.sliding_window,
                    block_table=attn_metadata.block_table[:num_decodes],
                    softcap=self.logits_soft_cap,
                    q_descale=None,
                    k_descale=k_descale,
                    v_descale=v_descale,
                )
            elif rocm_aiter_ops.is_shuffle_kv_cache_enabled():
                _, num_heads, head_size = query.shape
                num_blocks, block_size, num_kv_heads, _ = key_cache.shape
                x = 16 // key_cache.element_size()
                new_key_cache = key_cache.reshape(
                    num_blocks, num_kv_heads, head_size // x, block_size, x
                )
                new_value_cache = value_cache.reshape(
                    num_blocks, num_kv_heads, block_size // x, head_size, x
                )

                # This kernel derives block addresses arithmetically, so it
                # only reads the right bytes when each side is a dense
                # plane of pages.
                assert new_key_cache.stride(0) == (
                    num_kv_heads * head_size * block_size
                ), (
                    "paged_attention_common needs the K/V sides as dense "
                    "planes; the resolved KV cache layout interleaves them "
                    "within a block."
                )
                num_seqs = attn_metadata.seq_lens.shape[0]
                max_num_partitions = (
                    attn_metadata.max_seq_len + _PARTITION_SIZE_ROCM - 1
                ) // _PARTITION_SIZE_ROCM
                tmp_out = torch.empty(
                    (num_seqs, num_heads, max_num_partitions, head_size),
                    dtype=query.dtype,
                    device=query.device,
                )
                exp_sums = torch.empty(
                    (num_seqs, num_heads, max_num_partitions),
                    dtype=torch.float32,
                    device=query.device,
                )
                max_logits = torch.empty_like(exp_sums)
                # asm indexes this layer's dense scale buffer from build();
                # the HIP kernel reads the per-tensor scale directly.
                k_qscale_asm = v_qscale_asm = None
                if attn_metadata.k_scale is not None:
                    assert attn_metadata.v_scale is not None
                    k_qscale_asm = attn_metadata.k_scale[layer.layer_name]
                    v_qscale_asm = attn_metadata.v_scale[layer.layer_name]
                rocm_aiter_ops.paged_attention_common(
                    Q=query[:num_decode_tokens],
                    K=new_key_cache,
                    V=new_value_cache,
                    tmp_out=tmp_out,
                    max_logits=max_logits,
                    exp_sums=exp_sums,
                    max_seq_len=attn_metadata.max_seq_len,
                    block_tables=attn_metadata.block_table[:num_decodes],
                    context_lens=attn_metadata.seq_lens[:num_decodes],
                    block_tables_stride0=attn_metadata.block_table[:num_decodes].stride(
                        0
                    ),
                    scale=self.scale,
                    K_QScale_hip=layer._k_scale,
                    V_QScale_hip=layer._v_scale,
                    K_QScale_asm=k_qscale_asm,
                    V_QScale_asm=v_qscale_asm,
                    out_=output[:num_decode_tokens],
                    kv_cache_dtype=self.kv_cache_dtype,
                )
            else:
                _, num_heads, head_size = query.shape
                nbytes_per_qo_elem = torch.finfo(query.dtype).bits // 8
                num_seqs = attn_metadata.seq_lens.shape[0]
                if use_swa_paged:
                    decode_block_table = decode_md.swa_block_table
                    decode_seq_lens = decode_md.swa_seq_lens
                    decode_max_seq_len = decode_md.swa_max_seq_len
                else:
                    decode_block_table = attn_metadata.block_table[:num_decodes]
                    decode_seq_lens = attn_metadata.seq_lens[:num_decodes]
                    decode_max_seq_len = attn_metadata.max_seq_len
                max_num_partitions = (
                    decode_max_seq_len + _PARTITION_SIZE_ROCM - 1
                ) // _PARTITION_SIZE_ROCM

                workspace_buffer = torch.empty(
                    (num_seqs * num_heads * max_num_partitions * head_size)
                    * nbytes_per_qo_elem
                    + 2 * (num_seqs * num_heads * max_num_partitions) * 4,
                    dtype=torch.uint8,
                    device=output.device,
                )

                # import so that aiter register the op to the namespace of
                # torch.ops.aiter
                import aiter  # noqa: F401

                torch.ops.aiter.paged_attention_v1(
                    output[:num_decode_tokens],
                    workspace_buffer,
                    query[:num_decode_tokens],
                    key_cache,
                    value_cache,
                    self.scale,
                    decode_block_table,
                    attn_metadata.query_start_loc[:num_decodes],
                    decode_seq_lens,
                    decode_max_seq_len,
                    self.alibi_slopes,
                    self.kv_cache_dtype,
                    "NHD",
                    self.logits_soft_cap,
                    layer._k_scale,
                    layer._v_scale,
                    None,
                    _PARTITION_SIZE_ROCM,
                    1,
                    self.sliding_window[0] + 1,
                )

        return output

    def _split_kv_cache(
        self, kv_cache: torch.Tensor, use_typed: bool = False
    ) -> tuple[torch.Tensor, torch.Tensor]:
        cache = self._kv_view_cache
        if (
            cache is not None
            and cache[0] is kv_cache
            and cache[1] == kv_cache.data_ptr()
        ):
            return cache[3] if use_typed else cache[2]
        if rocm_aiter_ops.is_shuffle_kv_cache_enabled():
            # (B, 2, N, H*hs) -> one (B, N, H, hs) per side, which is what the
            # shuffle read/write kernels reinterpret in place. The heads are
            # folded into the content dim by customize_spec.
            key_cache, value_cache = kv_cache.unflatten(
                -1, (self.num_kv_heads, self.head_size)
            ).unbind(1)
        else:
            # (B, H, N, 2*hs) -> ((B, N, H, hs), (B, N, H, hs))
            key_cache, value_cache = kv_cache.transpose(1, 2).split(
                self.head_size, dim=-1
            )
        raw = (key_cache, value_cache)
        typed = raw
        if is_quantized_kv_cache(self.kv_cache_dtype):
            fp8_dtype = current_platform.fp8_dtype()
            typed = (key_cache.view(fp8_dtype), value_cache.view(fp8_dtype))
        self._kv_view_cache = (kv_cache, kv_cache.data_ptr(), raw, typed)
        return typed if use_typed else raw

    def do_kv_cache_update(
        self,
        layer: AttentionLayer,
        key: torch.Tensor,
        value: torch.Tensor,
        kv_cache: torch.Tensor,
        slot_mapping: torch.Tensor,
    ):
        key_cache, value_cache = self._split_kv_cache(kv_cache, use_typed=True)

        # key and value may be None in the case of cross attention. They are
        # calculated once based on the output from the encoder and then cached
        # in KV cache.
        # Reshape the input keys and values and store them in the cache.
        # Skip this if sharing KV cache with an earlier attention layer.
        # NOTE(woosuk): Here, key and value are padded while slot_mapping
        # is not padded. However, we don't need to do
        # key[:num_actual_tokens] and value[:num_actual_tokens] because
        # the reshape_and_cache_flash op uses the slot_mapping's shape
        # to determine the number of actual tokens.
        if rocm_aiter_ops.is_shuffle_kv_cache_enabled():
            k_scale = layer._k_scale
            v_scale = layer._v_scale
            assert k_scale is not None and v_scale is not None, (
                "k_scale and v_scale are required for shuffled update"
            )
            reshape_and_cache_shuffle_triton(
                key,
                value,
                key_cache,
                value_cache,
                slot_mapping,
                self.kv_cache_dtype,
                k_scale,
                v_scale,
            )
        else:
            torch.ops._C_cache_ops.reshape_and_cache_flash(
                key,
                value,
                key_cache,
                value_cache,
                slot_mapping,
                self.kv_cache_dtype,
                layer._k_scale,
                layer._v_scale,
            )

    def fused_rope_kvcache_supported(self):
        # Only support fusion when shuffle KV cache layout is not used;
        # shuffle layout uses a different cache update path.
        return (
            rocm_aiter_ops.is_enabled()
            and not rocm_aiter_ops.is_shuffle_kv_cache_enabled()
        )

    def fused_qk_norm_rope_kvcache_supported(self):
        return rocm_aiter_ops.is_enabled()

    def do_qk_norm_rope_kvcache_update(
        self,
        layer: AttentionLayer,
        qkv: torch.Tensor,
        q_out: torch.Tensor,
        k_out: torch.Tensor,
        positions: torch.Tensor,
        q_weight: torch.Tensor,
        k_weight: torch.Tensor,
        rms_norm_eps: float,
        cos_sin_cache: torch.Tensor,
        is_neox: bool,
        kv_cache: torch.Tensor,
        layer_slot_mapping: torch.Tensor,
        q_out_fp8: torch.Tensor | None = None,
        q_scale: torch.Tensor | None = None,
    ):
        key_cache, value_cache = self._split_kv_cache(kv_cache)
        rocm_aiter_ops.do_qk_norm_rope_kvcache_update(
            qkv=qkv,
            q_weight=q_weight,
            k_weight=k_weight,
            cos_sin_cache=cos_sin_cache,
            positions=positions,
            num_heads_q=self.num_heads,
            num_heads_k=self.num_kv_heads,
            head_dim=self.head_size,
            is_neox=is_neox,
            rms_norm_eps=rms_norm_eps,
            q_out=q_out,
            k_out=k_out,
            key_cache=key_cache,
            value_cache=value_cache,
            slot_mapping=layer_slot_mapping,
            k_scale=layer._k_scale_cpu,
            v_scale=layer._v_scale_cpu,
            kv_cache_dtype=self.kv_cache_dtype,
            use_shuffle_layout=rocm_aiter_ops.is_shuffle_kv_cache_enabled(),
            return_kv=True,
            q_out_fp8=q_out_fp8,
            q_scale=q_scale,
        )

    def do_rope_and_kv_cache_update(
        self,
        layer: AttentionLayer,
        query: torch.Tensor,
        key: torch.Tensor,
        value: torch.Tensor,
        positions: torch.Tensor,
        cos_sin_cache: torch.Tensor,
        is_neox: bool,
        kv_cache: torch.Tensor,
        layer_slot_mapping: torch.Tensor,
        query_out: torch.Tensor | None = None,
        key_out: torch.Tensor | None = None,
    ):
        # (B, H, N, 2*hs) -> ((B, N, H, hs), (B, N, H, hs))
        key_cache, value_cache = self._split_kv_cache(kv_cache, use_typed=True)
        flash_layout = True

        is_fp8_kv_cache = is_quantized_kv_cache(self.kv_cache_dtype)

        rocm_aiter_ops.triton_rope_and_cache(
            query,
            key,
            value,
            positions,
            cos_sin_cache,
            is_neox,
            key_cache,
            value_cache,
            layer_slot_mapping,
            layer._k_scale,
            layer._v_scale,
            flash_layout,
            is_fp8_kv_cache,
            query_out=query_out,
            key_out=key_out,
        )

forward(layer, query, key, value, kv_cache, attn_metadata, output, output_scale=None, output_block_scale=None)

Forward pass with AiterFlashAttention.

Parameters:

  • layer

    (Module) –

    The attention layer, providing the q/k/v quantization scales.

  • query

    (Tensor) –

    shape = [num_tokens, num_heads, head_size]

  • key

    (Tensor | None) –

    shape = [num_tokens, num_kv_heads, head_size]

  • value

    (Tensor | None) –

    shape = [num_tokens, num_kv_heads, head_size]

  • kv_cache

    (Tensor) –

    shape = [num_blocks, 2, block_size, num_kv_heads, head_size]

  • attn_metadata

    (AiterFlashAttentionMetadata) –

    Metadata for attention.

  • output

    (Tensor) –

    Tensor that the attention result is written into.

  • output_scale

    (Tensor | None, default: None ) –

    Scale for fused output quantization; not supported by this backend.

  • output_block_scale

    (Tensor | None, default: None ) –

    Block scale for fused output quantization; not supported by this backend.

Returns:

  • Tensor –

    shape = [num_tokens, num_heads * head_size]

NOTE: FP8 quantization, flash-attn expect the size of {q,k,v}_descale to be (num_sequences, num_kv_heads). We use torch's .expand() to avoid duplicating values

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
def forward(
    self,
    layer: torch.nn.Module,
    query: torch.Tensor,
    key: torch.Tensor | None,
    value: torch.Tensor | None,
    kv_cache: torch.Tensor,
    attn_metadata: AiterFlashAttentionMetadata,
    output: torch.Tensor,
    output_scale: torch.Tensor | None = None,
    output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
    """Forward pass with AiterFlashAttention.

    Args:
        layer: The attention layer, providing the q/k/v quantization scales.
        query: shape = [num_tokens, num_heads, head_size]
        key: shape = [num_tokens, num_kv_heads, head_size]
        value: shape = [num_tokens, num_kv_heads, head_size]
        kv_cache: shape =
            [num_blocks, 2, block_size, num_kv_heads, head_size]
        attn_metadata: Metadata for attention.
        output: Tensor that the attention result is written into.
        output_scale: Scale for fused output quantization; not supported
            by this backend.
        output_block_scale: Block scale for fused output quantization;
            not supported by this backend.

    Returns:
        shape = [num_tokens, num_heads * head_size]
    NOTE: FP8 quantization, flash-attn expect the size of
          {q,k,v}_descale to be (num_sequences, num_kv_heads).
          We use torch's .expand() to avoid duplicating values

    """
    if output_scale is not None or output_block_scale is not None:
        raise NotImplementedError(
            "fused output quantization is not yet supported "
            "for AiterFlashAttentionImpl"
        )

    if attn_metadata is None:
        # Profiling run.
        return output.fill_(0)

    # IMPORTANT!
    # NOTE(woosuk): With piece-wise CUDA graphs, this method is
    # executed in eager-mode PyTorch. Thus, we need to be careful
    # about any CPU overhead in this method. For example, `view`
    # and `slice` (or `[:n]`) operations are surprisingly slow even
    # in the case they do not invoke any GPU ops.
    # Minimize the PyTorch ops in this method as much as possible.
    # Whenever making a change in this method, please benchmark the
    # performance to make sure it does not introduce any overhead.
    num_actual_tokens = attn_metadata.num_actual_tokens

    key_cache, value_cache = self._split_kv_cache(kv_cache, use_typed=True)

    # decode:extend:prefill
    query = query[:num_actual_tokens]
    if key is not None:
        key = key[:num_actual_tokens]
    if value is not None:
        value = value[:num_actual_tokens]

    output_actual_tokens = output[:num_actual_tokens]

    num_decodes = attn_metadata.num_decodes
    num_prefills = attn_metadata.num_prefills
    num_extends = attn_metadata.num_extends

    num_decode_tokens = attn_metadata.num_decode_tokens
    num_extend_tokens = attn_metadata.num_extend_tokens
    if (self.kv_sharing_target_layer_name is not None or key is None) and (
        num_prefills > 0 or num_extends > 0
    ):
        # Shared layers project only Q. Fetch the new K/V tokens from the
        # target cache for the direct prefill and extend suffix kernels.
        shared = attn_metadata.kv_sharing_metadata
        assert shared is not None
        key, value = shared.workspace[:, :num_actual_tokens].unbind(0)
        cp_mha_gather_cache(
            key_cache=key_cache,
            value_cache=value_cache,
            key=key[num_decode_tokens:],
            value=value[num_decode_tokens:],
            block_tables=attn_metadata.block_table[num_decodes:],
            k_scales=layer._k_scale,
            v_scales=layer._v_scale,
            cu_seqlens_kv=shared.query_start_loc,
            token_to_batch=shared.token_to_batch,
            seq_starts=shared.seq_starts,
            dequant=is_quantized_kv_cache(self.kv_cache_dtype),
            kv_cache_layout="SHUFFLE"
            if rocm_aiter_ops.is_shuffle_kv_cache_enabled()
            else "NHD",
            total_tokens=num_actual_tokens - num_decode_tokens,
        )
    # calculate for pure prefills
    if num_prefills > 0:
        assert attn_metadata.prefill_metadata is not None
        assert key is not None and value is not None

        prefill_query = query[num_decode_tokens + num_extend_tokens :]
        prefill_key = key[num_decode_tokens + num_extend_tokens :]
        prefill_value = value[num_decode_tokens + num_extend_tokens :]

        rocm_aiter_ops.flash_attn_varlen_func(
            q=prefill_query,
            k=prefill_key,
            v=prefill_value,
            cu_seqlens_q=attn_metadata.prefill_metadata.query_start_loc,
            cu_seqlens_k=attn_metadata.prefill_metadata.query_start_loc,
            max_seqlen_q=attn_metadata.prefill_metadata.max_query_len,
            max_seqlen_k=attn_metadata.prefill_metadata.max_seq_len,
            min_seqlen_q=0,
            dropout_p=0.0,
            softmax_scale=self.scale,
            causal=attn_metadata.causal,
            window_size=self.sliding_window,
            alibi_slopes=self.alibi_slopes,
            out=output_actual_tokens[num_decode_tokens + num_extend_tokens :],
            sink_ptr=self.sinks,
        )

    # calculate for extends
    if num_extends > 0:
        assert attn_metadata.extend_metadata is not None
        assert key is not None and value is not None
        extend_tokens_slice = slice(
            num_decode_tokens, num_decode_tokens + num_extend_tokens
        )
        extend_queries = query[extend_tokens_slice]
        extend_keys = key[extend_tokens_slice]
        extend_values = value[extend_tokens_slice]
        extend_outputs = output[extend_tokens_slice]
        k_scale = layer._k_scale
        v_scale = layer._v_scale
        self.extend_forward(
            attn_metadata=attn_metadata,
            query=extend_queries,
            key=extend_keys,
            value=extend_values,
            key_cache=key_cache,
            value_cache=value_cache,
            output=extend_outputs,
            cu_seqlens_q=attn_metadata.extend_metadata.query_start_loc,
            max_seqlen_q=attn_metadata.extend_metadata.max_query_len,
            max_seqlen_k=attn_metadata.extend_metadata.max_seq_len,
            block_table=attn_metadata.block_table[
                num_decodes : num_decodes + num_extends
            ],
            slot_mapping=attn_metadata.slot_mapping[
                num_decodes : num_decodes + num_extends
            ],
            k_scale=k_scale,
            v_scale=v_scale,
        )

    # calculate for decodes
    if num_decodes > 0:
        assert attn_metadata.decode_metadata is not None
        decode_max_query_len = attn_metadata.decode_metadata.max_query_len

        if (
            self._fast_verify
            and attn_metadata.causal
            and rocm_gqa_verify.fast_verify(
                query,
                key_cache,
                value_cache,
                output,
                attn_metadata,
                num_decodes,
                num_decode_tokens,
                decode_max_query_len,
                self.scale,
                self.sliding_window[0] + 1,
                layer,
                attn_metadata.decode_metadata.verify_map,
            )
        ):
            return output

        # Use unified_attention for the decodes the paged kernels can't
        # take: sliding window, sinks, or a multi-token batch
        # (pa_fwd_asm and paged_attention_v1 don't support sinks).
        # Single-token SWA decode on the trimmed block table is ~2x
        # faster on the paged kernel than unified_attention.
        decode_md = attn_metadata.decode_metadata
        use_swa_paged = (
            self.sliding_window[0] != -1
            and decode_max_query_len == 1
            and self.sinks is None
            and self.alibi_slopes is None
            and decode_md.swa_block_table is not None
            and self.head_size >= 64
            and not rocm_aiter_ops.is_shuffle_kv_cache_enabled()
        )
        if (
            (self.sliding_window[0] != -1 and not use_swa_paged)
            or decode_max_query_len > 1
            or self.sinks is not None
        ):
            k_descale, v_descale = self._get_kv_cache_descales(layer, num_decodes)
            assert not rocm_aiter_ops.is_shuffle_kv_cache_enabled(), (
                "Shuffle KV cache layout is not supported with sliding "
                "window, sinks, or speculative decoding (multi-token decode)."
            )
            if not attn_metadata.causal:
                from aiter.ops.triton.attention.mha_v3 import (
                    flash_attn_with_kvcache,
                )

                decode_query = query[:num_decode_tokens].reshape(
                    num_decodes,
                    decode_max_query_len,
                    query.shape[1],
                    query.shape[2],
                )
                decode_out = flash_attn_with_kvcache(
                    q=decode_query,
                    k_cache=key_cache,
                    v_cache=value_cache,
                    cache_seqlens=attn_metadata.seq_lens[:num_decodes],
                    softmax_scale=self.scale,
                    causal=attn_metadata.causal,
                    window_size=self.sliding_window,
                    softcap=self.logits_soft_cap,
                    q_descale=None,
                    k_descale=k_descale,
                    v_descale=v_descale,
                    page_table=attn_metadata.block_table[:num_decodes],
                )
                output[:num_decode_tokens].copy_(
                    decode_out.reshape(
                        num_decode_tokens,
                        query.shape[1],
                        query.shape[2],
                    )
                )
            else:
                # Non-uniform query lengths can appear in real serving
                # traffic (e.g. mixed datasets). Fall back to varlen
                # unified_attention instead of asserting.
                from aiter.ops.triton.unified_attention import (
                    unified_attention,
                )

                unified_attention(
                    q=query[:num_decode_tokens],
                    k=key_cache,
                    v=value_cache,
                    out=output[:num_decode_tokens],
                    cu_seqlens_q=attn_metadata.query_start_loc[: num_decodes + 1],
                    max_seqlen_q=decode_max_query_len,
                    seqused_k=attn_metadata.seq_lens[:num_decodes],
                    max_seqlen_k=attn_metadata.max_seq_len,
                    softmax_scale=self.scale,
                    causal=True,
                    alibi_slopes=self.alibi_slopes,
                    window_size=self.sliding_window,
                    block_table=attn_metadata.block_table[:num_decodes],
                    softcap=self.logits_soft_cap,
                    q_descale=None,
                    k_descale=k_descale,
                    v_descale=v_descale,
                    sinks=self.sinks,
                )
            return

        # The ll4mi kernel in paged_attention_v1 requires
        # HEAD_SIZE >= 16 * NWARPS (= 64 on ROCm with NWARPS=4).
        # For smaller head sizes or sliding window attention,
        # fall back to the unified_attention triton kernel which
        # handles both correctly.
        _MIN_HEAD_SIZE_FOR_LL4MI = 64
        use_unified_attention = self.head_size < _MIN_HEAD_SIZE_FOR_LL4MI

        if use_unified_attention:
            k_descale, v_descale = self._get_kv_cache_descales(layer, num_decodes)
            assert not rocm_aiter_ops.is_shuffle_kv_cache_enabled(), (
                "unified_attention fallback with shuffle layout "
                "is not supported yet."
            )
            from aiter.ops.triton.unified_attention import (
                unified_attention,
            )

            decode_cu_seqlens_q = attn_metadata.query_start_loc[: num_decodes + 1]
            unified_attention(
                q=query[:num_decode_tokens],
                k=key_cache,
                v=value_cache,
                out=output[:num_decode_tokens],
                cu_seqlens_q=decode_cu_seqlens_q,
                max_seqlen_q=1,
                seqused_k=attn_metadata.seq_lens[:num_decodes],
                max_seqlen_k=attn_metadata.max_seq_len,
                softmax_scale=self.scale,
                causal=True,
                alibi_slopes=self.alibi_slopes,
                window_size=self.sliding_window,
                block_table=attn_metadata.block_table[:num_decodes],
                softcap=self.logits_soft_cap,
                q_descale=None,
                k_descale=k_descale,
                v_descale=v_descale,
            )
        elif rocm_aiter_ops.is_shuffle_kv_cache_enabled():
            _, num_heads, head_size = query.shape
            num_blocks, block_size, num_kv_heads, _ = key_cache.shape
            x = 16 // key_cache.element_size()
            new_key_cache = key_cache.reshape(
                num_blocks, num_kv_heads, head_size // x, block_size, x
            )
            new_value_cache = value_cache.reshape(
                num_blocks, num_kv_heads, block_size // x, head_size, x
            )

            # This kernel derives block addresses arithmetically, so it
            # only reads the right bytes when each side is a dense
            # plane of pages.
            assert new_key_cache.stride(0) == (
                num_kv_heads * head_size * block_size
            ), (
                "paged_attention_common needs the K/V sides as dense "
                "planes; the resolved KV cache layout interleaves them "
                "within a block."
            )
            num_seqs = attn_metadata.seq_lens.shape[0]
            max_num_partitions = (
                attn_metadata.max_seq_len + _PARTITION_SIZE_ROCM - 1
            ) // _PARTITION_SIZE_ROCM
            tmp_out = torch.empty(
                (num_seqs, num_heads, max_num_partitions, head_size),
                dtype=query.dtype,
                device=query.device,
            )
            exp_sums = torch.empty(
                (num_seqs, num_heads, max_num_partitions),
                dtype=torch.float32,
                device=query.device,
            )
            max_logits = torch.empty_like(exp_sums)
            # asm indexes this layer's dense scale buffer from build();
            # the HIP kernel reads the per-tensor scale directly.
            k_qscale_asm = v_qscale_asm = None
            if attn_metadata.k_scale is not None:
                assert attn_metadata.v_scale is not None
                k_qscale_asm = attn_metadata.k_scale[layer.layer_name]
                v_qscale_asm = attn_metadata.v_scale[layer.layer_name]
            rocm_aiter_ops.paged_attention_common(
                Q=query[:num_decode_tokens],
                K=new_key_cache,
                V=new_value_cache,
                tmp_out=tmp_out,
                max_logits=max_logits,
                exp_sums=exp_sums,
                max_seq_len=attn_metadata.max_seq_len,
                block_tables=attn_metadata.block_table[:num_decodes],
                context_lens=attn_metadata.seq_lens[:num_decodes],
                block_tables_stride0=attn_metadata.block_table[:num_decodes].stride(
                    0
                ),
                scale=self.scale,
                K_QScale_hip=layer._k_scale,
                V_QScale_hip=layer._v_scale,
                K_QScale_asm=k_qscale_asm,
                V_QScale_asm=v_qscale_asm,
                out_=output[:num_decode_tokens],
                kv_cache_dtype=self.kv_cache_dtype,
            )
        else:
            _, num_heads, head_size = query.shape
            nbytes_per_qo_elem = torch.finfo(query.dtype).bits // 8
            num_seqs = attn_metadata.seq_lens.shape[0]
            if use_swa_paged:
                decode_block_table = decode_md.swa_block_table
                decode_seq_lens = decode_md.swa_seq_lens
                decode_max_seq_len = decode_md.swa_max_seq_len
            else:
                decode_block_table = attn_metadata.block_table[:num_decodes]
                decode_seq_lens = attn_metadata.seq_lens[:num_decodes]
                decode_max_seq_len = attn_metadata.max_seq_len
            max_num_partitions = (
                decode_max_seq_len + _PARTITION_SIZE_ROCM - 1
            ) // _PARTITION_SIZE_ROCM

            workspace_buffer = torch.empty(
                (num_seqs * num_heads * max_num_partitions * head_size)
                * nbytes_per_qo_elem
                + 2 * (num_seqs * num_heads * max_num_partitions) * 4,
                dtype=torch.uint8,
                device=output.device,
            )

            # import so that aiter register the op to the namespace of
            # torch.ops.aiter
            import aiter  # noqa: F401

            torch.ops.aiter.paged_attention_v1(
                output[:num_decode_tokens],
                workspace_buffer,
                query[:num_decode_tokens],
                key_cache,
                value_cache,
                self.scale,
                decode_block_table,
                attn_metadata.query_start_loc[:num_decodes],
                decode_seq_lens,
                decode_max_seq_len,
                self.alibi_slopes,
                self.kv_cache_dtype,
                "NHD",
                self.logits_soft_cap,
                layer._k_scale,
                layer._v_scale,
                None,
                _PARTITION_SIZE_ROCM,
                1,
                self.sliding_window[0] + 1,
            )

    return output

AiterFlashAttentionMetadataBuilder

Bases: AttentionMetadataBuilder[AiterFlashAttentionMetadata]

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
 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
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
class AiterFlashAttentionMetadataBuilder(
    AttentionMetadataBuilder[AiterFlashAttentionMetadata]
):
    _cudagraph_support = AttentionCGSupport.UNIFORM_BATCH

    asm_kv_scale_tables: ClassVar[AsmKvScaleTables] = AsmKvScaleTables()

    def __init__(
        self,
        kv_cache_spec: AttentionSpec,
        layer_names: list[str],
        vllm_config: VllmConfig,
        device: torch.device,
    ):
        super().__init__(kv_cache_spec, layer_names, vllm_config, device)

        self.model_config = vllm_config.model_config
        self.parallel_config = vllm_config.parallel_config
        self.cache_config = vllm_config.cache_config

        self.num_heads_q = self.model_config.get_num_attention_heads(
            self.parallel_config
        )
        self.num_heads_kv = self.model_config.get_num_kv_heads(self.parallel_config)
        self.headdim = self.model_config.get_head_size()
        self.block_size = kv_cache_spec.block_size
        # Sliding window size to be used with the AOT scheduler will be
        # populated on first build() call.
        self.aot_sliding_window: tuple[int, int] | None = None
        self._init_reorder_batch_threshold(1, supports_spec_as_decode=True)

        sliding_window_configs: set[tuple[int, int] | None] = set()
        kv_sharing_shape = None
        self._verify_kv_heads: int | None = None
        swa_tables_needed = False
        layers = get_layers_from_vllm_config(self.vllm_config, Attention)
        for name, layer in layers.items():
            if name not in layer_names:
                continue
            assert isinstance(layer.impl, AiterFlashAttentionImpl), (
                "Aiter Flash Attention Metadata Builder can only be used "
                "with Aiter Flash Attention Impl."
            )
            sliding_window_configs.add(layer.impl.sliding_window)
            if vllm_config.kernel_config.enable_jit_warmup:
                _AITER_FA_EXTEND_KERNEL.register_warmup(
                    dtype=self.model_config.dtype,
                    head_dim=layer.impl.head_size,
                    num_qo_heads=layer.impl.num_heads,
                    num_kv_heads=layer.impl.num_kv_heads,
                    sliding_window=layer.impl.sliding_window,
                    has_alibi=layer.impl.alibi_slopes is not None,
                    has_sinks=layer.impl.sinks is not None,
                )
            if layer.impl._fast_verify and layer.impl.sliding_window[0] == -1:
                self._verify_kv_heads = layer.impl.num_kv_heads
            if layer.impl.sliding_window[0] != -1 and not layer.impl._fast_verify:
                swa_tables_needed = True
            if (
                layer.kv_sharing_target_layer_name is not None
                or layer.kv_cache_update_bypass
            ):
                kv_sharing_shape = (layer.impl.num_kv_heads, layer.impl.head_size)

        while len(sliding_window_configs) > 0:
            sliding_window_config = sliding_window_configs.pop()
            if sliding_window_config is not None and sliding_window_config[0] != -1:
                assert self.aot_sliding_window is None, (
                    "Aiter Flash ATTENTION can only support one valid sliding window!"
                )
                self.aot_sliding_window = sliding_window_config

        # Persistent so full CUDA graphs keep reading the same storage. Layers on
        # the `rocm_gqa_verify` kernels apply the window themselves.
        self._swa_block_table: torch.Tensor | None = None
        self._swa_seq_lens: torch.Tensor | None = None
        self._swa_block_offsets: torch.Tensor | None = None
        if self.aot_sliding_window is not None and swa_tables_needed:
            window = self.aot_sliding_window[0] + 1
            num_window_blocks = cdiv(window, self.block_size) + 1
            max_num_reqs = vllm_config.scheduler_config.max_num_seqs
            self._swa_block_table = torch.zeros(
                (max_num_reqs, num_window_blocks), dtype=torch.int32, device=device
            )
            self._swa_seq_lens = torch.zeros(
                max_num_reqs, dtype=torch.int32, device=device
            )
            self._swa_block_offsets = torch.arange(
                num_window_blocks, dtype=torch.int64, device=device
            )

        self._verify_map_buffers = (
            None
            if self._verify_kv_heads is None
            else rocm_gqa_verify.map_buffers(
                vllm_config.scheduler_config.max_num_seqs, device
            )
        )

        self.extend_workspace = torch.empty(
            [2, _CP_TOKENS_PER_ITER_ROCM, self.num_heads_kv, self.headdim],
            dtype=self.model_config.dtype,
            device=device,
        )
        self.k_scale: dict[str, torch.Tensor] | None = None
        self.v_scale: dict[str, torch.Tensor] | None = None
        self.kv_sharing_workspace: torch.Tensor | None = None
        if kv_sharing_shape is not None:
            self.kv_sharing_workspace = torch.empty(
                (
                    2,
                    vllm_config.scheduler_config.max_num_batched_tokens,
                    *kv_sharing_shape,
                ),
                dtype=self.model_config.dtype,
                device=device,
            )

    def _build_swa_decode_tables(
        self,
        block_table: torch.Tensor,
        seq_lens: torch.Tensor,
        num_decodes: int,
        max_seq_len: int,
    ) -> tuple[torch.Tensor | None, torch.Tensor | None, int]:
        """Trim the decode block table to the sliding window.

        Exact: the kernel's window mask drops the leading tokens of the first
        kept block, and RoPE is already applied in the cache.
        """
        if (
            self._swa_block_table is None
            or self.aot_sliding_window is None
            or num_decodes > self._swa_block_table.shape[0]
        ):
            return None, None, 0
        assert self._swa_seq_lens is not None and self._swa_block_offsets is not None
        window = self.aot_sliding_window[0] + 1
        lens = seq_lens[:num_decodes]
        first_block = (lens - window).clamp_(min=0) // self.block_size
        index = (self._swa_block_offsets + first_block[:, None]).clamp_(
            max=block_table.shape[1] - 1
        )
        swa_block_table = self._swa_block_table[:num_decodes]
        torch.gather(block_table[:num_decodes], 1, index, out=swa_block_table)
        swa_seq_lens = self._swa_seq_lens[:num_decodes]
        torch.sub(lens, first_block, alpha=self.block_size, out=swa_seq_lens)
        return (
            swa_block_table,
            swa_seq_lens,
            min(max_seq_len, window + self.block_size - 1),
        )

    def build_for_cudagraph_capture(
        self, common_attn_metadata: CommonAttentionMetadata
    ):
        return self.build(
            common_prefix_len=0, common_attn_metadata=common_attn_metadata
        )

    def _build_asm_kv_scale_tables(self) -> None:
        # Only for fp8 shuffle kv cache: the asm decode kernel reads a dense
        # [num_blocks, num_kv_heads, block_size] scale table per layer. Map each
        # layer to the shared table for its scale once the KV cache is bound.
        if (
            self.k_scale is not None
            or not rocm_aiter_ops.is_shuffle_kv_cache_enabled()
            or not is_quantized_kv_cache(self.vllm_config.cache_config.cache_dtype)
        ):
            return
        attn_layers = self.vllm_config.compilation_config.static_forward_context
        k_scale_tables: dict[str, torch.Tensor] = {}
        v_scale_tables: dict[str, torch.Tensor] = {}
        for layer_name in self.layer_names:
            layer = attn_layers[layer_name]
            num_blocks = layer.kv_cache.shape[0]
            k_scale_tables[layer_name] = self.asm_kv_scale_tables.get(
                self.device,
                num_blocks,
                self.num_heads_kv,
                self.block_size,
                layer._k_scale_float,
            )
            v_scale_tables[layer_name] = self.asm_kv_scale_tables.get(
                self.device,
                num_blocks,
                self.num_heads_kv,
                self.block_size,
                layer._v_scale_float,
            )
        self.k_scale, self.v_scale = k_scale_tables, v_scale_tables

    def build(
        self,
        common_prefix_len: int,
        common_attn_metadata: CommonAttentionMetadata,
        fast_build: bool = False,
    ) -> "AiterFlashAttentionMetadata":
        assert self.reorder_batch_threshold is not None
        split_ret = split_decodes_prefills_and_extends(
            common_attn_metadata,
            decode_threshold=self.reorder_batch_threshold,
        )
        self._build_asm_kv_scale_tables()
        (
            num_decodes,
            num_extends,
            num_prefills,
            num_decode_tokens,
            num_extend_tokens,
            _,
        ) = split_ret

        query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu

        with gpu_sync_allowed():
            # Only copy seq_lens to CPU when prefill or extend is present to avoid a
            # blocking device→host transfer.
            seq_lens = (
                common_attn_metadata.seq_lens.cpu()
                if num_prefills > 0 or num_extends > 0
                else None
            )

        query_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1]

        kv_sharing_metadata = None
        if self.kv_sharing_workspace is not None and seq_lens is not None:
            query_lens = query_lens_cpu[num_decodes:]
            token_to_batch = torch.repeat_interleave(
                torch.arange(len(query_lens), dtype=torch.int32, device="cpu"),
                query_lens,
            )
            query_start_loc = common_attn_metadata.query_start_loc[num_decodes:]
            kv_sharing_metadata = AiterKVSharingMetadata(
                workspace=self.kv_sharing_workspace,
                query_start_loc=query_start_loc - query_start_loc[0],
                token_to_batch=async_tensor_h2d(token_to_batch, self.device),
                seq_starts=async_tensor_h2d(
                    seq_lens[num_decodes:] - query_lens, self.device
                ),
            )

        decode_metadata = None
        if num_decodes > 0:
            decode_max_query_len = query_lens_cpu[:num_decodes].max().item()
            swa_block_table, swa_seq_lens, swa_max_seq_len = None, None, 0
            if decode_max_query_len == 1:
                swa_block_table, swa_seq_lens, swa_max_seq_len = (
                    self._build_swa_decode_tables(
                        common_attn_metadata.block_table_tensor,
                        common_attn_metadata.seq_lens,
                        num_decodes,
                        common_attn_metadata.max_seq_len,
                    )
                )
            verify_map = None
            if (
                self._verify_map_buffers is not None
                and self._verify_kv_heads is not None
                and rocm_gqa_verify.uniform_query_len(
                    num_decodes, num_decode_tokens, decode_max_query_len
                )
            ):
                verify_map = rocm_gqa_verify.verify_map(
                    common_attn_metadata.seq_lens[:num_decodes],
                    self._verify_kv_heads,
                    self._verify_map_buffers,
                )
            decode_metadata = AiterFlashAttentionDecodeMetadata(
                max_query_len=decode_max_query_len,
                swa_block_table=swa_block_table,
                swa_seq_lens=swa_seq_lens,
                swa_max_seq_len=swa_max_seq_len,
                verify_map=verify_map,
            )

        prefill_metadata = None
        if num_prefills > 0:
            assert seq_lens is not None
            query_lens_for_prefill = query_lens_cpu[num_decodes + num_extends :]
            query_start_loc_device = common_attn_metadata.query_start_loc[
                num_decodes + num_extends :
            ]
            prefill_metadata = AiterFlashAttentionPrefillMetadata(
                max_query_len=query_lens_for_prefill.max().item(),
                max_seq_len=seq_lens[num_decodes + num_extends :].max().item(),
                query_start_loc=query_start_loc_device - query_start_loc_device[0],
            )

        extend_metadata = None
        if num_extends > 0:
            assert seq_lens is not None
            num_extends_slice = slice(num_decodes, num_decodes + num_extends)
            query_lens_for_extend = query_lens_cpu[num_extends_slice]
            seq_lens_for_extend = seq_lens[num_extends_slice]
            computed_kv_lens = seq_lens_for_extend - query_lens_for_extend
            swa_metadata = None
            if self.aot_sliding_window is not None:
                swa_seqlen_for_extend = torch.minimum(
                    seq_lens_for_extend,
                    query_lens_for_extend + self.aot_sliding_window[0] + 1,
                )
                cu_seq_lens = torch.zeros(
                    num_extends + 1,
                    dtype=torch.int32,
                    device=seq_lens_for_extend.device,
                    pin_memory=True,
                )
                torch.cumsum(
                    swa_seqlen_for_extend,
                    dim=0,
                    dtype=cu_seq_lens.dtype,
                    out=cu_seq_lens[1:],
                )
                token_to_seq = torch.arange(
                    0,
                    num_extends,
                    dtype=torch.int32,
                    device=seq_lens_for_extend.device,
                )
                token_to_seq = torch.repeat_interleave(
                    token_to_seq, swa_seqlen_for_extend
                )
                fetched_shape = cu_seq_lens[-1].item()
                # TODO(ganyi): Maybe reuse these 2 buffer from extend_workspace
                swa_workspace = torch.empty(
                    (2, fetched_shape, self.num_heads_kv, self.headdim),
                    dtype=self.vllm_config.model_config.dtype,
                    device=self.device,
                )

                seq_starts = seq_lens_for_extend - swa_seqlen_for_extend
                max_seqlen_k = swa_seqlen_for_extend.max().item()
                total_tokens = cu_seq_lens[-1].item()

                swa_metadata = AiterChunkSlidingWindowMetadata(
                    swa_cu_seqlens=cu_seq_lens.to(self.device, non_blocking=True),
                    swa_seq_starts=async_tensor_h2d(seq_starts, self.device),
                    swa_token_to_batch=async_tensor_h2d(token_to_seq, self.device),
                    swa_max_seqlens=max_seqlen_k,
                    swa_total_tokens=total_tokens,
                    swa_workspace=swa_workspace,
                )

            # Split the workspace only among extends that have context to read.
            num_extends_with_context = max(int((computed_kv_lens > 0).sum()), 1)
            max_context_chunk = _CP_TOKENS_PER_ITER_ROCM // num_extends_with_context
            num_chunks = cdiv(computed_kv_lens.max().item(), max_context_chunk)

            chunk_starts = (
                torch.arange(num_chunks, dtype=torch.int32)
                .unsqueeze(1)
                .expand(-1, num_extends)
                * max_context_chunk
            )
            chunk_ends = torch.min(
                computed_kv_lens.unsqueeze(0), chunk_starts + max_context_chunk
            )
            chunk_seq_lens = chunk_ends - chunk_starts
            chunk_seq_lens.clamp_(min=0)  # [num_chunks, num_extends]
            cu_seq_lens_cpu = torch.zeros(
                [num_chunks, num_extends + 1], dtype=torch.int32, pin_memory=True
            )
            torch.cumsum(
                chunk_seq_lens, dim=1, out=cu_seq_lens_cpu[:, 1:], dtype=torch.int32
            )
            # Avoid .max() on an empty tensor when there is no context
            # (num_chunks == 0, e.g. Whisper encoder's first pass).
            max_cum_tokens = (
                cu_seq_lens_cpu[:, -1].max().item() if num_chunks > 0 else 0
            )

            range_idx = torch.arange(max_cum_tokens, dtype=torch.int32)[None, None, :]
            idx_to_batch_tensor = range_idx == cu_seq_lens_cpu[:, 1:][:, :, None]
            idx_to_batch_tensor = idx_to_batch_tensor.sum(
                dim=1
            )  # [num_chunks, max_cum_tokens]
            token_to_batch_tensor = torch.cumsum(idx_to_batch_tensor, dim=1)

            chunk_context_metadata = AiterChunkContextMetadata(
                workspace=self.extend_workspace,
                cu_seq_lens_chunk=cu_seq_lens_cpu.to(self.device, non_blocking=True),
                chunk_starts=async_tensor_h2d(chunk_starts, self.device),
                token_to_batch=async_tensor_h2d(token_to_batch_tensor, self.device),
                max_seq_lens=chunk_seq_lens.max(dim=1).values.tolist(),
                num_chunks=num_chunks,
                total_token_per_batch=cu_seq_lens_cpu[:, -1].tolist(),
                swa_metadata=swa_metadata,
            )

            query_start_loc_device = common_attn_metadata.query_start_loc[
                num_decodes : num_decodes + num_extends + 1
            ]
            seq_lens_device = common_attn_metadata.seq_lens[num_extends_slice]
            cu_seq_lens = torch.zeros(
                num_extends + 1, dtype=torch.int32, device=seq_lens_device.device
            )
            torch.cumsum(
                seq_lens_device, dim=0, dtype=cu_seq_lens.dtype, out=cu_seq_lens[1:]
            )
            extend_metadata = AiterFlashAttentionChunkPrefillMetadata(
                max_query_len=query_lens_for_extend.max().item(),
                max_seq_len=seq_lens[num_extends_slice].max().item(),
                query_start_loc=query_start_loc_device - query_start_loc_device[0],
                chunk_context_metadata=chunk_context_metadata,
            )

        attn_metadata = AiterFlashAttentionMetadata(
            num_actual_tokens=common_attn_metadata.num_actual_tokens,
            query_start_loc=common_attn_metadata.query_start_loc,
            max_seq_len=common_attn_metadata.max_seq_len,
            seq_lens=common_attn_metadata.seq_lens,
            block_table=common_attn_metadata.block_table_tensor,
            causal=common_attn_metadata.causal,
            slot_mapping=common_attn_metadata.slot_mapping,
            num_decodes=num_decodes,
            num_decode_tokens=num_decode_tokens,
            num_prefills=num_prefills,
            num_extends=num_extends,
            num_extend_tokens=num_extend_tokens,
            decode_metadata=decode_metadata,
            prefill_metadata=prefill_metadata,
            extend_metadata=extend_metadata,
            k_scale=self.k_scale,
            v_scale=self.v_scale,
            kv_sharing_metadata=kv_sharing_metadata,
        )
        return attn_metadata

_build_swa_decode_tables(block_table, seq_lens, num_decodes, max_seq_len)

Trim the decode block table to the sliding window.

Exact: the kernel's window mask drops the leading tokens of the first kept block, and RoPE is already applied in the cache.

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
def _build_swa_decode_tables(
    self,
    block_table: torch.Tensor,
    seq_lens: torch.Tensor,
    num_decodes: int,
    max_seq_len: int,
) -> tuple[torch.Tensor | None, torch.Tensor | None, int]:
    """Trim the decode block table to the sliding window.

    Exact: the kernel's window mask drops the leading tokens of the first
    kept block, and RoPE is already applied in the cache.
    """
    if (
        self._swa_block_table is None
        or self.aot_sliding_window is None
        or num_decodes > self._swa_block_table.shape[0]
    ):
        return None, None, 0
    assert self._swa_seq_lens is not None and self._swa_block_offsets is not None
    window = self.aot_sliding_window[0] + 1
    lens = seq_lens[:num_decodes]
    first_block = (lens - window).clamp_(min=0) // self.block_size
    index = (self._swa_block_offsets + first_block[:, None]).clamp_(
        max=block_table.shape[1] - 1
    )
    swa_block_table = self._swa_block_table[:num_decodes]
    torch.gather(block_table[:num_decodes], 1, index, out=swa_block_table)
    swa_seq_lens = self._swa_seq_lens[:num_decodes]
    torch.sub(lens, first_block, alpha=self.block_size, out=swa_seq_lens)
    return (
        swa_block_table,
        swa_seq_lens,
        min(max_seq_len, window + self.block_size - 1),
    )

AsmKvScaleTables dataclass

Dense per-slot scale tables the asm decode kernel reads for an fp8 cache.

One table per distinct (device, shape, scale), shared by every layer and every metadata builder in the process, so the target and draft models with equal scales reuse a single allocation. Tables are constants: never write to one in place; a per-token or dynamic scale needs its own buffer.

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
@dataclass(slots=True)
class AsmKvScaleTables:
    """Dense per-slot scale tables the asm decode kernel reads for an fp8 cache.

    One table per distinct (device, shape, scale), shared by every layer and
    every metadata builder in the process, so the target and draft models with
    equal scales reuse a single allocation. Tables are constants: never write
    to one in place; a per-token or dynamic scale needs its own buffer.
    """

    tables: dict[tuple[str, int, int, int, float], torch.Tensor] = field(
        default_factory=dict
    )

    def get(
        self,
        device: torch.device,
        num_blocks: int,
        num_kv_heads: int,
        block_size: int,
        scale: float,
    ) -> torch.Tensor:
        key = (str(device), num_blocks, num_kv_heads, block_size, scale)
        table = self.tables.get(key)
        if table is None:
            table = torch.full(
                (num_blocks, num_kv_heads, block_size),
                scale,
                dtype=torch.float32,
                device=device,
            )
            self.tables[key] = table
        return table

_uses_fast_verify(vllm_config, kv_cache_dtype)

Whether a layer can use the decode kernels in vllm.v1.attention.ops.rocm_gqa_verify: gfx950 and an FP8 e4m3 KV cache in the default (unshuffled) layout. The layer still has to pass supports_layer.

Source code in vllm/v1/attention/backends/rocm_aiter_fa.py
def _uses_fast_verify(vllm_config: VllmConfig | None, kv_cache_dtype: str) -> bool:
    """Whether a layer can use the decode kernels in
    `vllm.v1.attention.ops.rocm_gqa_verify`: gfx950 and an FP8 e4m3 KV cache in the
    default (unshuffled) layout. The layer still has to pass `supports_layer`."""
    if vllm_config is None or not current_platform.is_rocm():
        return False
    if (
        kv_cache_dtype not in ("fp8", "fp8_e4m3")
        or rocm_aiter_ops.is_shuffle_kv_cache_enabled()
    ):
        return False
    from vllm.platforms.rocm import on_gfx950

    return on_gfx950()