Views
No views yet
uv run https://huggingface.co/kernels-community/vllm-flash-attn3/raw/main/readme_example.py1# /// script
2# requires-python = ">=3.10"
3# dependencies = [
4# "torch",
5# "triton",
6# "numpy",
7# "kernels",
8# ]
9# ///
10
11import torch
12from kernels import get_kernel
13
14# Load vllm-flash-attn3 via kernels library
15vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3")
16
17# Access Flash Attention function
18flash_attn_func = vllm_flash_attn3.flash_attn_func
19
20# Set device and seed for reproducibility
21device = "cuda"
22torch.manual_seed(42)
23torch.cuda.manual_seed(42)
24
25# Parameters
26batch_size = 2
27seqlen_q = 128 # Query sequence length
28seqlen_k = 256 # Key sequence length
29nheads = 8 # Number of attention heads
30d = 64 # Head dimension
31
32# Create input tensors (Q, K, V)
33q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=torch.bfloat16)
34k = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=torch.bfloat16)
35v = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=torch.bfloat16)
36
37print(f"Query shape: {q.shape}")
38print(f"Key shape: {k.shape}")
39print(f"Value shape: {v.shape}")
40
41# Run Flash Attention 3
42output, lse = flash_attn_func(q, k, v, causal=True)
43
44print(f"\nOutput shape: {output.shape}")
45print(f"LSE (log-sum-exp) shape: {lse.shape}")
46print(f"\nAttention computation successful!")
47print(f"Output tensor stats - Mean: {output.mean().item():.4f}, Std: {output.std().item():.4f}")1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3model_id = "<your model id on the Hub>"
4
5tokenizer = AutoTokenizer.from_pretrained(model_id)
6model = AutoModelForCausalLM.from_pretrained(
7 model_id,
8 device_map="auto",
9 torch_dtype="auto",
10+ # Flash Attention with Sinks
11+ attn_implementation="kernels-community/vllm-flash-attn3”,
12)