Skip to content

vllm.v1.attention.backends.flashinfer

Attention layer with FlashInfer.

Classes:

Functions:

  • fast_plan_decode

    A faster version of BatchDecodeWithPagedKVCacheWrapper::plan used for

BatchDCPPrefillWrapper

Methods:

  • plan

    Plan the prefill operation with given parameters.

Source code in vllm/v1/attention/backends/flashinfer.py
class BatchDCPPrefillWrapper:
    def __init__(
        self,
        kv_layout: str,
        workspace_buffer: torch.Tensor | None = None,
        dcp_a2a: bool = False,
    ):
        if dcp_a2a:
            self._dcp_combine = partial(dcp_a2a_lse_reduce, is_lse_base_on_e=False)
        else:
            self._dcp_combine = partial(cp_lse_ag_out_rs, is_lse_base_on_e=False)
        self._context = BatchPrefillWithPagedKVCacheWrapper(workspace_buffer, kv_layout)
        self._new_tokens = BatchPrefillWithRaggedKVCacheWrapper(workspace_buffer)

    def plan(
        self,
        qo_indptr_cpu: torch.Tensor,
        paged_kv_indptr_cpu: torch.Tensor,
        paged_kv_indices: torch.Tensor,
        paged_kv_last_page_len_cpu: torch.Tensor,
        page_size: int,
        num_qo_heads: int,
        dcp_world_size: int,
        num_kv_heads: int,
        head_dim: int,
        sm_scale: float,
        window_left: int,
        logits_soft_cap: float | None,
        q_data_type: torch.dtype,
        kv_cache_dtype: torch.dtype,
        prefill_fixed_split_size: int,
        disable_split_kv: bool,
    ):
        """Plan the prefill operation with given parameters."""
        self._context.plan(
            qo_indptr=qo_indptr_cpu,
            paged_kv_indptr=paged_kv_indptr_cpu,
            paged_kv_indices=paged_kv_indices,
            paged_kv_last_page_len=paged_kv_last_page_len_cpu,
            num_qo_heads=num_qo_heads * dcp_world_size,
            num_kv_heads=num_kv_heads,
            head_dim_qk=head_dim,
            page_size=page_size,
            causal=False,  # This is context run
            sm_scale=sm_scale,
            window_left=window_left,
            logits_soft_cap=logits_soft_cap,
            q_data_type=q_data_type,
            kv_data_type=kv_cache_dtype,
            fixed_split_size=prefill_fixed_split_size,
            disable_split_kv=disable_split_kv,
        )
        self._new_tokens.plan(
            qo_indptr=qo_indptr_cpu,
            kv_indptr=qo_indptr_cpu,
            num_qo_heads=num_qo_heads,
            num_kv_heads=num_kv_heads,
            head_dim_qk=head_dim,
            head_dim_vo=head_dim,
            causal=True,  # This is newtokens run
            sm_scale=sm_scale,
            window_left=window_left,
            logits_soft_cap=logits_soft_cap,
            q_data_type=q_data_type,
        )

    def run(
        self,
        layer: torch.nn.Module,
        prefill_query: torch.Tensor,
        kv_cache_tuple: tuple[torch.Tensor, torch.Tensor],
        key: torch.Tensor,
        value: torch.Tensor,
        out: torch.Tensor,
    ):
        prefill_query_across_dcp = get_dcp_group().all_gather(
            prefill_query.contiguous(), dim=1
        )
        output_context_tmp, lse_context_tmp = self._context.run(
            prefill_query_across_dcp,
            kv_cache_tuple,
            k_scale=layer._k_scale_float,
            v_scale=layer._v_scale_float,
            return_lse=True,
        )
        output_context, lse_context = self._dcp_combine(
            output_context_tmp,
            lse_context_tmp,
            get_dcp_group(),
            return_lse=True,
        )
        lse_context = log2_lse_to_ln(lse_context.transpose(0, 1).contiguous())

        output_query, lse_query = self._new_tokens.run(
            prefill_query,
            key,
            value,
            return_lse=True,
        )
        lse_query = log2_lse_to_ln(lse_query.transpose(0, 1).contiguous())

        merge_attn_states(
            out,
            output_context,
            lse_context,
            output_query,
            lse_query,
        )
        return out

plan(qo_indptr_cpu, paged_kv_indptr_cpu, paged_kv_indices, paged_kv_last_page_len_cpu, page_size, num_qo_heads, dcp_world_size, num_kv_heads, head_dim, sm_scale, window_left, logits_soft_cap, q_data_type, kv_cache_dtype, prefill_fixed_split_size, disable_split_kv)

Plan the prefill operation with given parameters.

Source code in vllm/v1/attention/backends/flashinfer.py
def plan(
    self,
    qo_indptr_cpu: torch.Tensor,
    paged_kv_indptr_cpu: torch.Tensor,
    paged_kv_indices: torch.Tensor,
    paged_kv_last_page_len_cpu: torch.Tensor,
    page_size: int,
    num_qo_heads: int,
    dcp_world_size: int,
    num_kv_heads: int,
    head_dim: int,
    sm_scale: float,
    window_left: int,
    logits_soft_cap: float | None,
    q_data_type: torch.dtype,
    kv_cache_dtype: torch.dtype,
    prefill_fixed_split_size: int,
    disable_split_kv: bool,
):
    """Plan the prefill operation with given parameters."""
    self._context.plan(
        qo_indptr=qo_indptr_cpu,
        paged_kv_indptr=paged_kv_indptr_cpu,
        paged_kv_indices=paged_kv_indices,
        paged_kv_last_page_len=paged_kv_last_page_len_cpu,
        num_qo_heads=num_qo_heads * dcp_world_size,
        num_kv_heads=num_kv_heads,
        head_dim_qk=head_dim,
        page_size=page_size,
        causal=False,  # This is context run
        sm_scale=sm_scale,
        window_left=window_left,
        logits_soft_cap=logits_soft_cap,
        q_data_type=q_data_type,
        kv_data_type=kv_cache_dtype,
        fixed_split_size=prefill_fixed_split_size,
        disable_split_kv=disable_split_kv,
    )
    self._new_tokens.plan(
        qo_indptr=qo_indptr_cpu,
        kv_indptr=qo_indptr_cpu,
        num_qo_heads=num_qo_heads,
        num_kv_heads=num_kv_heads,
        head_dim_qk=head_dim,
        head_dim_vo=head_dim,
        causal=True,  # This is newtokens run
        sm_scale=sm_scale,
        window_left=window_left,
        logits_soft_cap=logits_soft_cap,
        q_data_type=q_data_type,
    )

FIDecode dataclass

Metadata for the native FlashInfer decode pathway (non-TRTLLM).

Source code in vllm/v1/attention/backends/flashinfer.py
@dataclass
class FIDecode:
    """Metadata for the native FlashInfer decode pathway (non-TRTLLM)."""

    wrapper: BatchDecodeWithPagedKVCacheWrapper

FIPrefill dataclass

Metadata for the native FlashInfer prefill pathway (non-TRTLLM).

Source code in vllm/v1/attention/backends/flashinfer.py
@dataclass
class FIPrefill:
    """Metadata for the native FlashInfer prefill pathway (non-TRTLLM)."""

    wrapper: BatchPrefillWithPagedKVCacheWrapper | BatchDCPPrefillWrapper

FlashInferBackend

Bases: AttentionBackend

Methods:

  • customize_spec

    NVFP4 stores K and V as separate per-head slots of packed fp4 data

  • supports_sink

    FlashInfer supports sinks on SM12x XQA and SM100 trtllm-gen.

Source code in vllm/v1/attention/backends/flashinfer.py
class FlashInferBackend(AttentionBackend):
    @classmethod
    def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
        """NVFP4 stores K and V as separate per-head slots of packed fp4 data
        plus fp8 block scales."""
        if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_nvfp4:
            return spec
        hs_k = nvfp4_kv_cache_full_dim(spec.head_size)
        hs_v = nvfp4_kv_cache_full_dim(spec.head_size_v)
        assert hs_k == hs_v, "nvfp4 with asymmetric K/V head sizes not yet supported"
        return replace(
            spec,
            num_head_slots=2 * spec.num_kv_heads,
            state_content_bytes=hs_k * get_dtype_size(spec.dtype),
        )

    supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16]
    supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
        "auto",
        "float16",
        "bfloat16",
        "fp8",
        "fp8_e4m3",
        "fp8_e5m2",
        "nvfp4",
        "nvfp4_4over6",
    ]

    @staticmethod
    def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
        # Page sizes >= 128 only run on the trtllm-gen dynamic kernel (GQA/MQA
        # on Blackwell); advertise them only when usable so selection never
        # picks a large kernel block we cannot serve.
        use_large_pages = False
        vllm_config = get_current_vllm_config_or_none()
        if vllm_config is not None and vllm_config.model_config is not None:
            pc = vllm_config.parallel_config
            mc = vllm_config.model_config
            num_qo_heads = mc.get_num_attention_heads(pc)
            num_kv_heads = mc.get_num_kv_heads(pc)
            use_large_pages = (
                num_kv_heads > 0
                and num_qo_heads // num_kv_heads > 1
                and current_platform.is_device_capability_family(100)
                and can_use_trtllm_attention(num_qo_heads, num_kv_heads)
            )
        if not use_large_pages:
            return [16, 32, 64]
        return [16, 32, 64, 128, 256, 512, 1024]

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

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

    @classmethod
    def supports_device_cpu_query_lens_mismatch(cls) -> bool:
        # The wrappers are planned from qo_indptr_cpu, so the CPU query offsets
        # have to be the ones the kernel runs on.
        return False

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

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

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

    @staticmethod
    def get_dtype_for_flashinfer(kv_cache_dtype: str) -> torch.dtype:
        if kv_cache_dtype in ("fp8", "fp8_e4m3"):
            return torch.float8_e4m3fn
        elif kv_cache_dtype == "fp8_e5m2":
            return torch.float8_e5m2
        elif kv_cache_dtype.startswith("nvfp4"):
            return torch.uint8
        else:
            raise ValueError(f"Unrecognized dtype: {kv_cache_dtype}")

    @classmethod
    def supports_kv_cache_dtype(cls, kv_cache_dtype: CacheDType | None) -> bool:
        if kv_cache_dtype is not None and kv_cache_dtype.startswith("nvfp4"):
            return (
                current_platform.is_device_capability_family(100)
                and supports_trtllm_attention(is_prefill=True)
                and supports_trtllm_attention(is_prefill=False)
            )
        return super().supports_kv_cache_dtype(kv_cache_dtype)

    @classmethod
    def get_supported_head_sizes(cls) -> list[int]:
        # https://github.com/flashinfer-ai/flashinfer/blob/3d55c71a62052c590c130897d3a3db49b14fcc34/include/flashinfer/utils.cuh#L157
        return [64, 128, 256, 512]

    @classmethod
    def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
        # FlashInfer supports SM75+, but is currently broken on SM75 (Turing):
        # https://github.com/flashinfer-ai/flashinfer/issues/3620 (fix:
        # https://github.com/flashinfer-ai/flashinfer/pull/3621). Temporarily
        # raise the floor to SM80 so it is not auto-selected on SM75 until
        # that fix lands; revert to DeviceCapability(7, 5) once it does.
        return capability >= DeviceCapability(8, 0) and capability <= DeviceCapability(
            12, 1
        )

    @classmethod
    def supports_sink(cls) -> bool:
        """FlashInfer supports sinks on SM12x XQA and SM100 trtllm-gen."""
        from vllm.utils.flashinfer import (
            force_use_trtllm_attention,
        )

        if force_use_trtllm_attention() is False:
            return False

        if current_platform.is_device_capability_family(120):
            return supports_trtllm_attention(is_prefill=False)

        if not current_platform.is_device_capability_family(100):
            return False

        return supports_trtllm_attention(
            is_prefill=False
        ) and supports_trtllm_attention(is_prefill=True)

    @classmethod
    def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None:
        capability = current_platform.get_device_capability()
        if capability is not None and capability.major == 10:
            # The trtllm-gen kernels consume head-major block interiors; the L/B
            # nesting outside the block is immaterial to them.
            return (KVCacheLayout.LBHNC, KVCacheLayout.BLHNC)
        return super().supported_kv_cache_layouts()

    forward_includes_kv_cache_update: bool = False

customize_spec(spec) classmethod

NVFP4 stores K and V as separate per-head slots of packed fp4 data plus fp8 block scales.

Source code in vllm/v1/attention/backends/flashinfer.py
@classmethod
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
    """NVFP4 stores K and V as separate per-head slots of packed fp4 data
    plus fp8 block scales."""
    if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_nvfp4:
        return spec
    hs_k = nvfp4_kv_cache_full_dim(spec.head_size)
    hs_v = nvfp4_kv_cache_full_dim(spec.head_size_v)
    assert hs_k == hs_v, "nvfp4 with asymmetric K/V head sizes not yet supported"
    return replace(
        spec,
        num_head_slots=2 * spec.num_kv_heads,
        state_content_bytes=hs_k * get_dtype_size(spec.dtype),
    )

supports_sink() classmethod

FlashInfer supports sinks on SM12x XQA and SM100 trtllm-gen.

Source code in vllm/v1/attention/backends/flashinfer.py
@classmethod
def supports_sink(cls) -> bool:
    """FlashInfer supports sinks on SM12x XQA and SM100 trtllm-gen."""
    from vllm.utils.flashinfer import (
        force_use_trtllm_attention,
    )

    if force_use_trtllm_attention() is False:
        return False

    if current_platform.is_device_capability_family(120):
        return supports_trtllm_attention(is_prefill=False)

    if not current_platform.is_device_capability_family(100):
        return False

    return supports_trtllm_attention(
        is_prefill=False
    ) and supports_trtllm_attention(is_prefill=True)

FlashInferDecodeKernel

Bases: Enum

Decode kernels selected inside the FlashInfer backend.

Source code in vllm/v1/attention/backends/flashinfer.py
class FlashInferDecodeKernel(Enum):
    """Decode kernels selected inside the FlashInfer backend."""

    XQA = "xqa"
    TRTLLM_GEN = "trtllm-gen"

FlashInferImpl

Bases: AttentionImpl

Methods:

  • forward

    Forward pass with FlashInfer.

