Repository navigation
Variable Length (VarLen) Kernel #5587
|
Hi everyone, I'm looking to use variable-length (unpadded/ragged batching) attention kernels in JAX/Flax to avoid padding overhead. A few questions: Does JAX or Flax directly support variable-length attention kernels (e.g., FlashAttention varlen)? Is this handled via jax.nn.dot_product_attention using implementation='cudnn' along with query_seq_lengths and key_value_seq_lengths? If anyone has a minimal working example demonstrating the expected input shapes (e.g., whether sequences should be flattened into a single batch dimension or passed with dynamic length vectors), I'd really appreciate it! Thanks! |
Replies: 1 comment 1 reply
|
Yes. Current JAX supports sequence-length-aware attention, with one important distinction: the public API uses padded dense tensors plus per-example length vectors, not FlashAttention-style flattened packed tokens with cumulative offsets. The batched shapes are:
import jax
import jax.numpy as jnp
def varlen_attention(q, k, v, q_lengths, kv_lengths, *, causal=False):
return jax.nn.dot_product_attention(
q,
k,
v,
is_causal=causal,
query_seq_lengths=jnp.asarray(q_lengths, dtype=jnp.int32),
key_value_seq_lengths=jnp.asarray(kv_lengths, dtype=jnp.int32),
implementation="cudnn",
)
B, T, S, N, K, H = 2, 128, 160, 8, 8, 64
q = jnp.zeros((B, T, N, H), dtype=jnp.bfloat16)
k = jnp.zeros((B, S, K, H), dtype=jnp.bfloat16)
v = jnp.zeros((B, S, K, H), dtype=jnp.bfloat16)
q_lengths = jnp.array([93, 61], dtype=jnp.int32)
kv_lengths = jnp.array([145, 72], dtype=jnp.int32)
y = varlen_attention(q, k, v, q_lengths, kv_lengths)
assert y.shape == (B, T, N, H)Do not concatenate the sequences into A few limitations matter:
Current Flax Linen and NNX attention wrappers expose masks but not The reliable Flax approach is therefore a small custom Linen/NNX block: use the normal projections to create References: JAX public API and validation, length/cuDNN tests, cuDNN restrictions, Flax Linen wrapper, and Flax NNX wrapper. |
Yes. Current JAX supports sequence-length-aware attention, with one important distinction: the public API uses padded dense tensors plus per-example length vectors, not FlashAttention-style flattened packed tokens with cumulative offsets.
The batched shapes are:
[B, T, N, H][B, S, K, H][B],int32[B],int32[B, T, N, H]Nis the number of query heads andKis the number of key/value heads.Nmust be divisible byK;K == Nis MHA,K == 1is MQA, and intermediate divisors are GQA. Each sequence's valid tokens occupy the prefix of its padded row.