flashinfer
FlashInfer — High-performance kernel library for LLM inference with optimized attention, paged KV-cache, FP8/FP4 quantization
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
メニュー
FlashInfer — High-performance kernel library for LLM inference with optimized attention, paged KV-cache, FP8/FP4 quantization
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
SOC 職業分類に基づく
Iteratively optimize cuTile kernel performance through systematic profiling, bottleneck analysis, IR comparison, and targeted tuning. Covers tile sizes, occupancy, autotune configs, TMA, latency hints, persistent scheduling, num_ctas, flush_to_zero, and IR-level debugging. Use when asked to "optimize cutile kernel", "improve kernel perf", "tune cutile performance", "make kernel faster", or iteratively benchmark and refine a cuTile GPU kernel in the TileGym project.
Integrate TileGym kernels into Hugging Face `transformers` models by replacing the library's submodule(s) and certain class(es)' implementations, and patching certain class(es)' init/forward/load weight methods prior to instantiating models. Used when the user requires integrating TileGym kernels into `transformers` models.
Use when the user wants to add, modify, debug, or review an xLLM TileLang Ascend kernel or specialization, including Python kernel definitions, generated Ascend-C source, runtime wrapper dispatch, TileLang CMake wiring, and NPU tests.
TileLang-Ascend 新增 Ascend 专属 T.tile.xxx 小 API 的端到端开发流程。用户要求新增、封装、暴露、实现或测试 ascend_tile.py 中的 T.tile API / Ascend tile primitive 时必须使用本 skill,尤其适用于需要同时打通 Python 前端、C++ lowering/codegen、Ascend C helper、文档和 CI 测试的任务。
TileLang-Ascend 算子测试设计技能。支持多种场景:(1) 从 design.md 设计测试配置 (2) 从 examples/{op}/*.py 补充测试 (3) 手动提供算子信息生成测试 (4) 测试覆盖率分析。理解算子实现逻辑后智能判断测试策略。触发:设计算子测试、生成测试用例、补充测试、测试覆盖率不足。
Generates optimized CUDA kernel code based on performance analysis reports or algorithm type. Reads NCU analysis reports (e.g. *_analysis.md) and optionally existing kernel code, then produces high-quality compilable .cu files with applied optimizations. Use when the user provides an NCU analysis report or requests CUDA kernel generation, optimization, or implementation of techniques like Shared Memory Tiling, vectorized loads, bank conflict elimination, or double buffering. Does not handle compilation, execution, or profiling.
| name | flashinfer |
| description | FlashInfer — High-performance kernel library for LLM inference with optimized attention, paged KV-cache, FP8/FP4 quantization |
| license | MIT |
| metadata | {"author":"Agent Cluster","tags":["flashinfer","llm","inference","attention","kv-cache","fp8","quantization","cuda","serving"]} |
High-performance GPU kernel library for Large Language Model inference delivering state-of-the-art performance across diverse GPU architectures with optimized attention, GEMM, and MoE operations.
Official Sources:
Definition:
"A library and kernel generator for Large Language Models that provides high-performance implementation of LLM GPU kernels such as FlashAttention, PageAttention and LoRA."
Key Features:
# Basic installation
pip install flashinfer-python
# With pre-compiled kernels (recommended)
pip install flashinfer-python flashinfer-cubin
# With JIT cache for specific CUDA version
pip install flashinfer-jit-cache --index-url https://flashinfer.ai/whl/cu129
System Requirements:
flashinfer show-config
import torch
import flashinfer
# Single decode with paged KV-cache
output = flashinfer.single_decode_with_kv_cache(
q=query, # (num_qo_heads, head_dim)
kv_data=kv_cache, # (num_pages, 2, num_kv_heads, page_size, head_dim)
kv_indices=kv_page_indices, # (num_pages,)
kv_indptr=kv_page_indptr, # (batch_size + 1,)
kv_last_page_len=last_page_lengths, # (batch_size,)
)
Decode (Token-by-Token Generation):
# Single request decode
output = flashinfer.single_decode_with_kv_cache(
q=query,
kv_data=kv_cache,
# ... KV-cache parameters
)
# Batch decode with cuDNN backend
output = flashinfer.cudnn_batch_decode_with_kv_cache(
q=queries, # (total_num_qo_heads, head_dim)
kv_data=kv_cache,
qo_indptr=qo_indptr, # Query offsets
kv_indptr=kv_indptr, # KV offsets
)
# Using wrapper for multi-layer inference
wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper()
wrapper.begin_forward(...)
for layer in model.layers:
output = wrapper.forward(query)
wrapper.end_forward()
Prefill (Prompt Processing):
# Single request prefill
output = flashinfer.single_prefill_with_kv_cache(
q=query, # (qo_len, num_qo_heads, head_dim)
kv_data=kv_cache,
causal=True, # Causal masking
)
# Batch prefill with ragged KV-cache
wrapper = flashinfer.BatchPrefillWithRaggedKVCacheWrapper()
wrapper.begin_forward(
qo_indptr=qo_indptr,
kv_indptr=kv_indptr,
)
output = wrapper.forward(query, kv_cache)
Append (Speculative Decoding):
# Append new tokens to KV-cache
output = flashinfer.single_prefill_with_kv_cache(
q=new_queries, # (num_new_tokens, num_qo_heads, head_dim)
kv_data=kv_cache,
causal=True,
append_mode=True,
)
1. Paged KV-Cache:
# Page-based storage (like virtual memory)
kv_cache = torch.empty(
num_pages, 2, num_kv_heads, page_size, head_dim,
dtype=torch.float16, device='cuda'
)
# Page table maps sequences to pages
page_indices = torch.tensor([[0, 1, 2], [3, 4, 5]], device='cuda')
2. Ragged Tensor:
# Variable-length sequences without padding
kv_data = torch.cat([seq1_kv, seq2_kv, seq3_kv], dim=0)
kv_indptr = torch.tensor([0, len(seq1), len(seq1)+len(seq2), ...])
3. Padded Tensor:
# Standard dense format
kv_cache = torch.zeros(
batch_size, max_seq_len, 2, num_kv_heads, head_dim
)
FP8 Matrix Multiplication:
# FP8 GEMM with groupwise scaling
output = flashinfer.gemm_fp8_nt_groupwise(
x=input_fp8, # FP8 input
w=weight_fp8, # FP8 weight
x_scale=input_scale, # Per-group scales
w_scale=weight_scale,
group_size=128,
)
FP4 Quantized GEMM:
# FP4 matrix multiplication
output = flashinfer.mm_fp4(
x=input,
w_q=weight_fp4, # Quantized to FP4
scales=scales,
group_size=64,
)
Mixture of Experts:
# Fused MoE with FP8 quantization
output = flashinfer.trtllm_fp8_block_scale_moe(
x=hidden_states, # (num_tokens, hidden_size)
w1=expert_weights_w1, # FP8 weights
w2=expert_weights_w2,
topk_weights=routing_weights, # (num_tokens, topk)
topk_ids=expert_ids, # (num_tokens, topk)
scales_w1=scales_w1,
scales_w2=scales_w2,
)
Top-K and Top-P Sampling:
# Top-K sampling
next_token = flashinfer.top_k_sampling_from_probs(
probs=probs, # (batch_size, vocab_size)
top_k=40,
uniform_samples=torch.rand(batch_size, device='cuda'),
)
# Top-P (nucleus) sampling
next_token = flashinfer.top_p_sampling_from_probs(
probs=probs,
top_p=0.9,
uniform_samples=torch.rand(batch_size, device='cuda'),
)
# Combined Top-K and Top-P
next_token = flashinfer.top_k_top_p_sampling_from_logits(
logits=logits,
top_k=40,
top_p=0.9,
uniform_samples=torch.rand(batch_size, device='cuda'),
)
Speculative Decoding:
# Chain speculative sampling
accepted_tokens = flashinfer.chain_speculative_sampling(
draft_probs=draft_model_probs, # (batch_size, num_draft_tokens, vocab)
draft_tokens=draft_tokens, # (batch_size, num_draft_tokens)
target_probs=target_model_probs, # (batch_size, num_draft_tokens+1, vocab)
uniform_samples=torch.rand(batch_size, num_draft_tokens+1),
)
Optimize shared prefix scenarios (e.g., document QA):
# Shared prefix attention (stored in SMEM)
shared_output = flashinfer.single_prefill_with_kv_cache(
q=queries,
kv_data=shared_prefix_kv,
# ... shared KV parameters
)
# Unique suffix attention
suffix_output = flashinfer.batch_decode_with_kv_cache(
q=queries,
kv_data=suffix_kv,
# ... suffix KV parameters
)
# Merge attention states
final_output = merge_attention_states(shared_output, suffix_output)
Performance: Up to 31x speedup vs baseline PageAttention
For DeepSeek models:
# MLA-specific wrapper
wrapper = flashinfer.BatchMLAPagedAttentionWrapper()
wrapper.begin_forward(...)
# MLA decode
output = flashinfer.trtllm_batch_decode_with_kv_cache_mla(
q=latent_query,
kv_data=latent_kv_cache,
# ... MLA-specific parameters
)
# Apply RoPE in-place
flashinfer.apply_rope_inplace(
q=query, # (seq_len, num_heads, head_dim)
k=key,
indptr=indptr,
offsets=position_offsets,
rotary_dim=head_dim,
)
# Apply RoPE with position IDs
flashinfer.apply_rope_pos_ids(
q=query,
k=key,
pos_ids=position_ids,
rotary_dim=head_dim,
)
# RMSNorm
output = flashinfer.rmsnorm(
input=hidden_states,
weight=norm_weight,
eps=1e-6,
)
# Fused Add + RMSNorm
output = flashinfer.fused_add_rmsnorm(
input=hidden_states,
residual=residual,
weight=norm_weight,
eps=1e-6,
)
Decode Attention: O(1) operational intensity (memory-bound) Prefill Attention: O(l_q) operational intensity (compute-bound for long sequences)
| GPU | Decode TFLOPS | Prefill TFLOPS |
|---|---|---|
| H100 | ~200 | ~800 |
| A100 | ~80 | ~300 |
| RTX 4090 | ~60 | ~250 |
from flashinfer import BatchDecodeWithPagedKVCacheWrapper
class FlashInferAttention:
def __init__(self, num_heads, head_dim):
self.wrapper = BatchDecodeWithPagedKVCacheWrapper()
def forward(self, query, kv_cache, kv_indptr, kv_indices):
return self.wrapper.forward(query)
import flashinfer
# Initialize wrappers
decode_wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper()
prefill_wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper()
# Use in forward pass
if is_prefill:
output = prefill_wrapper.forward(query, kv_cache)
else:
output = decode_wrapper.forward(query)
flashinfer-cubin for faster startupflashinfer.bench for performance analysis