Source code in vllm/v1/attention/backends/flashinfer.py
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
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
class FlashInferImpl(AttentionImpl):
    can_return_lse_for_decode: bool = True

    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.window_left = (
            self.sliding_window[0] if self.sliding_window is not None else -1
        )
        self.cache_dtype = kv_cache_dtype
        self.is_kvcache_nvfp4 = kv_cache_dtype.startswith("nvfp4")
        self.kv_cache_dtype = "nvfp4" if self.is_kvcache_nvfp4 else kv_cache_dtype
        self.fp4_data_dim = head_size // 2 if self.is_kvcache_nvfp4 else 0
        self.logits_soft_cap = logits_soft_cap
        self.kv_sharing_target_layer_name = kv_sharing_target_layer_name

        self.num_queries_per_kv = self.num_heads // self.num_kv_heads

        if attn_type != AttentionType.DECODER:
            raise NotImplementedError(
                "Encoder self-attention and "
                "encoder/decoder cross-attention "
                "are not implemented for "
                "FlashInferImpl"
            )

        self.sinks: torch.Tensor | None = None
        # Keep the source so RL weight updates can refresh the runtime tensor.
        self._sinks_source = sinks
        if sinks is not None:
            if sinks.shape[0] != num_heads:
                raise ValueError(
                    "Sinks must have the same number of heads as the number of "
                    f"heads in the layer. Expected {num_heads}, but got "
                    f"{sinks.shape[0]}."
                )
            self.sinks = sinks

        self.supports_xqa_or_trtllm_gen_decode = can_use_trtllm_attention(
            num_heads, num_kv_heads, is_prefill=False
        )
        vllm_config = get_current_vllm_config_or_none()
        # The layout is resolved after model construction, so read it lazily.
        self.cache_config = vllm_config.cache_config if vllm_config else None
        # Query pre-quantization needs a single dtype for the whole query tensor.
        # SM90 XQA needs BF16/FP16-Q for decode and FP8 for prefill,
        # so only enable this for SM100 trtllm-gen where both use FP8-Q.
        self.supports_quant_query_input = (
            self.supports_xqa_or_trtllm_gen_decode
            and is_quantized_kv_cache(self.kv_cache_dtype)
            and current_platform.is_device_capability_family(100)
            and vllm_config is not None
            and not vllm_config.attention_config.disable_flashinfer_q_quantization
        )
        self.bmm1_scale: float | None = None
        self.bmm2_scale: float | None = None
        self.o_sf_scale: float | None = None

        # Pre-allocated FP8 output buffer for NVFP4 without fused output quant.
        if self.is_kvcache_nvfp4 and vllm_config is not None:
            max_num_tokens = vllm_config.scheduler_config.max_num_batched_tokens
            self._nvfp4_fp8_out = torch.empty(
                (max_num_tokens, num_heads, head_size),
                dtype=FP8_DTYPE,
                device="cuda",
            )
        else:
            self._nvfp4_fp8_out = None

        dcp_a2a = (
            vllm_config is not None
            and vllm_config.parallel_config.decode_context_parallel_size > 1
            and vllm_config.parallel_config.dcp_comm_backend == "a2a"
        )
        if dcp_a2a:
            self.dcp_combine = partial(dcp_a2a_lse_reduce, is_lse_base_on_e=False)
        else:
            self.dcp_combine = partial(cp_lse_ag_out_rs, is_lse_base_on_e=False)

    @property
    def kv_cache_layout(self) -> KVCacheLayout:
        assert self.cache_config is not None
        return self.cache_config.get_resolved_kv_cache_layout()

    def fused_output_quant_supported(self, quant_key: QuantKey):
        # XQA does not support FP8/NVFP4 output, so require trtllm-gen
        # (SM100+) here.  Without that we cannot fuse the output quant.
        return (
            self.supports_xqa_or_trtllm_gen_decode
            and is_quantized_kv_cache(self.kv_cache_dtype)
            and current_platform.is_device_capability_family(100)
            and quant_key in (kFp8StaticTensorSym, kNvfp4Dynamic)
        )

    # FlashInfer requires attention sinks to be float32
    def process_weights_after_loading(self, act_dtype: torch.dtype):
        source_sinks = self._sinks_source
        if source_sinks is None:
            return
        if source_sinks.dtype == torch.float32:
            self.sinks = source_sinks
        elif self.sinks is None or self.sinks.dtype != torch.float32:
            self.sinks = source_sinks.to(torch.float32)
        else:
            self.sinks.copy_(source_sinks)

    def get_xqa_bmm1_scale(self, layer: torch.nn.Module, q_data_type: torch.dtype):
        bmm1_scale = self.scale
        if is_quantized_kv_cache(self.kv_cache_dtype):
            if q_data_type in (torch.float8_e4m3fn, torch.float8_e5m2):
                bmm1_scale *= layer._q_scale_float
            bmm1_scale *= layer._k_scale_float
        return bmm1_scale

    # SM90 may need FP8-Q for native prefill and BF16/FP16-Q for XQA decode,
    # so quantize only the slice whose target dtype differs.
    def maybe_quant_query(
        self,
        query: torch.Tensor,
        q_data_type: torch.dtype,
        scale: torch.Tensor,
    ) -> torch.Tensor:
        if query.dtype != q_data_type:
            assert query.dtype in [torch.float16, torch.bfloat16]
            assert q_data_type in [torch.float8_e4m3fn, torch.float8_e5m2]
            assert query.dim() == 3
            num_tokens = query.shape[0]
            num_heads = query.shape[1]
            head_size = query.shape[2]
            assert query.stride(2) == 1 and query.stride(1) == head_size
            query_quantized, _ = custom_ops.scaled_fp8_quant(
                query.view(num_tokens, num_heads * head_size), scale=scale
            )
            return query_quantized.view(num_tokens, num_heads, head_size)

        return query

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

        Args:
            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: [num_blocks, num_kv_heads, block_size, 2*head_size]
            attn_metadata: Metadata for attention.
        Returns:
            shape = [num_tokens, num_heads * head_size]
        """
        if attn_metadata is None:
            # Profiling run.
            return output.fill_(0)

        if self.bmm1_scale is None:
            self.bmm1_scale = self.scale
            if is_quantized_kv_cache(self.kv_cache_dtype):
                self.bmm1_scale *= layer._q_scale_float * layer._k_scale_float

        if self.bmm2_scale is None:
            self.bmm2_scale = 1.0
            if is_quantized_kv_cache(self.kv_cache_dtype):
                self.bmm2_scale *= layer._v_scale_float

        prefill_use_trtllm = isinstance(attn_metadata.prefill, TRTLLMPrefill)
        decode_kernel = (
            attn_metadata.decode.kernel
            if isinstance(attn_metadata.decode, FlashInferTrtllmAPIDecode)
            else None
        )
        decode_with_xqa = decode_kernel == FlashInferDecodeKernel.XQA
        decode_with_trtllm_gen = decode_kernel == FlashInferDecodeKernel.TRTLLM_GEN
        decode_with_flashinfer_trtllm_api = decode_with_xqa or decode_with_trtllm_gen

        # The attn+quant fusion happens when output_scale is provided.
        if output_scale is None:
            assert output_block_scale is None, (
                "output_block_scale is not supported when fusion has not happened"
            )
        else:
            assert attn_metadata.q_data_type_prefill == FP8_DTYPE, (
                "Query must be FP8 when attn+quant fusion happened for prefill."
            )
            assert attn_metadata.q_data_type_decode == FP8_DTYPE, (
                "Query must be FP8 when attn+quant fusion happened for decode."
            )
            assert (attn_metadata.num_prefills == 0 or prefill_use_trtllm) and (
                attn_metadata.num_decodes == 0 or decode_with_trtllm_gen
            ), "Output quant fusion requires TRTLLM prefill/trtllm-gen decode"

            if output.dtype == FP8_DTYPE:
                assert output_block_scale is None, (
                    "output_block_scale should not be provided for fp8 output"
                )
            elif output.dtype == FP4_DTYPE:
                assert output_block_scale is not None, (
                    "output_block_scale is required for nvfp4 output"
                )
            else:
                raise ValueError(f"Unsupported output dtype: {output.dtype}")

            # TRTLLM attn kernel requires to scale to pass as a host scalar,
            # store the o scale as a host scalar in warmup run with cuda graph
            # not enabled
            if layer._o_scale_float is None:
                layer._o_scale_float = output_scale.cpu().item()
                if output.dtype == FP8_DTYPE:
                    self.bmm2_scale = self.bmm2_scale / layer._o_scale_float
                elif output.dtype == FP4_DTYPE:
                    self.o_sf_scale = layer._o_scale_float

        # 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

        # FlashInfer treats uint8 KV cache as NVFP4. vLLM stores FP8 KV cache
        # as uint8 bytes, so pass FP8 caches with their logical dtype.
        if not self.is_kvcache_nvfp4 and kv_cache.dtype == torch.uint8:
            fp8_view_dtype = None
            if self.kv_cache_dtype in ("fp8", "fp8_e4m3", torch.float8_e4m3fn):
                fp8_view_dtype = torch.float8_e4m3fn
            elif self.kv_cache_dtype in ("fp8_e5m2", torch.float8_e5m2):
                fp8_view_dtype = torch.float8_e5m2
            if fp8_view_dtype is not None:
                kv_cache = kv_cache.view(fp8_view_dtype)

        # Inputs and outputs may be padded for CUDA graphs
        query = query[:num_actual_tokens]
        key = key[:num_actual_tokens]
        value = value[:num_actual_tokens]
        output_padded = output
        output = output[:num_actual_tokens]

        if attn_metadata.use_cascade:
            # Cascade attention (rare case).
            assert attn_metadata.cascade_wrapper is not None
            stride_order = self.kv_cache_layout.layer_view_order
            if self.is_kvcache_nvfp4:
                kv_cache_views = tuple(
                    cache.permute(*stride_order)
                    for cache in kv_cache.split(self.num_kv_heads, dim=1)
                )
            else:
                kv_perm = kv_cache.permute(*stride_order)
                kv_cache_views = kv_perm.split(self.head_size, dim=-1)
            kv_tuple = tuple(
                canonicalize_singleton_dim_strides(cache) for cache in kv_cache_views
            )
            output.copy_(attn_metadata.cascade_wrapper.run(query, kv_tuple))
            return output

        # When using spec decoding, num_decodes can be < num_decode_tokens
        # because some decode requests may have more than one query token.
        num_decode_tokens = attn_metadata.num_decode_tokens
        num_prefill_tokens = attn_metadata.num_prefill_tokens

        stride_order = self.kv_cache_layout.layer_view_order
        kv_cache_permute = kv_cache.permute(*stride_order)  # HND and contiguous
        # Fix degenerate strides on any size-1 dimension (e.g. num_kv_heads=1
        # with TP=8).  PyTorch permits non-canonical strides on size-1 dims;
        # CUDA TMA requires ≥16-byte alignment on all non-outermost strides.
        # canonicalize_singleton_dim_strides patches metadata via as_strided —
        # zero-copy.  See vllm.utils.torch_utils.
        fixed = canonicalize_singleton_dim_strides(kv_cache_permute)
        if fixed is not kv_cache_permute:
            logger.debug(
                "Canonicalized degenerate KV cache strides (FlashInfer): "
                "shape=%s, strides before=%s, strides after=%s",
                kv_cache_permute.shape,
                kv_cache_permute.stride(),
                fixed.stride(),
            )
        kv_cache_permute = fixed

        # Split K/V — zero-copy views. NVFP4 stores K/V as separate head
        # groups; other dtypes pack K/V in the content dim.
        hs = self.head_size
        nvfp4_kv_data = None
        nvfp4_kv_block_scales = None
        if self.is_kvcache_nvfp4:
            k_cache, v_cache = kv_cache.split(self.num_kv_heads, dim=1)
            kv_cache_tuple = (
                canonicalize_singleton_dim_strides(k_cache.permute(*stride_order)),
                canonicalize_singleton_dim_strides(v_cache.permute(*stride_order)),
            )
            k_data, k_sf = nvfp4_split_data_scale(kv_cache_tuple[0])
            v_data, v_sf = nvfp4_split_data_scale(kv_cache_tuple[1])
            nvfp4_kv_data = (k_data, v_data)
            nvfp4_kv_block_scales = (k_sf, v_sf)
        else:
            kv_cache_tuple = kv_cache_permute.split(hs, dim=-1)

        use_dcp = self.dcp_world_size > 1
        decode_with_dedicated_xqa = (
            decode_with_xqa and current_platform.is_device_capability_family(120)
        )
        if decode_with_dedicated_xqa:
            assert not use_dcp
            assert not self.is_kvcache_nvfp4
            assert self.o_sf_scale is None
            assert output.dtype != FP4_DTYPE

        # Regular attention (common case).
        # Decodes are at the front and prefills are at the back.
        if num_prefill_tokens > 0:
            prefill_query = query[num_decode_tokens:]
            assert prefill_query.shape[0] == num_prefill_tokens

            # Convert query to the expected dtype for prefill if needed.
            prefill_query = self.maybe_quant_query(
                prefill_query,
                attn_metadata.q_data_type_prefill,
                layer._q_scale,
            )

            if not prefill_use_trtllm:
                assert isinstance(attn_metadata.prefill, FIPrefill)
                prefill_wrapper = attn_metadata.prefill.wrapper
                assert prefill_wrapper is not None
                if use_dcp:
                    assert isinstance(prefill_wrapper, BatchDCPPrefillWrapper)
                    assert prefill_wrapper._context._window_left == self.window_left
                    assert prefill_wrapper._context._logits_soft_cap == (
                        self.logits_soft_cap or 0.0
                    )
                    assert prefill_wrapper._context._sm_scale == self.scale
                    assert not prefill_wrapper._context._causal
                    assert prefill_wrapper._new_tokens._window_left == self.window_left
                    assert prefill_wrapper._new_tokens._logits_soft_cap == (
                        self.logits_soft_cap or 0.0
                    )
                    assert prefill_wrapper._new_tokens._sm_scale == self.scale
                    assert prefill_wrapper._new_tokens._causal

                    prefill_wrapper.run(
                        layer,
                        prefill_query,
                        kv_cache_tuple,
                        key[num_decode_tokens:],
                        value[num_decode_tokens:],
                        out=output[num_decode_tokens:],
                    )
                else:
                    assert isinstance(
                        prefill_wrapper, BatchPrefillWithPagedKVCacheWrapper
                    )
                    assert prefill_wrapper._window_left == self.window_left
                    assert prefill_wrapper._logits_soft_cap == (
                        self.logits_soft_cap or 0.0
                    )
                    assert prefill_wrapper._sm_scale == self.scale
                    assert prefill_wrapper._causal == attn_metadata.causal

                    if self.is_kvcache_nvfp4:
                        kv_cache_for_fi = nvfp4_kv_data
                    else:
                        kv_cache_for_fi = kv_cache_tuple
                    kv_cache_sf = (
                        nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None
                    )

                    # NVFP4 trtllm kernel only supports FP8 output.
                    # Use a pre-allocated FP8 buffer and dequantize
                    # afterwards.
                    needs_fp8_out_prefill = (
                        self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
                    )
                    if needs_fp8_out_prefill:
                        out_prefill = self._nvfp4_fp8_out[:num_prefill_tokens]
                    else:
                        out_prefill = output[num_decode_tokens:]

                    if isinstance(
                        prefill_wrapper, BatchAttentionWithAttentionSinkWrapper
                    ):
                        assert self.sinks is not None
                        prefill_wrapper.run(
                            prefill_query,
                            kv_cache_for_fi,
                            self.sinks,
                            self.scale * layer._q_scale_float * layer._k_scale_float,
                            v_scale=layer._v_scale_float,
                            out=out_prefill,
                        )
                    else:
                        prefill_wrapper.run(
                            prefill_query,
                            kv_cache_for_fi,
                            q_scale=layer._q_scale_float,
                            k_scale=layer._k_scale_float,
                            v_scale=layer._v_scale_float,
                            out=out_prefill,
                            kv_cache_sf=kv_cache_sf,
                        )

                    if needs_fp8_out_prefill:
                        output[
                            num_decode_tokens : num_decode_tokens + num_prefill_tokens
                        ].copy_(out_prefill.to(output.dtype))
            else:
                assert isinstance(attn_metadata.prefill, TRTLLMPrefill)
                # prefill_query may be non-contiguous or have degenerate strides
                # on size=1 dims. contiguous() ensures memory layout; then
                # canonicalize_singleton_dim_strides fixes any remaining
                # degenerate strides on size=1 dims for TMA alignment.
                prefill_query = prefill_query.contiguous()
                prefill_query = canonicalize_singleton_dim_strides(prefill_query)
                workspace_buffer = _get_trtllm_workspace_buffer()
                block_tables_prefill = attn_metadata.prefill.block_tables
                seq_lens_prefill = attn_metadata.prefill.seq_lens

                # This path needs to be enabled with VLLM_KV_CACHE_LAYOUT = HND
                assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
                assert is_strictly_contiguous(prefill_query)
                assert is_strictly_contiguous(workspace_buffer)
                assert is_strictly_contiguous(block_tables_prefill)
                assert is_strictly_contiguous(seq_lens_prefill)

                if output.dtype == FP4_DTYPE:
                    assert self.o_sf_scale is not None
                    out = FP4Tensor(
                        data=output[num_decode_tokens:],
                        scale=output_block_scale,
                        scale_start_index=num_decode_tokens,
                        original_shape=prefill_query.shape,
                    )
                else:
                    assert self.o_sf_scale is None
                    out = output[num_decode_tokens:]

                # NVFP4 trtllm kernel only supports FP8 output.
                # Use a pre-allocated FP8 buffer and dequantize afterwards.
                needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
                if needs_fp8_out:
                    out = self._nvfp4_fp8_out[:num_prefill_tokens]

                prefill_kv_block_scales = None
                if self.is_kvcache_nvfp4:
                    # NVFP4 trtllm-gen kernel requires FP8 query.
                    assert attn_metadata.q_data_type_prefill == FP8_DTYPE, (
                        "NVFP4 KV cache requires FP8 quantized queries for "
                        "trtllm-gen prefill. Set "
                        "disable_flashinfer_q_quantization=False."
                    )
                    mock_kv_cache = nvfp4_kv_data
                    mock_block_table = block_tables_prefill
                    prefill_kv_block_scales = nvfp4_kv_block_scales
                elif (
                    attn_metadata.q_data_type_prefill != FP8_DTYPE
                    and self.kv_cache_dtype.startswith("fp8")
                ):
                    # TRTLLM prefill attention does not support BF16 Q
                    # and fp8 kv cache. So to enable prefill attention
                    # with fp8 kv cache, we can construct a mock block
                    # and mock kv cache with BF16 KV involved in the prefill.
                    kv_cache_permute = canonicalize_singleton_dim_strides(
                        kv_cache_permute
                    )
                    kv_strides = kv_cache_permute.stride()
                    assert (
                        kv_strides[-1] == 1
                        and kv_strides[-2] == kv_cache_permute.shape[-1]
                    ), (
                        "KV cache inner dims (block_size, head_size) must be "
                        f"contiguous, got strides {kv_strides}"
                    )
                    # fp8 uses (B, H, N, 2*hs); reshape to (B, 2, H, N, hs)
                    # for the dequant kernel — zero-copy view. The dequant
                    # kernel handles the interleaved K/V block stride.
                    B_kv, H_kv, N_kv = kv_cache_permute.shape[:3]
                    kv_cache_5d = kv_cache_permute.view(B_kv, H_kv, N_kv, 2, hs)
                    kv_cache_5d = kv_cache_5d.permute(0, 3, 1, 2, 4)
                    mock_kv_cache, mock_block_table = trtllm_prefill_attn_kvfp8_dequant(
                        kv_cache_5d,
                        block_tables_prefill,
                        layer._k_scale,
                        layer._v_scale,
                        attn_metadata.q_data_type_prefill,
                    )
                else:
                    mock_kv_cache = kv_cache_tuple
                    mock_block_table = block_tables_prefill

                trtllm_batch_context_with_kv_cache(
                    query=prefill_query,
                    kv_cache=mock_kv_cache,
                    workspace_buffer=workspace_buffer,
                    block_tables=mock_block_table,
                    seq_lens=seq_lens_prefill,
                    max_q_len=attn_metadata.prefill.max_q_len,
                    max_kv_len=attn_metadata.prefill.max_seq_len,
                    bmm1_scale=self.bmm1_scale,
                    bmm2_scale=self.bmm2_scale,
                    batch_size=attn_metadata.num_prefills,
                    cum_seq_lens_q=attn_metadata.prefill.cum_seq_lens_q,
                    cum_seq_lens_kv=attn_metadata.prefill.cum_seq_lens_kv,
                    window_left=self.window_left,
                    sinks=self.sinks,
                    o_sf_scale=self.o_sf_scale,
                    out=out,
                    kv_cache_sf=prefill_kv_block_scales,
                )

                if needs_fp8_out:
                    output[
                        num_decode_tokens : num_decode_tokens + num_prefill_tokens
                    ].copy_(out[:num_prefill_tokens].to(output.dtype))

        if num_decode_tokens > 0:
            decode_query = query[:num_decode_tokens]
            assert decode_query.shape[0] == num_decode_tokens

            # Convert query to the expected dtype for decode if needed.
            decode_query = self.maybe_quant_query(
                decode_query,
                attn_metadata.q_data_type_decode,
                layer._q_scale,
            )

            if not decode_with_flashinfer_trtllm_api:
                assert isinstance(attn_metadata.decode, FIDecode)
                decode_wrapper = attn_metadata.decode.wrapper
                assert decode_wrapper is not None
                assert decode_wrapper._window_left == self.window_left
                assert decode_wrapper._logits_soft_cap == (self.logits_soft_cap or 0.0)
                assert decode_wrapper._sm_scale == self.scale

                if self.is_kvcache_nvfp4:
                    kv_cache_for_fi = nvfp4_kv_data
                else:
                    kv_cache_for_fi = kv_cache_tuple
                kv_cache_sf = nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None

                # NVFP4 kernel only supports FP8 output.
                # Use a pre-allocated FP8 buffer and dequantize afterwards.
                needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
                if needs_fp8_out:
                    out_decode = self._nvfp4_fp8_out[:num_decode_tokens]
                else:
                    out_decode = output[:num_decode_tokens]

                if use_dcp:
                    decode_query = get_dcp_group().all_gather(
                        decode_query.contiguous(), dim=-2
                    )
                    output_tmp = torch.empty_like(decode_query)
                    lse = torch.empty(
                        (decode_query.size(0), decode_query.size(1)),
                        dtype=torch.float32,
                        device=decode_query.device,
                    )
                    decode_wrapper.run(
                        decode_query,
                        kv_cache_for_fi,
                        q_scale=layer._q_scale_float,
                        k_scale=layer._k_scale_float,
                        v_scale=layer._v_scale_float,
                        out=output_tmp,
                        lse=lse,
                        return_lse=True,
                        kv_cache_sf=kv_cache_sf,
                        sinks=self.sinks,
                    )
                    output[:num_decode_tokens] = self.dcp_combine(
                        output_tmp,
                        lse,
                        get_dcp_group(),
                    )
                else:
                    decode_wrapper.run(
                        decode_query,
                        kv_cache_for_fi,
                        q_scale=layer._q_scale_float,
                        k_scale=layer._k_scale_float,
                        v_scale=layer._v_scale_float,
                        out=out_decode,
                        kv_cache_sf=kv_cache_sf,
                        sinks=self.sinks,
                    )

                if needs_fp8_out:
                    output[:num_decode_tokens].copy_(out_decode.to(output.dtype))
            else:
                assert isinstance(attn_metadata.decode, FlashInferTrtllmAPIDecode)
                # decode_query may be non-contiguous or have degenerate strides
                # on size=1 dims. contiguous() ensures memory layout; then
                # canonicalize_singleton_dim_strides fixes any remaining
                # degenerate strides on size=1 dims for TMA alignment.
                decode_query = decode_query.contiguous()
                decode_query = canonicalize_singleton_dim_strides(decode_query)
                workspace_buffer = _get_trtllm_workspace_buffer()
                block_tables_decode = attn_metadata.decode.block_tables
                seq_lens_decode = attn_metadata.decode.seq_lens

                # trtllm-gen needs HND layout on SM100. XQA is selected
                # separately on SM90 and does not use this SM100 layout gate.
                if decode_with_trtllm_gen:
                    assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
                else:
                    assert decode_with_xqa
                assert is_strictly_contiguous(decode_query)
                assert is_strictly_contiguous(workspace_buffer)
                assert is_strictly_contiguous(block_tables_decode)
                assert is_strictly_contiguous(seq_lens_decode)
                kv_cache_permute = canonicalize_singleton_dim_strides(kv_cache_permute)
                kv_strides = kv_cache_permute.stride()
                assert (
                    kv_strides[-1] == 1 and kv_strides[-2] == kv_cache_permute.shape[-1]
                ), (
                    "KV cache inner dims (block_size, head_size) must be "
                    f"contiguous, got strides {kv_strides}"
                )

                if use_dcp:
                    assert decode_with_trtllm_gen
                    if output.dtype == FP4_DTYPE:
                        raise NotImplementedError(
                            "DCP decode with FlashInfer trtllm-gen does not support "
                            "FP4 attention output yet."
                        )
                    decode_query = get_dcp_group().all_gather(
                        decode_query.contiguous(), dim=-2
                    )
                    decode_query = canonicalize_singleton_dim_strides(decode_query)

                if decode_with_dedicated_xqa:
                    bmm1_scale = self.get_xqa_bmm1_scale(
                        layer, attn_metadata.q_data_type_decode
                    )
                    q_len_per_req = attn_metadata.decode.q_len_per_req

                    flashinfer_xqa_batch_decode_with_kv_cache(
                        query=decode_query,
                        kv_cache=kv_cache_tuple,
                        workspace_buffer=workspace_buffer,
                        block_tables=block_tables_decode,
                        seq_lens=seq_lens_decode,
                        max_seq_len=attn_metadata.decode.max_seq_len,
                        bmm1_scale=bmm1_scale,
                        bmm2_scale=self.bmm2_scale,
                        window_left=self.window_left,
                        out=output[:num_decode_tokens],
                        sinks=self.sinks,
                        kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
                        q_len_per_req=q_len_per_req,
                        mask=attn_metadata.decode.mask,
                        q_cu_seq_lens=attn_metadata.decode.q_cu_seq_lens,
                    )
                    return output_padded

                if output.dtype == FP4_DTYPE:
                    assert self.o_sf_scale is not None
                    out = FP4Tensor(
                        data=output[:num_decode_tokens],
                        scale=output_block_scale,
                        scale_start_index=0,
                        original_shape=decode_query.shape,
                    )
                else:
                    assert self.o_sf_scale is None
                    out = output[:num_decode_tokens]

                # NVFP4 trtllm kernel only supports FP8 output.
                # Use a pre-allocated FP8 buffer and dequantize afterwards.
                needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
                if needs_fp8_out:
                    out = self._nvfp4_fp8_out[:num_decode_tokens]

                if num_decode_tokens % attn_metadata.num_decodes != 0:
                    # This gets triggered when the dummy_run forces
                    # attention to be initialized with q_len = 0
                    q_len_per_req = 1
                else:
                    q_len_per_req = num_decode_tokens // attn_metadata.num_decodes

                if decode_with_xqa and q_len_per_req > 1:
                    raise NotImplementedError(
                        "FlashInfer XQA speculative decode is not wired in vLLM yet."
                    )

                # XQA decode can use model-dtype Q with FP8 KV, so only include
                # q_scale when the decode query is actually FP8.
                bmm1_scale = (
                    self.get_xqa_bmm1_scale(layer, attn_metadata.q_data_type_decode)
                    if decode_with_xqa
                    else self.bmm1_scale
                )

                lse = None
                if use_dcp:
                    out = torch.empty(
                        decode_query.shape,
                        dtype=output.dtype,
                        device=decode_query.device,
                    )
                    lse = torch.empty(
                        (decode_query.size(0), decode_query.size(1)),
                        dtype=torch.float32,
                        device=decode_query.device,
                    )

                trtllm_batch_decode_with_kv_cache(
                    query=decode_query,
                    kv_cache=(
                        nvfp4_kv_data if self.is_kvcache_nvfp4 else kv_cache_tuple
                    ),
                    workspace_buffer=workspace_buffer,
                    block_tables=block_tables_decode,
                    seq_lens=seq_lens_decode,
                    max_seq_len=attn_metadata.decode.max_seq_len,
                    bmm1_scale=bmm1_scale,
                    bmm2_scale=self.bmm2_scale,
                    window_left=self.window_left,
                    sinks=self.sinks,
                    o_sf_scale=self.o_sf_scale,
                    out=out,
                    kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
                    backend=attn_metadata.decode.kernel.value,
                    q_len_per_req=q_len_per_req,
                    kv_cache_sf=(
                        nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None
                    ),
                    lse=lse,
                    return_lse=self.need_to_return_lse_for_decode,
                )

                if use_dcp:
                    assert isinstance(out, torch.Tensor)
                    assert lse is not None
                    output[:num_decode_tokens] = self.dcp_combine(
                        out,
                        lse,
                        get_dcp_group(),
                    )
                elif needs_fp8_out:
                    output[:num_decode_tokens].copy_(out.to(output.dtype))
        return output_padded

    def do_kv_cache_update(
        self,
        layer: torch.nn.Module,
        key: torch.Tensor,
        value: torch.Tensor,
        kv_cache: torch.Tensor,
        slot_mapping: torch.Tensor,
    ) -> None:
        if self.kv_sharing_target_layer_name is None:
            # 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 self.is_kvcache_nvfp4:
                # (B, 2*H, N, full_dim) -> ((B, N, H, full_dim),
                #                            (B, N, H, full_dim));
                # K heads first, then V heads.
                k_cache, v_cache = kv_cache.transpose(1, 2).split(
                    self.num_kv_heads, dim=-2
                )
            else:
                # (B, H, N, 2*hs) -> ((B, N, H, hs), (B, N, H, hs))
                k_cache, v_cache = kv_cache.transpose(1, 2).split(
                    self.head_size, dim=-1
                )
            torch.ops._C_cache_ops.reshape_and_cache_flash(
                key,
                value,
                k_cache,
                v_cache,
                slot_mapping,
                self.cache_dtype,
                layer._k_scale,
                layer._v_scale,
            )

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

Forward pass with FlashInfer.

Parameters:

  • query

    (Tensor) –

    shape = [num_tokens, num_heads, head_size]

  • key

    (Tensor) –

    shape = [num_tokens, num_kv_heads, head_size]

  • value

    (Tensor) –

    shape = [num_tokens, num_kv_heads, head_size]

  • kv_cache

    (Tensor) –

    [num_blocks, num_kv_heads, block_size, 2*head_size]

  • attn_metadata

    (FlashInferMetadata) –

    Metadata for attention.

Returns: shape = [num_tokens, num_heads * head_size]

Source code in vllm/v1/attention/backends/flashinfer.py
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
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
def forward(
    self,
    layer: torch.nn.Module,
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    kv_cache: torch.Tensor,
    attn_metadata: FlashInferMetadata,
    output: torch.Tensor,
    output_scale: torch.Tensor | None = None,
    output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
    """Forward pass with FlashInfer.

    Args:
        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: [num_blocks, num_kv_heads, block_size, 2*head_size]
        attn_metadata: Metadata for attention.
    Returns:
        shape = [num_tokens, num_heads * head_size]
    """
    if attn_metadata is None:
        # Profiling run.
        return output.fill_(0)

    if self.bmm1_scale is None:
        self.bmm1_scale = self.scale
        if is_quantized_kv_cache(self.kv_cache_dtype):
            self.bmm1_scale *= layer._q_scale_float * layer._k_scale_float

    if self.bmm2_scale is None:
        self.bmm2_scale = 1.0
        if is_quantized_kv_cache(self.kv_cache_dtype):
            self.bmm2_scale *= layer._v_scale_float

    prefill_use_trtllm = isinstance(attn_metadata.prefill, TRTLLMPrefill)
    decode_kernel = (
        attn_metadata.decode.kernel
        if isinstance(attn_metadata.decode, FlashInferTrtllmAPIDecode)
        else None
    )
    decode_with_xqa = decode_kernel == FlashInferDecodeKernel.XQA
    decode_with_trtllm_gen = decode_kernel == FlashInferDecodeKernel.TRTLLM_GEN
    decode_with_flashinfer_trtllm_api = decode_with_xqa or decode_with_trtllm_gen

    # The attn+quant fusion happens when output_scale is provided.
    if output_scale is None:
        assert output_block_scale is None, (
            "output_block_scale is not supported when fusion has not happened"
        )
    else:
        assert attn_metadata.q_data_type_prefill == FP8_DTYPE, (
            "Query must be FP8 when attn+quant fusion happened for prefill."
        )
        assert attn_metadata.q_data_type_decode == FP8_DTYPE, (
            "Query must be FP8 when attn+quant fusion happened for decode."
        )
        assert (attn_metadata.num_prefills == 0 or prefill_use_trtllm) and (
            attn_metadata.num_decodes == 0 or decode_with_trtllm_gen
        ), "Output quant fusion requires TRTLLM prefill/trtllm-gen decode"

        if output.dtype == FP8_DTYPE:
            assert output_block_scale is None, (
                "output_block_scale should not be provided for fp8 output"
            )
        elif output.dtype == FP4_DTYPE:
            assert output_block_scale is not None, (
                "output_block_scale is required for nvfp4 output"
            )
        else:
            raise ValueError(f"Unsupported output dtype: {output.dtype}")

        # TRTLLM attn kernel requires to scale to pass as a host scalar,
        # store the o scale as a host scalar in warmup run with cuda graph
        # not enabled
        if layer._o_scale_float is None:
            layer._o_scale_float = output_scale.cpu().item()
            if output.dtype == FP8_DTYPE:
                self.bmm2_scale = self.bmm2_scale / layer._o_scale_float
            elif output.dtype == FP4_DTYPE:
                self.o_sf_scale = layer._o_scale_float

    # 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

    # FlashInfer treats uint8 KV cache as NVFP4. vLLM stores FP8 KV cache
    # as uint8 bytes, so pass FP8 caches with their logical dtype.
    if not self.is_kvcache_nvfp4 and kv_cache.dtype == torch.uint8:
        fp8_view_dtype = None
        if self.kv_cache_dtype in ("fp8", "fp8_e4m3", torch.float8_e4m3fn):
            fp8_view_dtype = torch.float8_e4m3fn
        elif self.kv_cache_dtype in ("fp8_e5m2", torch.float8_e5m2):
            fp8_view_dtype = torch.float8_e5m2
        if fp8_view_dtype is not None:
            kv_cache = kv_cache.view(fp8_view_dtype)

    # Inputs and outputs may be padded for CUDA graphs
    query = query[:num_actual_tokens]
    key = key[:num_actual_tokens]
    value = value[:num_actual_tokens]
    output_padded = output
    output = output[:num_actual_tokens]

    if attn_metadata.use_cascade:
        # Cascade attention (rare case).
        assert attn_metadata.cascade_wrapper is not None
        stride_order = self.kv_cache_layout.layer_view_order
        if self.is_kvcache_nvfp4:
            kv_cache_views = tuple(
                cache.permute(*stride_order)
                for cache in kv_cache.split(self.num_kv_heads, dim=1)
            )
        else:
            kv_perm = kv_cache.permute(*stride_order)
            kv_cache_views = kv_perm.split(self.head_size, dim=-1)
        kv_tuple = tuple(
            canonicalize_singleton_dim_strides(cache) for cache in kv_cache_views
        )
        output.copy_(attn_metadata.cascade_wrapper.run(query, kv_tuple))
        return output

    # When using spec decoding, num_decodes can be < num_decode_tokens
    # because some decode requests may have more than one query token.
    num_decode_tokens = attn_metadata.num_decode_tokens
    num_prefill_tokens = attn_metadata.num_prefill_tokens

    stride_order = self.kv_cache_layout.layer_view_order
    kv_cache_permute = kv_cache.permute(*stride_order)  # HND and contiguous
    # Fix degenerate strides on any size-1 dimension (e.g. num_kv_heads=1
    # with TP=8).  PyTorch permits non-canonical strides on size-1 dims;
    # CUDA TMA requires ≥16-byte alignment on all non-outermost strides.
    # canonicalize_singleton_dim_strides patches metadata via as_strided —
    # zero-copy.  See vllm.utils.torch_utils.
    fixed = canonicalize_singleton_dim_strides(kv_cache_permute)
    if fixed is not kv_cache_permute:
        logger.debug(
            "Canonicalized degenerate KV cache strides (FlashInfer): "
            "shape=%s, strides before=%s, strides after=%s",
            kv_cache_permute.shape,
            kv_cache_permute.stride(),
            fixed.stride(),
        )
    kv_cache_permute = fixed

    # Split K/V — zero-copy views. NVFP4 stores K/V as separate head
    # groups; other dtypes pack K/V in the content dim.
    hs = self.head_size
    nvfp4_kv_data = None
    nvfp4_kv_block_scales = None
    if self.is_kvcache_nvfp4:
        k_cache, v_cache = kv_cache.split(self.num_kv_heads, dim=1)
        kv_cache_tuple = (
            canonicalize_singleton_dim_strides(k_cache.permute(*stride_order)),
            canonicalize_singleton_dim_strides(v_cache.permute(*stride_order)),
        )
        k_data, k_sf = nvfp4_split_data_scale(kv_cache_tuple[0])
        v_data, v_sf = nvfp4_split_data_scale(kv_cache_tuple[1])
        nvfp4_kv_data = (k_data, v_data)
        nvfp4_kv_block_scales = (k_sf, v_sf)
    else:
        kv_cache_tuple = kv_cache_permute.split(hs, dim=-1)

    use_dcp = self.dcp_world_size > 1
    decode_with_dedicated_xqa = (
        decode_with_xqa and current_platform.is_device_capability_family(120)
    )
    if decode_with_dedicated_xqa:
        assert not use_dcp
        assert not self.is_kvcache_nvfp4
        assert self.o_sf_scale is None
        assert output.dtype != FP4_DTYPE

    # Regular attention (common case).
    # Decodes are at the front and prefills are at the back.
    if num_prefill_tokens > 0:
        prefill_query = query[num_decode_tokens:]
        assert prefill_query.shape[0] == num_prefill_tokens

        # Convert query to the expected dtype for prefill if needed.
        prefill_query = self.maybe_quant_query(
            prefill_query,
            attn_metadata.q_data_type_prefill,
            layer._q_scale,
        )

        if not prefill_use_trtllm:
            assert isinstance(attn_metadata.prefill, FIPrefill)
            prefill_wrapper = attn_metadata.prefill.wrapper
            assert prefill_wrapper is not None
            if use_dcp:
                assert isinstance(prefill_wrapper, BatchDCPPrefillWrapper)
                assert prefill_wrapper._context._window_left == self.window_left
                assert prefill_wrapper._context._logits_soft_cap == (
                    self.logits_soft_cap or 0.0
                )
                assert prefill_wrapper._context._sm_scale == self.scale
                assert not prefill_wrapper._context._causal
                assert prefill_wrapper._new_tokens._window_left == self.window_left
                assert prefill_wrapper._new_tokens._logits_soft_cap == (
                    self.logits_soft_cap or 0.0
                )
                assert prefill_wrapper._new_tokens._sm_scale == self.scale
                assert prefill_wrapper._new_tokens._causal

                prefill_wrapper.run(
                    layer,
                    prefill_query,
                    kv_cache_tuple,
                    key[num_decode_tokens:],
                    value[num_decode_tokens:],
                    out=output[num_decode_tokens:],
                )
            else:
                assert isinstance(
                    prefill_wrapper, BatchPrefillWithPagedKVCacheWrapper
                )
                assert prefill_wrapper._window_left == self.window_left
                assert prefill_wrapper._logits_soft_cap == (
                    self.logits_soft_cap or 0.0
                )
                assert prefill_wrapper._sm_scale == self.scale
                assert prefill_wrapper._causal == attn_metadata.causal

                if self.is_kvcache_nvfp4:
                    kv_cache_for_fi = nvfp4_kv_data
                else:
                    kv_cache_for_fi = kv_cache_tuple
                kv_cache_sf = (
                    nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None
                )

                # NVFP4 trtllm kernel only supports FP8 output.
                # Use a pre-allocated FP8 buffer and dequantize
                # afterwards.
                needs_fp8_out_prefill = (
                    self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
                )
                if needs_fp8_out_prefill:
                    out_prefill = self._nvfp4_fp8_out[:num_prefill_tokens]
                else:
                    out_prefill = output[num_decode_tokens:]

                if isinstance(
                    prefill_wrapper, BatchAttentionWithAttentionSinkWrapper
                ):
                    assert self.sinks is not None
                    prefill_wrapper.run(
                        prefill_query,
                        kv_cache_for_fi,
                        self.sinks,
                        self.scale * layer._q_scale_float * layer._k_scale_float,
                        v_scale=layer._v_scale_float,
                        out=out_prefill,
                    )
                else:
                    prefill_wrapper.run(
                        prefill_query,
                        kv_cache_for_fi,
                        q_scale=layer._q_scale_float,
                        k_scale=layer._k_scale_float,
                        v_scale=layer._v_scale_float,
                        out=out_prefill,
                        kv_cache_sf=kv_cache_sf,
                    )

                if needs_fp8_out_prefill:
                    output[
                        num_decode_tokens : num_decode_tokens + num_prefill_tokens
                    ].copy_(out_prefill.to(output.dtype))
        else:
            assert isinstance(attn_metadata.prefill, TRTLLMPrefill)
            # prefill_query may be non-contiguous or have degenerate strides
            # on size=1 dims. contiguous() ensures memory layout; then
            # canonicalize_singleton_dim_strides fixes any remaining
            # degenerate strides on size=1 dims for TMA alignment.
            prefill_query = prefill_query.contiguous()
            prefill_query = canonicalize_singleton_dim_strides(prefill_query)
            workspace_buffer = _get_trtllm_workspace_buffer()
            block_tables_prefill = attn_metadata.prefill.block_tables
            seq_lens_prefill = attn_metadata.prefill.seq_lens

            # This path needs to be enabled with VLLM_KV_CACHE_LAYOUT = HND
            assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
            assert is_strictly_contiguous(prefill_query)
            assert is_strictly_contiguous(workspace_buffer)
            assert is_strictly_contiguous(block_tables_prefill)
            assert is_strictly_contiguous(seq_lens_prefill)

            if output.dtype == FP4_DTYPE:
                assert self.o_sf_scale is not None
                out = FP4Tensor(
                    data=output[num_decode_tokens:],
                    scale=output_block_scale,
                    scale_start_index=num_decode_tokens,
                    original_shape=prefill_query.shape,
                )
            else:
                assert self.o_sf_scale is None
                out = output[num_decode_tokens:]

            # NVFP4 trtllm kernel only supports FP8 output.
            # Use a pre-allocated FP8 buffer and dequantize afterwards.
            needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
            if needs_fp8_out:
                out = self._nvfp4_fp8_out[:num_prefill_tokens]

            prefill_kv_block_scales = None
            if self.is_kvcache_nvfp4:
                # NVFP4 trtllm-gen kernel requires FP8 query.
                assert attn_metadata.q_data_type_prefill == FP8_DTYPE, (
                    "NVFP4 KV cache requires FP8 quantized queries for "
                    "trtllm-gen prefill. Set "
                    "disable_flashinfer_q_quantization=False."
                )
                mock_kv_cache = nvfp4_kv_data
                mock_block_table = block_tables_prefill
                prefill_kv_block_scales = nvfp4_kv_block_scales
            elif (
                attn_metadata.q_data_type_prefill != FP8_DTYPE
                and self.kv_cache_dtype.startswith("fp8")
            ):
                # TRTLLM prefill attention does not support BF16 Q
                # and fp8 kv cache. So to enable prefill attention
                # with fp8 kv cache, we can construct a mock block
                # and mock kv cache with BF16 KV involved in the prefill.
                kv_cache_permute = canonicalize_singleton_dim_strides(
                    kv_cache_permute
                )
                kv_strides = kv_cache_permute.stride()
                assert (
                    kv_strides[-1] == 1
                    and kv_strides[-2] == kv_cache_permute.shape[-1]
                ), (
                    "KV cache inner dims (block_size, head_size) must be "
                    f"contiguous, got strides {kv_strides}"
                )
                # fp8 uses (B, H, N, 2*hs); reshape to (B, 2, H, N, hs)
                # for the dequant kernel — zero-copy view. The dequant
                # kernel handles the interleaved K/V block stride.
                B_kv, H_kv, N_kv = kv_cache_permute.shape[:3]
                kv_cache_5d = kv_cache_permute.view(B_kv, H_kv, N_kv, 2, hs)
                kv_cache_5d = kv_cache_5d.permute(0, 3, 1, 2, 4)
                mock_kv_cache, mock_block_table = trtllm_prefill_attn_kvfp8_dequant(
                    kv_cache_5d,
                    block_tables_prefill,
                    layer._k_scale,
                    layer._v_scale,
                    attn_metadata.q_data_type_prefill,
                )
            else:
                mock_kv_cache = kv_cache_tuple
                mock_block_table = block_tables_prefill

            trtllm_batch_context_with_kv_cache(
                query=prefill_query,
                kv_cache=mock_kv_cache,
                workspace_buffer=workspace_buffer,
                block_tables=mock_block_table,
                seq_lens=seq_lens_prefill,
                max_q_len=attn_metadata.prefill.max_q_len,
                max_kv_len=attn_metadata.prefill.max_seq_len,
                bmm1_scale=self.bmm1_scale,
                bmm2_scale=self.bmm2_scale,
                batch_size=attn_metadata.num_prefills,
                cum_seq_lens_q=attn_metadata.prefill.cum_seq_lens_q,
                cum_seq_lens_kv=attn_metadata.prefill.cum_seq_lens_kv,
                window_left=self.window_left,
                sinks=self.sinks,
                o_sf_scale=self.o_sf_scale,
                out=out,
                kv_cache_sf=prefill_kv_block_scales,
            )

            if needs_fp8_out:
                output[
                    num_decode_tokens : num_decode_tokens + num_prefill_tokens
                ].copy_(out[:num_prefill_tokens].to(output.dtype))

    if num_decode_tokens > 0:
        decode_query = query[:num_decode_tokens]
        assert decode_query.shape[0] == num_decode_tokens

        # Convert query to the expected dtype for decode if needed.
        decode_query = self.maybe_quant_query(
            decode_query,
            attn_metadata.q_data_type_decode,
            layer._q_scale,
        )

        if not decode_with_flashinfer_trtllm_api:
            assert isinstance(attn_metadata.decode, FIDecode)
            decode_wrapper = attn_metadata.decode.wrapper
            assert decode_wrapper is not None
            assert decode_wrapper._window_left == self.window_left
            assert decode_wrapper._logits_soft_cap == (self.logits_soft_cap or 0.0)
            assert decode_wrapper._sm_scale == self.scale

            if self.is_kvcache_nvfp4:
                kv_cache_for_fi = nvfp4_kv_data
            else:
                kv_cache_for_fi = kv_cache_tuple
            kv_cache_sf = nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None

            # NVFP4 kernel only supports FP8 output.
            # Use a pre-allocated FP8 buffer and dequantize afterwards.
            needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
            if needs_fp8_out:
                out_decode = self._nvfp4_fp8_out[:num_decode_tokens]
            else:
                out_decode = output[:num_decode_tokens]

            if use_dcp:
                decode_query = get_dcp_group().all_gather(
                    decode_query.contiguous(), dim=-2
                )
                output_tmp = torch.empty_like(decode_query)
                lse = torch.empty(
                    (decode_query.size(0), decode_query.size(1)),
                    dtype=torch.float32,
                    device=decode_query.device,
                )
                decode_wrapper.run(
                    decode_query,
                    kv_cache_for_fi,
                    q_scale=layer._q_scale_float,
                    k_scale=layer._k_scale_float,
                    v_scale=layer._v_scale_float,
                    out=output_tmp,
                    lse=lse,
                    return_lse=True,
                    kv_cache_sf=kv_cache_sf,
                    sinks=self.sinks,
                )
                output[:num_decode_tokens] = self.dcp_combine(
                    output_tmp,
                    lse,
                    get_dcp_group(),
                )
            else:
                decode_wrapper.run(
                    decode_query,
                    kv_cache_for_fi,
                    q_scale=layer._q_scale_float,
                    k_scale=layer._k_scale_float,
                    v_scale=layer._v_scale_float,
                    out=out_decode,
                    kv_cache_sf=kv_cache_sf,
                    sinks=self.sinks,
                )

            if needs_fp8_out:
                output[:num_decode_tokens].copy_(out_decode.to(output.dtype))
        else:
            assert isinstance(attn_metadata.decode, FlashInferTrtllmAPIDecode)
            # decode_query may be non-contiguous or have degenerate strides
            # on size=1 dims. contiguous() ensures memory layout; then
            # canonicalize_singleton_dim_strides fixes any remaining
            # degenerate strides on size=1 dims for TMA alignment.
            decode_query = decode_query.contiguous()
            decode_query = canonicalize_singleton_dim_strides(decode_query)
            workspace_buffer = _get_trtllm_workspace_buffer()
            block_tables_decode = attn_metadata.decode.block_tables
            seq_lens_decode = attn_metadata.decode.seq_lens

            # trtllm-gen needs HND layout on SM100. XQA is selected
            # separately on SM90 and does not use this SM100 layout gate.
            if decode_with_trtllm_gen:
                assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
            else:
                assert decode_with_xqa
            assert is_strictly_contiguous(decode_query)
            assert is_strictly_contiguous(workspace_buffer)
            assert is_strictly_contiguous(block_tables_decode)
            assert is_strictly_contiguous(seq_lens_decode)
            kv_cache_permute = canonicalize_singleton_dim_strides(kv_cache_permute)
            kv_strides = kv_cache_permute.stride()
            assert (
                kv_strides[-1] == 1 and kv_strides[-2] == kv_cache_permute.shape[-1]
            ), (
                "KV cache inner dims (block_size, head_size) must be "
                f"contiguous, got strides {kv_strides}"
            )

            if use_dcp:
                assert decode_with_trtllm_gen
                if output.dtype == FP4_DTYPE:
                    raise NotImplementedError(
                        "DCP decode with FlashInfer trtllm-gen does not support "
                        "FP4 attention output yet."
                    )
                decode_query = get_dcp_group().all_gather(
                    decode_query.contiguous(), dim=-2
                )
                decode_query = canonicalize_singleton_dim_strides(decode_query)

            if decode_with_dedicated_xqa:
                bmm1_scale = self.get_xqa_bmm1_scale(
                    layer, attn_metadata.q_data_type_decode
                )
                q_len_per_req = attn_metadata.decode.q_len_per_req

                flashinfer_xqa_batch_decode_with_kv_cache(
                    query=decode_query,
                    kv_cache=kv_cache_tuple,
                    workspace_buffer=workspace_buffer,
                    block_tables=block_tables_decode,
                    seq_lens=seq_lens_decode,
                    max_seq_len=attn_metadata.decode.max_seq_len,
                    bmm1_scale=bmm1_scale,
                    bmm2_scale=self.bmm2_scale,
                    window_left=self.window_left,
                    out=output[:num_decode_tokens],
                    sinks=self.sinks,
                    kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
                    q_len_per_req=q_len_per_req,
                    mask=attn_metadata.decode.mask,
                    q_cu_seq_lens=attn_metadata.decode.q_cu_seq_lens,
                )
                return output_padded

            if output.dtype == FP4_DTYPE:
                assert self.o_sf_scale is not None
                out = FP4Tensor(
                    data=output[:num_decode_tokens],
                    scale=output_block_scale,
                    scale_start_index=0,
                    original_shape=decode_query.shape,
                )
            else:
                assert self.o_sf_scale is None
                out = output[:num_decode_tokens]

            # NVFP4 trtllm kernel only supports FP8 output.
            # Use a pre-allocated FP8 buffer and dequantize afterwards.
            needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
            if needs_fp8_out:
                out = self._nvfp4_fp8_out[:num_decode_tokens]

            if num_decode_tokens % attn_metadata.num_decodes != 0:
                # This gets triggered when the dummy_run forces
                # attention to be initialized with q_len = 0
                q_len_per_req = 1
            else:
                q_len_per_req = num_decode_tokens // attn_metadata.num_decodes

            if decode_with_xqa and q_len_per_req > 1:
                raise NotImplementedError(
                    "FlashInfer XQA speculative decode is not wired in vLLM yet."
                )

            # XQA decode can use model-dtype Q with FP8 KV, so only include
            # q_scale when the decode query is actually FP8.
            bmm1_scale = (
                self.get_xqa_bmm1_scale(layer, attn_metadata.q_data_type_decode)
                if decode_with_xqa
                else self.bmm1_scale
            )

            lse = None
            if use_dcp:
                out = torch.empty(
                    decode_query.shape,
                    dtype=output.dtype,
                    device=decode_query.device,
                )
                lse = torch.empty(
                    (decode_query.size(0), decode_query.size(1)),
                    dtype=torch.float32,
                    device=decode_query.device,
                )

            trtllm_batch_decode_with_kv_cache(
                query=decode_query,
                kv_cache=(
                    nvfp4_kv_data if self.is_kvcache_nvfp4 else kv_cache_tuple
                ),
                workspace_buffer=workspace_buffer,
                block_tables=block_tables_decode,
                seq_lens=seq_lens_decode,
                max_seq_len=attn_metadata.decode.max_seq_len,
                bmm1_scale=bmm1_scale,
                bmm2_scale=self.bmm2_scale,
                window_left=self.window_left,
                sinks=self.sinks,
                o_sf_scale=self.o_sf_scale,
                out=out,
                kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
                backend=attn_metadata.decode.kernel.value,
                q_len_per_req=q_len_per_req,
                kv_cache_sf=(
                    nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None
                ),
                lse=lse,
                return_lse=self.need_to_return_lse_for_decode,
            )

            if use_dcp:
                assert isinstance(out, torch.Tensor)
                assert lse is not None
                output[:num_decode_tokens] = self.dcp_combine(
                    out,
                    lse,
                    get_dcp_group(),
                )
            elif needs_fp8_out:
                output[:num_decode_tokens].copy_(out.to(output.dtype))
    return output_padded

FlashInferMetadata dataclass

Attributes:

Source code in vllm/v1/attention/backends/flashinfer.py
@dataclass
class FlashInferMetadata:
    num_actual_tokens: int
    """Total number of tokens in the batch (excluding padding)."""

    slot_mapping: torch.Tensor
    """Tensor for writing K/V to the cache. Shape: [num_actual_tokens]"""

    # The data types of the query for prefill and decode.
    # On SM90, these two data types may be different.
    q_data_type_prefill: torch.dtype
    q_data_type_decode: torch.dtype

    num_decodes: int
    num_decode_tokens: int
    num_prefills: int
    num_prefill_tokens: int
    causal: bool

    prefill: FIPrefill | TRTLLMPrefill | None
    """
    Holds the metadata for the prefill portion of the batch.
    Will be `None` if `num_prefill_tokens == 0`.
    """

    decode: FIDecode | FlashInferTrtllmAPIDecode | None
    """
    Holds the metadata for the decode portion of the batch.
    Will be `None` if `num_decode_tokens == 0`.
    """

    # --- Special Case: Cascade Attention ---

    use_cascade: bool
    """
    If True, the entire batch is a cascade attention call, and the
    `prefill` and `decode` fields will both be None.
    """

    cascade_wrapper: MultiLevelCascadeAttentionWrapper | None

decode instance-attribute

Holds the metadata for the decode portion of the batch. Will be None if num_decode_tokens == 0.

num_actual_tokens instance-attribute

Total number of tokens in the batch (excluding padding).

prefill instance-attribute

Holds the metadata for the prefill portion of the batch. Will be None if num_prefill_tokens == 0.

slot_mapping instance-attribute

Tensor for writing K/V to the cache. Shape: [num_actual_tokens]

use_cascade instance-attribute

If True, the entire batch is a cascade attention call, and the prefill and decode fields will both be None.

FlashInferMetadataBuilder

Bases: AttentionMetadataBuilder[FlashInferMetadata]

Methods:

Source code in vllm/v1/attention/backends/flashinfer.py
 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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
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
class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
    kv_cache_spec: AttentionSpec
    reorder_batch_threshold: int = 1

    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.cache_config = vllm_config.cache_config
        self.model_config = vllm_config.model_config
        self.attention_config = vllm_config.attention_config
        self._workspace_buffer = None
        self._prefill_wrapper: (
            BatchPrefillWithPagedKVCacheWrapper | BatchDCPPrefillWrapper | None
        ) = None  # Wrapper for prefill/append
        self._noncausal_prefill_wrapper: BatchPrefillWithPagedKVCacheWrapper | None = (
            None  # Wrapper for non-causal prefill (DFlash)
        )
        self._decode_wrapper = None  # Wrapper for decode (general shape)

        if envs.VLLM_BATCH_INVARIANT:
            self.decode_fixed_split_size = 2048
            self.prefill_fixed_split_size = 4096
            self.disable_split_kv = True
        else:
            self.decode_fixed_split_size = -1
            self.prefill_fixed_split_size = -1
            self.disable_split_kv = False

        self.compilation_config = vllm_config.compilation_config
        self.max_num_batched_tokens = (
            vllm_config.scheduler_config.max_num_batched_tokens
        )
        max_num_pages_per_req = cdiv(
            self.model_config.max_model_len, self.kv_cache_spec.block_size
        )
        max_num_reqs = vllm_config.scheduler_config.max_num_seqs
        self.max_num_reqs = max_num_reqs
        max_num_pages = max_num_reqs * max_num_pages_per_req
        # Persistent uniform masks keep stable addresses for CUDA graphs.
        self._decode_mask_cache: dict[tuple[int, bool], torch.Tensor] = {}
        speculative_config = vllm_config.speculative_config
        num_spec_tokens = (
            speculative_config.num_speculative_tokens
            if speculative_config is not None
            else 0
        )
        self.enable_cuda_graph = (
            self.compilation_config.cudagraph_mode.decode_mode() == CUDAGraphMode.FULL
        )
        if self.enable_cuda_graph:
            # For full cudagraph capture, one `decode_wrapper` for each batch
            # size is needed for FlashInfer.
            self._decode_wrappers_cudagraph: dict[
                int, BatchDecodeWithPagedKVCacheWrapper
            ] = {}
            self._decode_cudagraph_max_bs = (1 + num_spec_tokens) * max_num_reqs
            if self.compilation_config.max_cudagraph_capture_size is not None:
                self._decode_cudagraph_max_bs = min(
                    self._decode_cudagraph_max_bs,
                    self.compilation_config.max_cudagraph_capture_size,
                )
        try:
            self.dcp_world_size = get_dcp_group().world_size
            self.dcp_rank = get_dcp_group().rank_in_group
            self.dcp_kv_cache_interleave_size = (
                vllm_config.parallel_config.dcp_kv_cache_interleave_size
            )
        except AssertionError:
            # DCP might not be initialized in testing
            self.dcp_world_size = 1
            self.dcp_rank = 0
            self.dcp_kv_cache_interleave_size = 1
        self.use_dcp = self.dcp_world_size > 1
        self.dcp_a2a = (
            self.use_dcp and vllm_config.parallel_config.dcp_comm_backend == "a2a"
        )

        # Compatible with models with non-uniform per-layer head counts.
        self.num_qo_heads = get_num_attention_heads_from_layers(
            vllm_config, layer_names
        ) or self.model_config.get_num_attention_heads(self.vllm_config.parallel_config)

        self.num_kv_heads = self.kv_cache_spec.num_kv_heads
        self.head_dim = self.kv_cache_spec.head_size
        self.page_size = self.kv_cache_spec.block_size

        if self.kv_cache_spec.kv_quant_mode != KVQuantMode.NONE:
            self.cache_dtype = self.cache_config.cache_dtype
            # Cannot use self.kv_cache_spec.dtype here because kv_cache_spec
            # storage dtype may not be the same as the op dtype (uint8 vs fp8_e4m3)
            self.is_kvcache_nvfp4 = self.cache_dtype.startswith("nvfp4")
            if self.is_kvcache_nvfp4:
                if (
                    force_use_trtllm_attention() is False
                    or not supports_trtllm_attention(is_prefill=True)
                    or not supports_trtllm_attention(is_prefill=False)
                ):
                    raise ValueError(
                        f"--kv-cache-dtype {self.cache_dtype} requires the "
                        "SM100 trtllm-gen "
                        "FlashInfer path."
                    )
                # The scale search only affects the store kernel. FlashInfer
                # reads both variants using the same NVFP4 layout.
                self.kv_cache_dtype = "nvfp4"
            else:
                self.kv_cache_dtype = FlashInferBackend.get_dtype_for_flashinfer(
                    self.cache_dtype
                )
        else:
            self.cache_dtype = "auto"
            self.is_kvcache_nvfp4 = False
            assert self.kv_cache_spec.dtype == self.model_config.dtype
            self.kv_cache_dtype = self.kv_cache_spec.dtype

        # Compute per-phase Q dtype.  On SM90 (XQA decode), the prefill and
        # decode phases require different Q dtypes when the KV cache is FP8
        # (FP8-Q for the FI native prefill, BF16/FP16-Q for XQA decode),
        # so both values must be tracked independently.
        self.q_data_type_prefill = self.get_q_data_type(is_prefill=True)
        self.q_data_type_decode = self.get_q_data_type(is_prefill=False)

        # Prefer TRTLLM/XQA for decoding whenever supported. The decode kernel
        # must be selected statically for FULL cudagraph capture.
        can_use_xqa_or_trtllm_gen_decode = can_use_trtllm_attention(
            self.num_qo_heads, self.num_kv_heads, is_prefill=False
        )
        # Page sizes >= 128 require the trtllm-gen GQA/MQA path (guaranteed by
        # get_supported_kernel_block_sizes).
        assert self.page_size <= 64 or (
            current_platform.is_device_capability_family(100)
            and can_use_xqa_or_trtllm_gen_decode
            and self.num_qo_heads // self.num_kv_heads > 1
        ), f"Unexpected FlashInfer page size {self.page_size} without trtllm-gen GQA"
        self.use_trtllm_decode_attention = can_use_xqa_or_trtllm_gen_decode
        self.flashinfer_trtllm_api_decode_kernel: FlashInferDecodeKernel | None = (
            self._get_flashinfer_trtllm_api_decode_kernel()
            if can_use_xqa_or_trtllm_gen_decode
            else None
        )
        # The dedicated FlashInfer XQA API accepts head dimensions in
        # [16, 256] that are divisible by 16. Some hybrid-attention models
        # (for example Gemma 4) use XQA-compatible sliding-attention groups
        # alongside global-attention groups with head_dim=512. Resolve the
        # backend per KV-cache group so the eligible groups still use XQA and
        # the wider groups fall back to native FlashInfer decode.
        if (
            self.flashinfer_trtllm_api_decode_kernel == FlashInferDecodeKernel.XQA
            and not (16 <= self.head_dim <= 256 and self.head_dim % 16 == 0)
        ):
            logger.warning_once(
                "FlashInfer XQA decode does not support head_dim=%d; "
                "reverting this KV-cache group to native FlashInfer decode.",
                self.head_dim,
            )
            self.use_trtllm_decode_attention = False
            self.flashinfer_trtllm_api_decode_kernel = None
        if (
            self.use_dcp
            and self.flashinfer_trtllm_api_decode_kernel == FlashInferDecodeKernel.XQA
        ):
            logger.warning_once(
                "FlashInfer XQA decode does not support returning LSE and "
                "therefore does not support DCP, reverting to native FlashInfer "
                "decode."
            )
            self.use_trtllm_decode_attention = False
            self.flashinfer_trtllm_api_decode_kernel = None
        self.use_dedicated_xqa = (
            current_platform.is_device_capability_family(120)
            and self.flashinfer_trtllm_api_decode_kernel == FlashInferDecodeKernel.XQA
        )
        supports_spec_as_decode = (
            self.flashinfer_trtllm_api_decode_kernel
            == FlashInferDecodeKernel.TRTLLM_GEN
            or self.use_dedicated_xqa
        )
        self._init_reorder_batch_threshold(
            1,
            supports_spec_as_decode=supports_spec_as_decode,
            # trtllm-gen decode receives no cp_rank/global-seq-len information,
            # so its end-aligned causal mask is wrong for q_len > 1 over the
            # DCP-interleaved local KV shard (spec token i misses up to
            # (dcp_world_size - 1) * (q_len - 1 - i) KV entries, including its
            # own). Keep the threshold at 1 under DCP so spec queries take the
            # DCP-aware prefill path, until the kernel is CP-aware (compare
            # flash_attn_varlen_func's cp_world_size/cp_rank/cp_tot_seqused_k).
            supports_dcp_with_varlen=False,
        )

        self._cascade_wrapper = None  # Wrapper for cascade attention

        # Global hyperparameters shared by all attention layers
        # TODO: discard this for trtllm-gen backend
        per_layer_parameters = get_per_layer_parameters(
            vllm_config, layer_names, FlashInferImpl
        )
        if current_platform.is_device_capability(90) and any(
            params.window_left != -1 for params in per_layer_parameters.values()
        ):
            # FlashInfer SM90 sliding-window prefill is not reliable with FP8-Q:
            # https://github.com/flashinfer-ai/flashinfer/issues/3578
            raise NotImplementedError(
                "FlashInfer backend on SM90 currently crashes with "
                "sliding-window attention layers. Use the default attention "
                "backend."
            )
        self.global_hyperparameters = infer_global_hyperparameters(per_layer_parameters)
        self.sm_scale = self.global_hyperparameters.sm_scale
        self.window_left = self.global_hyperparameters.window_left
        self.logits_soft_cap = self.global_hyperparameters.logits_soft_cap
        self.has_sinks = self.global_hyperparameters.has_sinks
        if self.has_sinks and not FlashInferBackend.supports_sink():
            raise NotImplementedError(
                "FlashInfer backend currently does not support attention "
                "sinks, please use trtllm on blackwell or flash attention on "
                "earlier GPUs."
            )
        capability = current_platform.get_device_capability()
        arch = f"sm{capability.major}{capability.minor}" if capability else "unknown"
        decode_backend = (
            self.flashinfer_trtllm_api_decode_kernel.value
            if self.flashinfer_trtllm_api_decode_kernel is not None
            else "flashinfer-native"
        )
        logger.info_once(
            "FlashInfer resolved query dtypes: prefill=%s, decode=%s, "
            "decode_backend=%s, kv_cache_dtype=%s, arch=%s",
            self.q_data_type_prefill,
            self.q_data_type_decode,
            decode_backend,
            self.kv_cache_dtype,
            arch,
        )
        # Preparing persistent buffers
        # Since we do not have explicit synchronization in ModelRunnerV2, we do not pin
        # reused CPU buffers to avoid a race condition between step N async copies to
        # GPU and step N+1 buffer updates.
        self.pin_memory = not vllm_config.use_v2_model_runner and PIN_MEMORY
        self.paged_kv_indptr = self._make_buffer(max_num_reqs + 1)
        self.paged_kv_indptr_cpu_buffer = torch.zeros_like(
            self.paged_kv_indptr.cpu, pin_memory=self.pin_memory
        )  # Extra buffer for mutable paged_kv_indptr.cpu in cuda graph mode
        self.paged_kv_indices = self._make_buffer(max_num_pages)
        self.paged_kv_last_page_len = self._make_buffer(max_num_reqs)

    @property
    def kv_cache_layout(self) -> KVCacheLayout:
        return self.cache_config.get_resolved_kv_cache_layout()

    # Keep SM90 prefill/decode Q dtype selection in one place.
    def get_q_data_type(self, is_prefill: bool) -> torch.dtype:
        # The user sets --attention-config.disable_flashinfer_q_quantization
        # to 1 explicitly, use model dtype for query.
        if self.vllm_config.attention_config.disable_flashinfer_q_quantization:
            return self.model_config.dtype

        # self.cache_dtype is resolved per KV-cache group: it is "auto" when
        # this group is unquantized (e.g. --kv-cache-dtype-skip-layers), even
        # if cache_config requests a quantized dtype globally.
        cache_dtype = self.cache_dtype

        # XQA decode requires BF16/FP16-Q even with FP8 KV cache.
        if (
            (
                current_platform.is_device_capability(90)
                or current_platform.is_device_capability_family(120)
            )
            and not is_prefill
            and force_use_trtllm_attention() is not False
            and cache_dtype.startswith("fp8")
        ):
            return self.model_config.dtype

        # Otherwise, match Q dtype to the KV cache dtype.
        if cache_dtype.startswith("fp8"):
            # FP8-Q requires an fp8 tensor-core attention path.
            # Architectures with only fa2 (e.g. SM89, SM120) cannot
            # consume FP8 queries, so keep the model dtype for Q there.
            if current_platform.is_device_capability(
                90
            ) or current_platform.is_device_capability_family(100):
                return FlashInferBackend.get_dtype_for_flashinfer(cache_dtype)
            return self.model_config.dtype
        if cache_dtype.startswith("nvfp4"):
            return FlashInferBackend.get_dtype_for_flashinfer("fp8_e4m3")
        return self.kv_cache_spec.dtype

    def _make_buffer(
        self, *size: int | torch.SymInt, dtype: torch.dtype = torch.int32
    ) -> CpuGpuBuffer:
        return CpuGpuBuffer(
            *size,
            dtype=dtype,
            device=self.device,
            pin_memory=self.pin_memory,
            with_numpy=True,
        )

    @override  # type: ignore[misc]
    @classmethod
    def get_cudagraph_support(
        cls: type["FlashInferMetadataBuilder"],
        vllm_config: VllmConfig,
        kv_cache_spec: KVCacheSpec,
    ) -> AttentionCGSupport:
        """Get the cudagraph support level for FlashInfer attention.

        SM90 XQA supports only single-token decode. SM12x uses the dedicated
        XQA API, which supports speculative and non-causal decode.
        """
        if current_platform.is_device_capability(90):
            return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE

        is_sm12x = current_platform.is_device_capability_family(120)
        # XQA does not return LSE and therefore does not support DCP.
        if is_sm12x and vllm_config.parallel_config.decode_context_parallel_size > 1:
            return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE

        kv_specs = iter_layer_specs(kv_cache_spec)
        num_qo_heads = vllm_config.model_config.get_num_attention_heads(
            vllm_config.parallel_config
        )
        has_trtllm_support: bool = len(kv_specs) > 0
        for spec in kv_specs:
            if not isinstance(spec, AttentionSpec):
                # FlashInfer only applies to attention, so we don't consider other types
                # of KV spec (e.g. Mamba) here. This is mostly for type checking.
                continue
            if not can_use_trtllm_attention(
                num_qo_heads=num_qo_heads,
                num_kv_heads=spec.num_kv_heads,
                is_prefill=False,
            ):
                has_trtllm_support = False
                break

        if has_trtllm_support and (
            is_sm12x or not vllm_config.attention_config.use_non_causal
        ):
            return AttentionCGSupport.UNIFORM_BATCH
        else:
            return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE

    def _get_workspace_buffer(self):
        if self._workspace_buffer is None:
            buffer_size = envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE
            if envs.VLLM_BATCH_INVARIANT:
                buffer_size = FLASHINFER_WORKSPACE_BUFFER_SIZE_BATCH_INVARIANT
            else:
                # FlashInfer prefill temp buffers (batch_prefill_tmp_v, ...)
                # scale with the prefill chunk and query-head footprint, NOT
                # context length. The fixed ~394 MiB default is too small for
                # wide-head models at the default 8192-token chunk on some
                # archs (e.g. sm_120), where FlashInfer hard-errors instead of
                # growing. Size to the batch's head footprint; never shrink
                # below the configured default.
                est = (
                    self.max_num_batched_tokens
                    * self.num_qo_heads
                    * self.head_dim
                    * FLASHINFER_PREFILL_WORKSPACE_BYTES_PER_ELEM
                )
                buffer_size = max(buffer_size, est)
            self._workspace_buffer = torch.zeros(
                buffer_size, dtype=torch.uint8, device=self.device
            )
        return self._workspace_buffer

    def set_workspace_buffer(self, workspace_buffer: torch.Tensor):
        self._workspace_buffer = workspace_buffer

    @staticmethod
    def _get_flashinfer_trtllm_api_decode_kernel() -> FlashInferDecodeKernel:
        if current_platform.is_device_capability(
            90
        ) or current_platform.is_device_capability_family(120):
            return FlashInferDecodeKernel.XQA
        assert current_platform.is_device_capability_family(100)
        return FlashInferDecodeKernel.TRTLLM_GEN

    def _compute_decode_query_lens(
        self,
        qo_indptr: torch.Tensor,
        qo_indptr_cpu: torch.Tensor,
        num_decodes: int,
        num_decode_tokens: int,
    ) -> tuple[int, torch.Tensor | None, list[int] | None]:
        """Return the query width, ragged offsets, and effective query lengths."""
        assert self.use_dedicated_xqa
        if num_decodes == 0 or num_decode_tokens == 0:
            return 1, None, None

        decode_q_lens = qo_indptr_cpu[1 : num_decodes + 1] - qo_indptr_cpu[:num_decodes]
        nonzero = decode_q_lens[decode_q_lens > 0]
        q_len_per_req = int(nonzero.max().item()) if nonzero.numel() > 0 else 1
        uniform = nonzero.numel() <= 1 or bool((nonzero == nonzero[0]).all().item())
        if uniform and num_decode_tokens == num_decodes * q_len_per_req:
            return q_len_per_req, None, None

        if q_len_per_req <= 1:
            return 1, None, None

        q_lens = decode_q_lens.tolist()
        return (
            q_len_per_req,
            qo_indptr[: num_decodes + 1],
            q_lens,
        )

    def _get_decode_mask(
        self,
        q_len_per_req: int,
        ragged_q_lens: list[int] | None,
        num_decodes: int,
        causal: bool,
    ) -> torch.Tensor | None:
        """Return the packed XQA draft mask for speculative decode."""
        if q_len_per_req <= 1:
            return None

        if ragged_q_lens is None:
            key = (q_len_per_req, causal)
            buf = self._decode_mask_cache.get(key)
            if buf is None:
                per_req = _make_xqa_draft_block_mask(q_len_per_req, causal, self.device)
                buf = (
                    per_req.unsqueeze(0).expand(self.max_num_reqs, -1, -1).contiguous()
                )
                self._decode_mask_cache[key] = buf
            return buf[:num_decodes]

        return _make_xqa_ragged_draft_block_mask(
            ragged_q_lens, q_len_per_req, causal, self.device
        )

    def _get_prefill_wrapper(
        self,
        causal: bool = True,
    ) -> BatchPrefillWithPagedKVCacheWrapper | BatchDCPPrefillWrapper:
        if not causal:
            if self.use_dcp:
                raise NotImplementedError(
                    "FlashInfer non-causal prefill is not supported with DCP yet."
                )
            if self.is_kvcache_nvfp4:
                raise NotImplementedError(
                    "FlashInfer non-causal attention is not supported with "
                    "NVFP4 KV cache."
                )
            if self._noncausal_prefill_wrapper is None:
                if self.has_sinks and current_platform.is_device_capability_family(120):
                    self._noncausal_prefill_wrapper = (
                        BatchAttentionWithAttentionSinkWrapper(
                            self._get_workspace_buffer(),
                            get_flashinfer_layout_string(self.kv_cache_layout),
                            backend="auto",
                            q_data_type=self.q_data_type_prefill,
                            kv_data_type=self.kv_cache_dtype,
                            head_dim_qk=self.head_dim,
                            head_dim_vo=self.head_dim,
                            window_left=self.window_left,
                        )
                    )
                else:
                    self._noncausal_prefill_wrapper = (
                        BatchPrefillWithPagedKVCacheWrapper(
                            self._get_workspace_buffer(),
                            get_flashinfer_layout_string(self.kv_cache_layout),
                            backend="auto",
                        )
                    )
            return self._noncausal_prefill_wrapper

        if self._prefill_wrapper is None:
            if self.use_dcp:
                self._prefill_wrapper = BatchDCPPrefillWrapper(
                    kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
                    workspace_buffer=self._get_workspace_buffer(),
                    dcp_a2a=self.dcp_a2a,
                )
            else:
                if self.has_sinks and current_platform.is_device_capability_family(120):
                    assert not self.is_kvcache_nvfp4
                    self._prefill_wrapper = BatchAttentionWithAttentionSinkWrapper(
                        self._get_workspace_buffer(),
                        get_flashinfer_layout_string(self.kv_cache_layout),
                        backend="auto",
                        q_data_type=self.q_data_type_prefill,
                        kv_data_type=self.kv_cache_dtype,
                        head_dim_qk=self.head_dim,
                        head_dim_vo=self.head_dim,
                        window_left=self.window_left,
                    )
                else:
                    # NVFP4 KV cache requires the trtllm-gen backend inside
                    # the wrapper; fa2/fa3 do not support nvfp4.
                    backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
                    self._prefill_wrapper = BatchPrefillWithPagedKVCacheWrapper(
                        self._get_workspace_buffer(),
                        get_flashinfer_layout_string(self.kv_cache_layout),
                        backend=backend,
                    )
        assert self._prefill_wrapper is not None
        return self._prefill_wrapper

    def _get_decode_wrapper(self, batch_size: int, use_cudagraph: bool = False):
        if use_cudagraph:
            decode_wrapper = self._decode_wrappers_cudagraph.get(batch_size, None)
        else:
            decode_wrapper = self._decode_wrapper

        if decode_wrapper is None:
            if use_cudagraph:
                paged_kv_indptr = self.paged_kv_indptr.gpu[: batch_size + 1]
                paged_kv_indices = self.paged_kv_indices.gpu
                paged_kv_last_page_len = self.paged_kv_last_page_len.gpu[:batch_size]
            else:
                paged_kv_indptr = None
                paged_kv_indices = None
                paged_kv_last_page_len = None
            # NVFP4 KV cache requires the trtllm-gen backend inside
            # the wrapper; fa2/fa3 do not support nvfp4.
            backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
            decode_wrapper = BatchDecodeWithPagedKVCacheWrapper(
                self._get_workspace_buffer(),
                get_flashinfer_layout_string(self.kv_cache_layout),
                use_cuda_graph=use_cudagraph,
                paged_kv_indptr_buffer=paged_kv_indptr,
                paged_kv_indices_buffer=paged_kv_indices,
                paged_kv_last_page_len_buffer=paged_kv_last_page_len,
                # Tensor cores are enabled by default because the perf would be
                # at least as good as cuda cores for all attention ops in latest
                # gpus.
                use_tensor_cores=True,
                backend=backend,
            )

            # save the decode wrapper
            if use_cudagraph:
                self._decode_wrappers_cudagraph[batch_size] = decode_wrapper
            else:
                self._decode_wrapper = decode_wrapper

        return decode_wrapper

    def _get_cascade_wrapper(self):
        if self._cascade_wrapper is None:
            self._cascade_wrapper = MultiLevelCascadeAttentionWrapper(
                2,
                self._get_workspace_buffer(),
                get_flashinfer_layout_string(self.kv_cache_layout),
            )
        return self._cascade_wrapper

    def _compute_flashinfer_kv_metadata(
        self,
        num_blocks_np: np.ndarray,
        seq_lens_np: np.ndarray,
        block_table_tensor: torch.Tensor,
        num_reqs: int,
        page_size: int,
    ) -> torch.Tensor:
        """
        Compute paged_kv_indptr, paged_kv_indices, paged_kv_last_page_len for FlashInfer
        attention.

        Results are stored in self.paged_kv_indptr,
        self.paged_kv_indices, self.paged_kv_last_page_len buffers.

        Returns paged_kv_indices, a GPU tensor with shape [num_actual_pages].
        """
        # write self.paged_kv_indptr_cpu inplace (0-index is always 0)
        np.cumsum(
            num_blocks_np,
            dtype=np.int32,
            out=self.paged_kv_indptr.np[1 : num_reqs + 1],
        )
        # NOTE(woosuk): Because self.paged_kv_indptr_cpu can be modified
        # after this line (e.g., for cuda graphs), we need to copy the data to
        # self.paged_kv_indptr_buffer to avoid race condition.
        self.paged_kv_indptr_cpu_buffer[: num_reqs + 1] = self.paged_kv_indptr.cpu[
            : num_reqs + 1
        ]
        paged_kv_indptr = self.paged_kv_indptr.gpu[: num_reqs + 1]
        paged_kv_indptr.copy_(
            self.paged_kv_indptr_cpu_buffer[: num_reqs + 1], non_blocking=True
        )

        # write self.paged_kv_indices inplace
        num_actual_pages = self.paged_kv_indptr.np[num_reqs]
        paged_kv_indices = self.paged_kv_indices.gpu[:num_actual_pages]
        _copy_page_indices_kernel[(num_reqs,)](
            paged_kv_indices,
            block_table_tensor,
            block_table_tensor.stride(0),
            paged_kv_indptr,
            BLOCK_SIZE=1024,
        )

        # write self.paged_kv_last_page_len_cpu inplace
        paged_kv_last_page_len_np = seq_lens_np % page_size
        self.paged_kv_last_page_len.np[:num_reqs] = np.where(
            (paged_kv_last_page_len_np == 0) & (seq_lens_np != 0),
            page_size,
            paged_kv_last_page_len_np,
        )
        self.paged_kv_last_page_len.gpu[:num_reqs].copy_(
            self.paged_kv_last_page_len.cpu[:num_reqs], non_blocking=True
        )
        return paged_kv_indices

    def build(
        self,
        common_prefix_len: int,
        common_attn_metadata: CommonAttentionMetadata,
        fast_build: bool = False,
    ) -> FlashInferMetadata:
        num_reqs = common_attn_metadata.num_reqs
        num_actual_tokens = common_attn_metadata.num_actual_tokens
        causal = common_attn_metadata.causal
        route_decode = causal or self.use_dedicated_xqa
        if route_decode:
            num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
                split_decodes_and_prefills(
                    common_attn_metadata,
                    decode_threshold=self.reorder_batch_threshold,
                    require_uniform=not self.use_dedicated_xqa,
                )
            )
        else:
            num_decodes = 0
            num_prefills = num_reqs
            num_decode_tokens = 0
            num_prefill_tokens = num_actual_tokens

        page_size = self.page_size
        max_seq_len = common_attn_metadata.max_seq_len
        seq_lens = common_attn_metadata.seq_lens
        block_table_tensor = common_attn_metadata.block_table_tensor
        qo_indptr = common_attn_metadata.query_start_loc
        qo_indptr_cpu = common_attn_metadata.query_start_loc_cpu

        # Step 1: Decide which dispatch modes to use:
        # - Cascade attention (distinct mode)
        # - Prefill (FI native or TRTLLM)
        # - Decode (FI native, XQA, or trtllm-gen)
        use_cascade = common_prefix_len > 0
        uses_spec_reorder = self.reorder_batch_threshold > 1
        # Page sizes >= 128 must use trtllm-gen; force it for prefill too.
        prefill_force_trtllm = (
            True if page_size >= 128 else self.attention_config.use_trtllm_attention
        )
        prefill_use_trtllm = causal and use_trtllm_attention(
            self.num_qo_heads,
            self.num_kv_heads,
            num_prefill_tokens,
            max_seq_len,
            self.dcp_world_size,
            self.cache_dtype,
            self.q_data_type_prefill,
            is_prefill=True,
            force_use_trtllm=prefill_force_trtllm,
            has_sinks=self.has_sinks,
            has_spec=uses_spec_reorder,
        )
        decode_with_flashinfer_trtllm_api = self.use_trtllm_decode_attention and (
            causal or self.use_dedicated_xqa
        )

        if not causal and self.use_dcp:
            raise NotImplementedError(
                "FlashInfer non-causal prefill is not supported with DCP yet."
            )
        if not causal and self.use_trtllm_decode_attention:
            logger.warning_once(
                "Using FlashInfer for draft model non-causal attention; TRTLLM "
                "can still be used for target model causal attention."
            )
        all_uses_trtllm = causal and (
            (num_prefills == 0 or prefill_use_trtllm)
            and (num_decodes == 0 or decode_with_flashinfer_trtllm_api)
        )

        if not all_uses_trtllm:
            if self.has_sinks and (
                not self.use_dedicated_xqa or self.use_dcp or use_cascade
            ):
                raise NotImplementedError(
                    "FlashInfer backend currently does not support attention "
                    "sinks, please use trtllm on blackwell or flash attention "
                    "on earlier GPUs."
                )

            if not self.global_hyperparameters.has_same_window_lefts:
                raise ValueError(
                    "Window left is not the same for all layers. "
                    "One potential fix is to set disable_sliding_window=True"
                )

            assert self.global_hyperparameters.has_same_all_params, (
                "FlashInfer backend currently only supports models in which "
                "all layers share the same values for the following "
                "hyperparameters: `window_left`, `logits_soft_cap`, "
                "`sm_scale`."
            )

        # Step 2: Initialize the output metadata
        # Leave prefill/decode/cascade_wrapper empty, to be populated
        # case by case depending on the batch contents and backend selection.
        attn_metadata = FlashInferMetadata(
            num_actual_tokens=num_actual_tokens,
            slot_mapping=common_attn_metadata.slot_mapping,
            q_data_type_prefill=self.q_data_type_prefill,
            q_data_type_decode=self.q_data_type_decode,
            num_decodes=num_decodes,
            num_decode_tokens=num_decode_tokens,
            num_prefills=num_prefills,
            num_prefill_tokens=num_prefill_tokens,
            causal=causal,
            use_cascade=use_cascade,
            prefill=None,
            decode=None,
            cascade_wrapper=None,
        )

        # Guard access to seq_lens_cpu, which may not always be needed
        # and can be expensive to retrieve in async mode.
        # When all attention (both prefill and decode) uses TRTLLM,
        # seq_lens_cpu is not needed since TRTLLM paths use GPU tensors
        # (block_tables, seq_lens) directly.
        needs_seq_lens_cpu = self.use_dcp or use_cascade or not all_uses_trtllm
        if needs_seq_lens_cpu:
            with gpu_sync_allowed():
                seq_lens_cpu = common_attn_metadata.seq_lens_cpu
            seq_lens_np = seq_lens_cpu.numpy()
            num_blocks_np = (seq_lens_np + (page_size - 1)) // page_size
        else:
            seq_lens_cpu = None
            seq_lens_np = None
            num_blocks_np = None

        # Adjust seq_lens_cpu for DCP
        if self.use_dcp:
            assert seq_lens_cpu is not None
            if num_prefills > 0:
                qo_indptr_prefill_cpu = (
                    qo_indptr_cpu[num_decodes:] - qo_indptr_cpu[num_decodes]
                )
                query_lens_prefill_cpu = (
                    qo_indptr_prefill_cpu[1:] - qo_indptr_prefill_cpu[:-1]
                )
                seq_lens_cpu[num_decodes:] = (
                    seq_lens_cpu[num_decodes:] - query_lens_prefill_cpu
                )

            seq_lens_cpu = get_dcp_local_seq_lens(
                seq_lens_cpu,
                self.dcp_world_size,
                self.dcp_rank,
                self.dcp_kv_cache_interleave_size,
            )

        # Adjust num_block_np for cascade attention
        if use_cascade:
            assert num_blocks_np is not None
            assert common_prefix_len % page_size == 0
            num_common_kv_blocks = common_prefix_len // page_size
            num_blocks_np -= num_common_kv_blocks

        # Compute paged_kv_indices if necessary
        # paged_kv_indices is only needed for FlashInfer native paths;
        # XQA/trtllm-gen paths use block_tables directly on GPU.
        needs_native_paged_prefill = num_prefills > 0 and not prefill_use_trtllm
        needs_native_paged_decode = (
            num_decodes > 0 and not decode_with_flashinfer_trtllm_api
        )
        needs_paged_kv_indices = (
            use_cascade or needs_native_paged_prefill or needs_native_paged_decode
        )
        if needs_paged_kv_indices:
            assert num_blocks_np is not None
            assert seq_lens_np is not None
            paged_kv_indices = self._compute_flashinfer_kv_metadata(
                num_blocks_np,
                seq_lens_np,
                block_table_tensor,
                num_reqs,
                page_size,
            )
        else:
            paged_kv_indices = None

        # Early-out for cascade attention
        if use_cascade:
            assert num_blocks_np is not None
            # Grab the blocks of the shared prefix from the first request.
            num_common_kv_blocks = common_prefix_len // page_size

            # Create CPU versions directly for cascade (no GPU versions needed)
            shared_qo_indptr_cpu = torch.tensor(
                [0, num_actual_tokens], dtype=torch.int32, device="cpu"
            )
            shared_kv_page_indptr_cpu = torch.tensor(
                [0, num_common_kv_blocks], dtype=torch.int32, device="cpu"
            )
            shared_kv_page_indices_cpu = block_table_tensor[0, :num_common_kv_blocks]
            shared_kv_last_page_len_cpu = torch.tensor(
                [page_size], dtype=torch.int32, device="cpu"
            )

            # Remove the blocks of the shared prefix from all requests.
            block_table_tensor = block_table_tensor[:, num_common_kv_blocks:]
            num_blocks_np -= num_common_kv_blocks

            assert paged_kv_indices is not None
            paged_kv_indptr_cpu = self.paged_kv_indptr.cpu[: 1 + num_reqs]
            paged_kv_last_page_len_cpu = self.paged_kv_last_page_len.cpu[:num_reqs]

            attn_metadata.cascade_wrapper = self._get_cascade_wrapper()
            # Cascade attention must use the same q dtype for prefill and decode
            # because it does not support FP8 kv-cache or FP8 query yet.
            assert self.q_data_type_prefill == self.q_data_type_decode
            attn_metadata.cascade_wrapper.plan(
                qo_indptr_arr=[shared_qo_indptr_cpu, qo_indptr_cpu],
                paged_kv_indptr_arr=[shared_kv_page_indptr_cpu, paged_kv_indptr_cpu],
                paged_kv_indices_arr=[shared_kv_page_indices_cpu, paged_kv_indices],
                paged_kv_last_page_len=[
                    shared_kv_last_page_len_cpu,
                    paged_kv_last_page_len_cpu,
                ],
                num_qo_heads=self.num_qo_heads,
                num_kv_heads=self.num_kv_heads,
                head_dim=self.head_dim,
                page_size=self.page_size,
                causal=True,
                sm_scale=self.sm_scale,
                window_left=self.window_left,
                logits_soft_cap=self.logits_soft_cap,
                q_data_type=self.q_data_type_prefill,
                kv_data_type=self.kv_cache_dtype,
            )
            return attn_metadata

        # Step 3: Handle prefill and decode pathways case by case
        ## PREFILL PATHWAY
        if num_prefills > 0:
            # Slices for shared prefill metadata
            prefill_start = num_decodes
            qo_indptr_prefill_cpu = (
                qo_indptr_cpu[prefill_start:] - qo_indptr_cpu[prefill_start]
            )
            assert qo_indptr_prefill_cpu.shape[0] == num_prefills + 1

            if prefill_use_trtllm:
                # TRTLLM prefill has no cross-rank combine for DCP-sharded KV;
                # use_trtllm_attention never selects it when DCP is enabled.
                assert not self.use_dcp
                # Create GPU versions
                qo_indptr_prefill_gpu = (
                    qo_indptr[prefill_start:] - qo_indptr[prefill_start]
                )
                # Compute cum_seq_lens_kv on GPU to avoid CPU sync.
                # This is the cumulative sum of the number of KV cache
                # blocks per prefill request.
                prefill_seq_lens = seq_lens[prefill_start:]
                num_blocks_per_req = (prefill_seq_lens + page_size - 1) // page_size
                paged_kv_indptr_prefill_gpu = self.paged_kv_indptr.gpu[
                    prefill_start : num_reqs + 1
                ]
                # Assign to slice to avoid cpu sync.
                paged_kv_indptr_prefill_gpu[:1] = 0
                torch.cumsum(
                    num_blocks_per_req,
                    dim=0,
                    out=paged_kv_indptr_prefill_gpu[1:],
                )
                # Compute max_q_len for prefill requests
                query_lens_prefill_cpu = (
                    qo_indptr_prefill_cpu[1:] - qo_indptr_prefill_cpu[:-1]
                )
                max_q_len_prefill = int(query_lens_prefill_cpu.max().item())
                attn_metadata.prefill = TRTLLMPrefill(
                    block_tables=block_table_tensor[prefill_start:],
                    seq_lens=prefill_seq_lens,
                    cum_seq_lens_q=qo_indptr_prefill_gpu,
                    cum_seq_lens_kv=paged_kv_indptr_prefill_gpu,
                    max_q_len=max_q_len_prefill,
                    max_seq_len=max_seq_len,
                )
            else:
                prefill_wrapper = self._get_prefill_wrapper(causal=attn_metadata.causal)
                # Slicing CPU buffers that are only needed for FI native prefills
                paged_kv_last_page_len_prefill_cpu = self.paged_kv_last_page_len.cpu[
                    prefill_start:num_reqs
                ]
                assert paged_kv_last_page_len_prefill_cpu.shape[0] == num_prefills
                paged_kv_indptr_prefill_cpu = self.paged_kv_indptr.cpu[
                    prefill_start : num_reqs + 1
                ]
                assert paged_kv_indptr_prefill_cpu.shape[0] == num_prefills + 1
                if self.use_dcp:
                    assert isinstance(prefill_wrapper, BatchDCPPrefillWrapper)
                    prefill_wrapper.plan(
                        qo_indptr_cpu=qo_indptr_prefill_cpu,
                        paged_kv_indptr_cpu=paged_kv_indptr_prefill_cpu,
                        paged_kv_indices=paged_kv_indices,
                        paged_kv_last_page_len_cpu=paged_kv_last_page_len_prefill_cpu,
                        page_size=self.page_size,
                        num_qo_heads=self.num_qo_heads,
                        dcp_world_size=self.dcp_world_size,
                        num_kv_heads=self.num_kv_heads,
                        head_dim=self.head_dim,
                        sm_scale=self.sm_scale,
                        window_left=self.window_left,
                        logits_soft_cap=self.logits_soft_cap,
                        q_data_type=self.q_data_type_prefill,
                        kv_cache_dtype=self.kv_cache_dtype,
                        prefill_fixed_split_size=self.prefill_fixed_split_size,
                        disable_split_kv=self.disable_split_kv,
                    )
                else:
                    assert isinstance(
                        prefill_wrapper,
                        BatchPrefillWithPagedKVCacheWrapper,
                    )
                    # NVFP4 trtllm kernel only supports FP8 output;
                    # use FP8 o_data_type so the wrapper matches the
                    # FP8 output buffer allocated in forward().
                    o_dtype = (
                        FP8_DTYPE if self.is_kvcache_nvfp4 else self.model_config.dtype
                    )
                    prefill_wrapper.plan(
                        qo_indptr=qo_indptr_prefill_cpu,
                        paged_kv_indptr=paged_kv_indptr_prefill_cpu,
                        paged_kv_indices=paged_kv_indices,
                        paged_kv_last_page_len=paged_kv_last_page_len_prefill_cpu,
                        num_qo_heads=self.num_qo_heads,
                        num_kv_heads=self.num_kv_heads,
                        head_dim_qk=self.head_dim,
                        page_size=self.page_size,
                        causal=attn_metadata.causal,
                        sm_scale=self.sm_scale,
                        window_left=self.window_left,
                        logits_soft_cap=self.logits_soft_cap,
                        q_data_type=self.q_data_type_prefill,
                        kv_data_type=self.kv_cache_dtype,
                        o_data_type=o_dtype,
                        fixed_split_size=self.prefill_fixed_split_size,
                        disable_split_kv=self.disable_split_kv,
                    )
                attn_metadata.prefill = FIPrefill(wrapper=prefill_wrapper)

        ## DECODE PATHWAY
        if num_decodes > 0:
            if decode_with_flashinfer_trtllm_api:
                assert self.flashinfer_trtllm_api_decode_kernel is not None
                if not self.use_dedicated_xqa:
                    assert num_decode_tokens % num_decodes == 0, (
                        "XQA/trtllm-gen decode requires uniform query lengths "
                        f"per request. Got {num_decode_tokens=} and {num_decodes=}."
                    )
                seq_lens_decode = seq_lens[:num_decodes]
                if self.use_dcp:
                    assert common_attn_metadata.dcp_local_seq_lens is not None
                    seq_lens_decode = common_attn_metadata.dcp_local_seq_lens[
                        :num_decodes
                    ]
                q_len_per_req = 1
                q_cu_seq_lens = None
                decode_mask = None
                if self.use_dedicated_xqa:
                    q_len_per_req, q_cu_seq_lens, ragged_q_lens = (
                        self._compute_decode_query_lens(
                            qo_indptr,
                            qo_indptr_cpu,
                            num_decodes,
                            num_decode_tokens,
                        )
                    )
                    decode_mask = self._get_decode_mask(
                        q_len_per_req,
                        ragged_q_lens,
                        num_decodes,
                        bool(causal),
                    )
                attn_metadata.decode = FlashInferTrtllmAPIDecode(
                    kernel=self.flashinfer_trtllm_api_decode_kernel,
                    block_tables=block_table_tensor[:num_decodes],
                    seq_lens=seq_lens_decode,
                    max_seq_len=max_seq_len,
                    q_len_per_req=q_len_per_req,
                    q_cu_seq_lens=q_cu_seq_lens,
                    mask=decode_mask,
                )
            else:
                assert seq_lens_cpu is not None
                pure_decode = num_prefills == 0
                use_cudagraph = (
                    self.enable_cuda_graph
                    and pure_decode
                    and num_decode_tokens <= self._decode_cudagraph_max_bs
                )
                num_input_tokens = num_decode_tokens

                decode_wrapper = self._get_decode_wrapper(
                    num_input_tokens, use_cudagraph
                )
                # Use the persistent buffer with padding length,
                # instead of the same address but chunked version
                # in atten_metadata when using cudagraph.
                # NVFP4 trtllm kernel only supports FP8 output;
                # use FP8 o_data_type so the wrapper matches the
                # FP8 output buffer allocated in forward().
                o_dtype = (
                    FP8_DTYPE if self.is_kvcache_nvfp4 else self.model_config.dtype
                )
                fast_plan_decode(
                    decode_wrapper,
                    indptr_cpu=self.paged_kv_indptr.cpu[: num_input_tokens + 1],
                    indices=paged_kv_indices,
                    last_page_len_cpu=self.paged_kv_last_page_len.cpu[
                        :num_input_tokens
                    ],
                    num_qo_heads=self.num_qo_heads * self.dcp_world_size,
                    num_kv_heads=self.num_kv_heads,
                    head_dim=self.head_dim,
                    page_size=self.page_size,
                    # Disable flashinfer's pos encoding and use vllm's rope.
                    pos_encoding_mode="NONE",
                    sm_scale=self.sm_scale,
                    window_left=self.window_left,
                    logits_soft_cap=self.logits_soft_cap,
                    q_data_type=self.q_data_type_decode,
                    kv_data_type=self.kv_cache_dtype,
                    o_data_type=o_dtype,
                    fixed_split_size=self.decode_fixed_split_size,
                    disable_split_kv=self.disable_split_kv,
                )
                attn_metadata.decode = FIDecode(wrapper=decode_wrapper)
        return attn_metadata

    def use_cascade_attention(self, *args, **kwargs) -> bool:
        if self.kv_cache_spec.dtype != self.vllm_config.model_config.dtype:
            # TODO: The cascade wrapper currently does not support setting
            # kv cache dtype to something different from query dtype.
            return False
        # TODO: Cascade attention doesn't work, disable it for now
        # return use_cascade_attention(*args, **kwargs)
        return False

_compute_decode_query_lens(qo_indptr, qo_indptr_cpu, num_decodes, num_decode_tokens)

Return the query width, ragged offsets, and effective query lengths.

Source code in vllm/v1/attention/backends/flashinfer.py
def _compute_decode_query_lens(
    self,
    qo_indptr: torch.Tensor,
    qo_indptr_cpu: torch.Tensor,
    num_decodes: int,
    num_decode_tokens: int,
) -> tuple[int, torch.Tensor | None, list[int] | None]:
    """Return the query width, ragged offsets, and effective query lengths."""
    assert self.use_dedicated_xqa
    if num_decodes == 0 or num_decode_tokens == 0:
        return 1, None, None

    decode_q_lens = qo_indptr_cpu[1 : num_decodes + 1] - qo_indptr_cpu[:num_decodes]
    nonzero = decode_q_lens[decode_q_lens > 0]
    q_len_per_req = int(nonzero.max().item()) if nonzero.numel() > 0 else 1
    uniform = nonzero.numel() <= 1 or bool((nonzero == nonzero[0]).all().item())
    if uniform and num_decode_tokens == num_decodes * q_len_per_req:
        return q_len_per_req, None, None

    if q_len_per_req <= 1:
        return 1, None, None

    q_lens = decode_q_lens.tolist()
    return (
        q_len_per_req,
        qo_indptr[: num_decodes + 1],
        q_lens,
    )

_compute_flashinfer_kv_metadata(num_blocks_np, seq_lens_np, block_table_tensor, num_reqs, page_size)

Compute paged_kv_indptr, paged_kv_indices, paged_kv_last_page_len for FlashInfer attention.

Results are stored in self.paged_kv_indptr, self.paged_kv_indices, self.paged_kv_last_page_len buffers.

Returns paged_kv_indices, a GPU tensor with shape [num_actual_pages].

Source code in vllm/v1/attention/backends/flashinfer.py
def _compute_flashinfer_kv_metadata(
    self,
    num_blocks_np: np.ndarray,
    seq_lens_np: np.ndarray,
    block_table_tensor: torch.Tensor,
    num_reqs: int,
    page_size: int,
) -> torch.Tensor:
    """
    Compute paged_kv_indptr, paged_kv_indices, paged_kv_last_page_len for FlashInfer
    attention.

    Results are stored in self.paged_kv_indptr,
    self.paged_kv_indices, self.paged_kv_last_page_len buffers.

    Returns paged_kv_indices, a GPU tensor with shape [num_actual_pages].
    """
    # write self.paged_kv_indptr_cpu inplace (0-index is always 0)
    np.cumsum(
        num_blocks_np,
        dtype=np.int32,
        out=self.paged_kv_indptr.np[1 : num_reqs + 1],
    )
    # NOTE(woosuk): Because self.paged_kv_indptr_cpu can be modified
    # after this line (e.g., for cuda graphs), we need to copy the data to
    # self.paged_kv_indptr_buffer to avoid race condition.
    self.paged_kv_indptr_cpu_buffer[: num_reqs + 1] = self.paged_kv_indptr.cpu[
        : num_reqs + 1
    ]
    paged_kv_indptr = self.paged_kv_indptr.gpu[: num_reqs + 1]
    paged_kv_indptr.copy_(
        self.paged_kv_indptr_cpu_buffer[: num_reqs + 1], non_blocking=True
    )

    # write self.paged_kv_indices inplace
    num_actual_pages = self.paged_kv_indptr.np[num_reqs]
    paged_kv_indices = self.paged_kv_indices.gpu[:num_actual_pages]
    _copy_page_indices_kernel[(num_reqs,)](
        paged_kv_indices,
        block_table_tensor,
        block_table_tensor.stride(0),
        paged_kv_indptr,
        BLOCK_SIZE=1024,
    )

    # write self.paged_kv_last_page_len_cpu inplace
    paged_kv_last_page_len_np = seq_lens_np % page_size
    self.paged_kv_last_page_len.np[:num_reqs] = np.where(
        (paged_kv_last_page_len_np == 0) & (seq_lens_np != 0),
        page_size,
        paged_kv_last_page_len_np,
    )
    self.paged_kv_last_page_len.gpu[:num_reqs].copy_(
        self.paged_kv_last_page_len.cpu[:num_reqs], non_blocking=True
    )
    return paged_kv_indices

_get_decode_mask(q_len_per_req, ragged_q_lens, num_decodes, causal)

Return the packed XQA draft mask for speculative decode.

Source code in vllm/v1/attention/backends/flashinfer.py
def _get_decode_mask(
    self,
    q_len_per_req: int,
    ragged_q_lens: list[int] | None,
    num_decodes: int,
    causal: bool,
) -> torch.Tensor | None:
    """Return the packed XQA draft mask for speculative decode."""
    if q_len_per_req <= 1:
        return None

    if ragged_q_lens is None:
        key = (q_len_per_req, causal)
        buf = self._decode_mask_cache.get(key)
        if buf is None:
            per_req = _make_xqa_draft_block_mask(q_len_per_req, causal, self.device)
            buf = (
                per_req.unsqueeze(0).expand(self.max_num_reqs, -1, -1).contiguous()
            )
            self._decode_mask_cache[key] = buf
        return buf[:num_decodes]

    return _make_xqa_ragged_draft_block_mask(
        ragged_q_lens, q_len_per_req, causal, self.device
    )

get_cudagraph_support(vllm_config, kv_cache_spec) classmethod

Get the cudagraph support level for FlashInfer attention.

SM90 XQA supports only single-token decode. SM12x uses the dedicated XQA API, which supports speculative and non-causal decode.

Source code in vllm/v1/attention/backends/flashinfer.py
@override  # type: ignore[misc]
@classmethod
def get_cudagraph_support(
    cls: type["FlashInferMetadataBuilder"],
    vllm_config: VllmConfig,
    kv_cache_spec: KVCacheSpec,
) -> AttentionCGSupport:
    """Get the cudagraph support level for FlashInfer attention.

    SM90 XQA supports only single-token decode. SM12x uses the dedicated
    XQA API, which supports speculative and non-causal decode.
    """
    if current_platform.is_device_capability(90):
        return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE

    is_sm12x = current_platform.is_device_capability_family(120)
    # XQA does not return LSE and therefore does not support DCP.
    if is_sm12x and vllm_config.parallel_config.decode_context_parallel_size > 1:
        return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE

    kv_specs = iter_layer_specs(kv_cache_spec)
    num_qo_heads = vllm_config.model_config.get_num_attention_heads(
        vllm_config.parallel_config
    )
    has_trtllm_support: bool = len(kv_specs) > 0
    for spec in kv_specs:
        if not isinstance(spec, AttentionSpec):
            # FlashInfer only applies to attention, so we don't consider other types
            # of KV spec (e.g. Mamba) here. This is mostly for type checking.
            continue
        if not can_use_trtllm_attention(
            num_qo_heads=num_qo_heads,
            num_kv_heads=spec.num_kv_heads,
            is_prefill=False,
        ):
            has_trtllm_support = False
            break

    if has_trtllm_support and (
        is_sm12x or not vllm_config.attention_config.use_non_causal
    ):
        return AttentionCGSupport.UNIFORM_BATCH
    else:
        return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE

FlashInferTrtllmAPIDecode dataclass

Metadata for XQA and trtllm-gen decode.

Attributes:

  • block_tables (Tensor) –

    The slice of the block table tensor corresponding only to decode requests.

  • mask (Tensor | None) –

    Packed XQA draft mask.

  • max_seq_len (int) –

    The maximum sequence length for KV Cache.

  • q_cu_seq_lens (Tensor | None) –

    Cumulative query lengths for ragged XQA decode.

  • q_len_per_req (int) –

    Query tokens per request for uniform speculative decode.

  • seq_lens (Tensor) –

    The slice of the sequence lengths tensor corresponding only to decode requests.

Source code in vllm/v1/attention/backends/flashinfer.py
@dataclass
class FlashInferTrtllmAPIDecode:
    """Metadata for XQA and trtllm-gen decode."""

    kernel: FlashInferDecodeKernel

    block_tables: torch.Tensor
    """
    The slice of the block table tensor corresponding *only* to decode requests.
    Shape: [num_decodes, max_num_blocks_per_seq]
    """

    seq_lens: torch.Tensor
    """
    The slice of the sequence lengths tensor corresponding *only* to decode requests.
    Shape: [num_decodes]
    """

    max_seq_len: int
    """The maximum sequence length for KV Cache."""

    q_len_per_req: int = 1
    """Query tokens per request for uniform speculative decode."""

    q_cu_seq_lens: torch.Tensor | None = None
    """Cumulative query lengths for ragged XQA decode."""

    mask: torch.Tensor | None = None
    """Packed XQA draft mask."""

block_tables instance-attribute

The slice of the block table tensor corresponding only to decode requests. Shape: [num_decodes, max_num_blocks_per_seq]

mask = None class-attribute instance-attribute

Packed XQA draft mask.

max_seq_len instance-attribute

The maximum sequence length for KV Cache.

q_cu_seq_lens = None class-attribute instance-attribute

Cumulative query lengths for ragged XQA decode.

q_len_per_req = 1 class-attribute instance-attribute

Query tokens per request for uniform speculative decode.

seq_lens instance-attribute

The slice of the sequence lengths tensor corresponding only to decode requests. Shape: [num_decodes]

TRTLLMPrefill dataclass

Metadata for the TRTLLM prefill pathway.

Attributes:

  • block_tables (Tensor) –

    The slice of the block table tensor corresponding only to prefill requests.

  • max_q_len (int) –

    The maximum query length among prefill requests.

  • max_seq_len (int) –

    The maximum sequence length for KV Cache.

  • seq_lens (Tensor) –

    The slice of the sequence lengths tensor corresponding only to prefill requests.

Source code in vllm/v1/attention/backends/flashinfer.py
@dataclass
class TRTLLMPrefill:
    """Metadata for the TRTLLM prefill pathway."""

    block_tables: torch.Tensor
    """
    The slice of the block table tensor corresponding *only* to prefill requests.
    Shape: [num_prefills, max_num_blocks_per_seq]
    """

    seq_lens: torch.Tensor
    """
    The slice of the sequence lengths tensor corresponding *only* to prefill requests.
    Shape: [num_prefills]
    """

    cum_seq_lens_q: torch.Tensor
    cum_seq_lens_kv: torch.Tensor

    max_q_len: int
    """
    The maximum query length *among prefill requests*.
    """

    max_seq_len: int
    """The maximum sequence length for KV Cache."""

block_tables instance-attribute

The slice of the block table tensor corresponding only to prefill requests. Shape: [num_prefills, max_num_blocks_per_seq]

max_q_len instance-attribute

The maximum query length among prefill requests.

max_seq_len instance-attribute

The maximum sequence length for KV Cache.

seq_lens instance-attribute

The slice of the sequence lengths tensor corresponding only to prefill requests. Shape: [num_prefills]

_make_xqa_draft_block_mask(q_len, causal, device)

Build a packed XQA draft mask for a uniform request.

Source code in vllm/v1/attention/backends/flashinfer.py
def _make_xqa_draft_block_mask(
    q_len: int, causal: bool, device: torch.device
) -> torch.Tensor:
    """Build a packed XQA draft mask for a uniform request."""
    num_packed = (q_len + 31) // 32
    padded = num_packed * 32
    q_idx = torch.arange(q_len, device=device).unsqueeze(1)
    kv_idx = torch.arange(padded, device=device).unsqueeze(0)
    bool_mask = kv_idx <= q_idx if causal else (kv_idx < q_len).expand(q_len, padded)
    return _pack_draft_block_bool_mask(bool_mask, num_packed)

_make_xqa_ragged_draft_block_mask(q_lens, max_q_len, causal, device)

Build a packed XQA draft mask for a ragged batch.

Source code in vllm/v1/attention/backends/flashinfer.py
def _make_xqa_ragged_draft_block_mask(
    q_lens: list[int], max_q_len: int, causal: bool, device: torch.device
) -> torch.Tensor:
    """Build a packed XQA draft mask for a ragged batch."""
    num_packed = (max_q_len + 31) // 32
    padded = num_packed * 32
    q_lens_t = torch.tensor(q_lens, device=device)
    row_lens = torch.repeat_interleave(q_lens_t, q_lens_t)
    request_starts = torch.cumsum(q_lens_t, dim=0) - q_lens_t
    row_starts = torch.repeat_interleave(request_starts, q_lens_t)
    q_idx = torch.arange(sum(q_lens), device=device) - row_starts
    kv_idx = torch.arange(padded, device=device).unsqueeze(0)
    bool_mask = kv_idx < row_lens.unsqueeze(1)
    if causal:
        bool_mask &= kv_idx <= q_idx.unsqueeze(1)
    return _pack_draft_block_bool_mask(bool_mask, num_packed)

_pack_draft_block_bool_mask(bool_mask, num_packed)

Pack a boolean draft mask into XQA's uint16 layout.

Source code in vllm/v1/attention/backends/flashinfer.py
def _pack_draft_block_bool_mask(
    bool_mask: torch.Tensor, num_packed: int
) -> torch.Tensor:
    """Pack a boolean draft mask into XQA's uint16 layout."""
    num_rows = bool_mask.shape[0]
    bits = 1 << torch.arange(32, device=bool_mask.device, dtype=torch.int64)
    mask_u32 = (
        (bool_mask.view(num_rows, num_packed, 32).to(torch.int64) * bits)
        .sum(dim=-1)
        .to(torch.uint32)
    )
    return mask_u32.view(torch.uint16).reshape(num_rows, num_packed * 2)

fast_plan_decode(self, indptr_cpu, indices, last_page_len_cpu, num_qo_heads, num_kv_heads, head_dim, page_size, pos_encoding_mode='NONE', window_left=-1, logits_soft_cap=None, q_data_type='float16', kv_data_type=None, o_data_type=None, data_type=None, sm_scale=None, rope_scale=None, rope_theta=None, non_blocking=True, fixed_split_size=-1, disable_split_kv=False)

A faster version of BatchDecodeWithPagedKVCacheWrapper::plan used for cudagraph capture/replay, while the no cudagraph version turns back to the original plan. using original plan after passing host-side buffers: - only host-to-device copy of indptr and last_page_len buffers Modifications for cudagraph: - only host-to-device copy of indptr and last_page_len buffers. - avoid device-to-device copy of indices buffer.

Part of the code get inspiration from the original plan from FlashInfer repo and the implementation of fast_decode_plan for FlashInfer in SGlang repo.

Source code in vllm/v1/attention/backends/flashinfer.py
def fast_plan_decode(
    self,  # decode wrapper
    indptr_cpu: torch.Tensor,
    indices: torch.Tensor,
    last_page_len_cpu: torch.Tensor,
    num_qo_heads: int,
    num_kv_heads: int,
    head_dim: int,
    page_size: int,
    pos_encoding_mode: str = "NONE",
    window_left: int = -1,
    logits_soft_cap: float | None = None,
    q_data_type: str | torch.dtype | None = "float16",
    kv_data_type: str | torch.dtype | None = None,
    o_data_type: str | torch.dtype | None = None,
    data_type: str | torch.dtype | None = None,
    sm_scale: float | None = None,
    rope_scale: float | None = None,
    rope_theta: float | None = None,
    non_blocking: bool = True,
    fixed_split_size: int = -1,
    disable_split_kv: bool = False,
) -> None:
    """
    A faster version of BatchDecodeWithPagedKVCacheWrapper::plan used for
    cudagraph capture/replay, while the no cudagraph version turns back
    to the original plan.
    using original plan after passing host-side buffers:
    - only host-to-device copy of indptr and last_page_len buffers
    Modifications for cudagraph:
    - only host-to-device copy of indptr and last_page_len buffers.
    - avoid device-to-device copy of indices buffer.

    Part of the code get inspiration from the original plan from FlashInfer repo
    and the implementation of fast_decode_plan for FlashInfer in SGlang repo.
    """
    # Warm up with the original plan if it is first call, and always run the
    # original plan if we run for dynamic shape. For fixed shape (cudagraph),
    # this warm up is to generate the _cached_module for the decode wrapper.
    if not self.is_cuda_graph_enabled or getattr(self, "vllm_first_call", True):
        self.plan(
            indptr=indptr_cpu,
            indices=indices,
            last_page_len=last_page_len_cpu,
            num_qo_heads=num_qo_heads,
            num_kv_heads=num_kv_heads,
            head_dim=head_dim,
            page_size=page_size,
            pos_encoding_mode=pos_encoding_mode,
            window_left=window_left,
            logits_soft_cap=logits_soft_cap,
            q_data_type=q_data_type,
            kv_data_type=kv_data_type,
            o_data_type=o_data_type,
            data_type=data_type,
            sm_scale=sm_scale,
            rope_scale=rope_scale,
            rope_theta=rope_theta,
            non_blocking=non_blocking,
            block_tables=None,
            seq_lens=None,
            fixed_split_size=fixed_split_size,
            disable_split_kv=disable_split_kv,
        )
        self.vllm_first_call = False
        return

    assert self.is_cuda_graph_enabled, "Should be cudagraph only here"

    fast_decode_plan(
        self,
        indptr=indptr_cpu,
        indices=indices,
        last_page_len=last_page_len_cpu,
        num_qo_heads=num_qo_heads,
        num_kv_heads=num_kv_heads,
        head_dim=head_dim,
        page_size=page_size,
        pos_encoding_mode=pos_encoding_mode,
        window_left=window_left,
        logits_soft_cap=logits_soft_cap,
        q_data_type=q_data_type,
        kv_data_type=kv_data_type,
        data_type=data_type,
        sm_scale=sm_scale,
        rope_scale=rope_scale,
        rope_theta=rope_theta,
        non_blocking=non_blocking,
        fixed_split_size=fixed_split_size,
        disable_split_kv=disable_split_kv,
    )