fla / build /torch-cuda /ops /attn /parallel.py
kernels-bot's picture
Uploaded using `kernel-builder`.
e19323e verified
Raw
History Blame
29.5 kB
# Copyright (c) 2023-2026, Songlin Yang, Yu Zhang, Zhiyuan Li
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# For a list of all contributors, visit:
# https://github.com/fla-org/flash-linear-attention/graphs/contributors
import torch
import triton
import triton.language as tl
from einops import reduce
from ...ops.backends import dispatch
from ...ops.utils import prepare_chunk_indices
from ...ops.utils.constant import RCP_LN2
from ...ops.utils.cumsum import chunk_global_cumsum
from ...ops.utils.op import exp2, log2
from ...utils import autocast_custom_bwd, autocast_custom_fwd, check_shared_mem, contiguous
@triton.heuristics({
'USE_G': lambda args: args['g_cumsum'] is not None,
'USE_SINK_BIAS': lambda args: args['sink_bias'] is not None,
'USE_WINDOW': lambda args: args['W'] is not None,
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.jit
def parallel_attn_fwd_kernel(
q,
k,
v,
o,
g_cumsum,
sink_bias,
lse,
scale,
cu_seqlens,
chunk_indices,
T,
W: tl.constexpr,
B: tl.constexpr,
H: tl.constexpr,
HQ: tl.constexpr,
G: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BS: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
USE_G: tl.constexpr,
USE_SINK_BIAS: tl.constexpr,
USE_WINDOW: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_hq = i_bh // HQ, i_bh % HQ
i_h = i_hq // G
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
T = (eos - bos).to(tl.int32)
else:
i_n = i_b
bos, eos = (i_n * T).to(tl.int64), (i_n * T + T).to(tl.int64)
RCP_LN2: tl.constexpr = 1.4426950216
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_o = tl.make_block_ptr(o + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
# the Q block is kept in the shared memory throughout the whole kernel
# [BT, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BT, BV]
b_o = tl.zeros([BT, BV], dtype=tl.float32)
b_m = tl.full([BT], float('-inf'), dtype=tl.float32)
b_acc = tl.zeros([BT], dtype=tl.float32)
if USE_G:
p_g = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
b_gq = tl.load(p_g, boundary_check=(0,)).to(tl.float32)
else:
b_gq = None
if USE_SINK_BIAS:
b_sink_bias = tl.load(sink_bias + i_hq).to(tl.float32)
else:
b_sink_bias = None
# [BT]
o_q = i_t * BT + tl.arange(0, BT)
# for sliding window, skip key blocks that are entirely outside the window.
# the earliest key position any query in this block needs: max(0, i_t*BT - W + 1)
i_start = tl.maximum((i_t * BT - W + 1) // BS * BS, 0) if USE_WINDOW else 0
for i_s in range(i_start, i_t * BT, BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BS, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
if USE_G:
b_gk = tl.load(g_cumsum + (bos + o_k) * HQ + i_hq, mask=m_k, other=0).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
if USE_WINDOW:
b_s = tl.where((o_q[:, None] - o_k[None, :] < W) & m_k[None, :], b_s, float('-inf'))
# [BT, BS]
b_m, b_mp = tl.maximum(b_m, tl.max(b_s, 1)), b_m
# keep the online softmax pivot finite for rows that still have no valid key.
# this matches sglang's masked-row stabilization and avoids -inf - (-inf) = NaN.
b_mw = tl.where(b_m == float('-inf'), 0., b_m)
b_r = exp2(b_mp - b_mw)
b_p = exp2(b_s - b_mw[:, None])
# [BT]
b_acc = b_acc * b_r + tl.sum(b_p, 1)
# [BT, BV]
b_o = b_o * b_r[:, None] + tl.dot(b_p.to(b_q.dtype), b_v)
b_mp = b_m
for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
# [BS]
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BS, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
if USE_G:
b_gk = tl.load(g_cumsum + (bos + o_k) * HQ + i_hq, mask=m_k, other=0).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
m_s = (o_q[:, None] >= o_k[None, :]) & m_k[None, :]
if USE_WINDOW:
m_s = m_s & (o_q[:, None] - o_k[None, :] < W)
b_s = tl.where(m_s, b_s, float('-inf'))
# [BT]
b_m, b_mp = tl.maximum(b_m, tl.max(b_s, 1)), b_m
b_mw = tl.where(b_m == float('-inf'), 0., b_m)
b_r = exp2(b_mp - b_mw)
b_p = exp2(b_s - b_mw[:, None])
# [BT]
b_acc = b_acc * b_r + tl.sum(b_p, 1)
# [BT, BV]
b_o = b_o * b_r[:, None] + tl.dot(b_p.to(b_q.dtype), b_v)
b_mp = b_m
if USE_SINK_BIAS:
# when a row has no valid key at all, b_m is still -inf here.
# use a finite pivot before merging the sink-bias mass so lse becomes
# the sink-bias logit instead of hitting the -inf + inf = NaN path.
b_m = tl.where(b_m == float('-inf'), 0., b_m)
# denominator-only sink-bias update (matches GPT-OSS / sglang):
# the bias logit augments the softmax normalizer without contributing
# to the value matmul.
b_acc += exp2(b_sink_bias - b_m)
b_o = b_o / b_acc[:, None]
b_m += log2(b_acc)
tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_lse, b_m.to(p_lse.dtype.element_ty), boundary_check=(0,))
@triton.jit
def parallel_attn_bwd_kernel_preprocess(
o,
do,
delta,
B: tl.constexpr,
V: tl.constexpr,
):
i_n = tl.program_id(0).to(tl.int64)
o_d = tl.arange(0, B)
m_d = o_d < V
b_o = tl.load(o + i_n * V + o_d, mask=m_d, other=0)
b_do = tl.load(do + i_n * V + o_d, mask=m_d, other=0).to(tl.float32)
b_delta = tl.sum(b_o * b_do)
tl.store(delta + i_n, b_delta.to(delta.dtype.element_ty))
@triton.heuristics({
'USE_G': lambda args: args['g_cumsum'] is not None,
'USE_WINDOW': lambda args: args['W'] is not None,
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.jit(do_not_specialize=['T'])
def parallel_attn_bwd_kernel_dq(
q,
k,
v,
lse,
delta,
do,
dq,
dg_cumsum,
g_cumsum,
scale,
cu_seqlens,
chunk_indices,
T,
W: tl.constexpr,
B: tl.constexpr,
H: tl.constexpr,
HQ: tl.constexpr,
G: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BS: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
USE_G: tl.constexpr,
USE_WINDOW: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_hq = i_bh // HQ, i_bh % HQ
i_h = i_hq // G
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
T = (eos - bos).to(tl.int32)
else:
i_n = i_b
bos, eos = (i_n * T).to(tl.int64), (i_n * T + T).to(tl.int64)
# NOTE: we must multiply RCP_LN2 after tl.dot for high precision
RCP_LN2: tl.constexpr = 1.4426950216
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_dq = tl.make_block_ptr(dq + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_do = tl.make_block_ptr(do + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
p_delta = tl.make_block_ptr(delta + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
# [BT, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BT, BV]
b_do = tl.load(p_do, boundary_check=(0, 1))
# [BT]
b_lse = tl.load(p_lse, boundary_check=(0,))
b_delta = tl.load(p_delta, boundary_check=(0,))
# [BT, BK]
b_dq = tl.zeros([BT, BK], dtype=tl.float32)
if USE_G:
b_dg = tl.zeros([BT], dtype=tl.float32)
p_gq = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
b_gq = tl.load(p_gq, boundary_check=(0,)).to(tl.float32)
else:
b_gq = None
b_dg = None
o_q = i_t * BT + tl.arange(0, BT)
i_start = tl.maximum((i_t * BT - W + 1) // BS * BS, 0) if USE_WINDOW else 0
for i_s in range(i_start, i_t * BT, BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BV, BS]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
if USE_G:
b_gk = tl.load(g_cumsum + (bos + o_k) * HQ + i_hq, mask=m_k, other=0).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
if USE_WINDOW:
b_s = tl.where((o_q[:, None] - o_k[None, :] < W) & m_k[None, :], b_s, float('-inf'))
b_p = exp2(b_s - b_lse[:, None])
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_do, b_v)
b_ds = b_p * (b_dp.to(tl.float32) - b_delta[:, None])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dq += tl.dot(b_ds.to(b_k.dtype), tl.trans(b_k))
if USE_G:
b_dg += tl.sum(b_ds, 1)
for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
# [BS]
o_k = i_s + tl.arange(0, BS)
m_k = o_k < T
# [BK, BS]
b_k = tl.load(p_k, boundary_check=(0, 1))
# [BV, BS]
b_v = tl.load(p_v, boundary_check=(0, 1))
# [BT, BS]
b_s = tl.dot(b_q, b_k) * scale * RCP_LN2
if USE_G:
p_gk = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
b_gk = tl.load(p_gk, boundary_check=(0,)).to(tl.float32)
b_s += b_gq[:, None] - b_gk[None, :]
if USE_WINDOW:
b_p = tl.where(
(o_q[:, None] >= o_k[None, :]) & (o_q[:, None] - o_k[None, :] < W) & m_k[None, :],
exp2(b_s - b_lse[:, None]), 0
)
else:
b_p = tl.where((o_q[:, None] >= o_k[None, :]) & m_k[None, :], exp2(b_s - b_lse[:, None]), 0)
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_do, b_v)
b_ds = b_p * (b_dp.to(tl.float32) - b_delta[:, None])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dq += tl.dot(b_ds.to(b_k.dtype), tl.trans(b_k))
if USE_G:
b_dg += tl.sum(b_ds, 1)
b_dq *= scale
tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
if USE_G:
p_dg = tl.make_block_ptr(dg_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0,))
@triton.heuristics({
'USE_G': lambda args: args['g_cumsum'] is not None,
'USE_WINDOW': lambda args: args['W'] is not None,
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.jit(do_not_specialize=['T'])
def parallel_attn_bwd_kernel_dkv(
q,
k,
v,
g_cumsum,
lse,
delta,
do,
dk,
dv,
dg_cumsum,
cu_seqlens,
chunk_indices,
scale,
T,
W: tl.constexpr,
B: tl.constexpr,
H: tl.constexpr,
HQ: tl.constexpr,
G: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BS: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
USE_G: tl.constexpr,
USE_WINDOW: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_v, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_hq = i_bh // HQ, i_bh % HQ
i_h = i_hq // G
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
T = (eos - bos).to(tl.int32)
else:
i_n = i_b
bos, eos = (i_n * T).to(tl.int64), (i_n * T + T).to(tl.int64)
RCP_LN2: tl.constexpr = 1.4426950216
p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_dk = tl.make_block_ptr(dk + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_t * BT, 0), (BT, BK), (1, 0))
p_dv = tl.make_block_ptr(dv + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
# [BT, BK]
b_k = tl.load(p_k, boundary_check=(0, 1))
b_dk = tl.zeros([BT, BK], dtype=tl.float32)
# [BT, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
b_dv = tl.zeros([BT, BV], dtype=tl.float32)
o_k = i_t * BT + tl.arange(0, BT)
if USE_G:
p_gk = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
b_gk = tl.load(p_gk, boundary_check=(0,)).to(tl.float32)
b_dg = tl.zeros([BT], dtype=tl.float32)
else:
b_gk = None
b_dg = None
for i_s in range(i_t * BT, min((i_t + 1) * BT, T), BS):
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_s, 0), (BS, BK), (1, 0))
p_do = tl.make_block_ptr(do + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
p_delta = tl.make_block_ptr(delta + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
# [BS]
o_q = i_s + tl.arange(0, BS)
m_q = o_q < T
# [BS, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BS, BV]
b_do = tl.load(p_do, boundary_check=(0, 1))
# [BS]
b_lse = tl.load(p_lse, boundary_check=(0,))
b_delta = tl.load(p_delta, boundary_check=(0,))
# [BT, BS]
b_s = tl.dot(b_k, tl.trans(b_q)) * scale * RCP_LN2
if USE_G:
p_gq = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
b_gq = tl.load(p_gq, boundary_check=(0,)).to(tl.float32)
b_s += b_gq[None, :] - b_gk[:, None]
if USE_WINDOW:
b_p = tl.where(
(o_k[:, None] <= o_q[None, :]) & (o_q[None, :] - o_k[:, None] < W) & m_q[None, :],
exp2(b_s - b_lse[None, :]), 0
)
else:
b_p = tl.where((o_k[:, None] <= o_q[None, :]) & m_q[None, :], exp2(b_s - b_lse[None, :]), 0)
# [BT, BS] @ [BS, BV] -> [BT, BV]
b_dv += tl.dot(b_p.to(b_do.dtype), b_do)
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_v, tl.trans(b_do))
# [BT, BS]
b_ds = b_p * (b_dp - b_delta[None, :])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)
if USE_G:
b_dg -= tl.sum(b_ds, 1)
# for sliding window, limit the range of future query blocks to process.
# a key at position k_pos can only be attended to by queries at positions [k_pos, k_pos + W - 1].
# so we only need queries up to (i_t + 1) * BT - 1 + W - 1.
i_end = min(tl.cdiv(T, BS) * BS, (i_t + 1) * BT + W - 1) if USE_WINDOW else tl.cdiv(T, BS) * BS
for i_s in range((i_t + 1) * BT, i_end, BS):
p_q = tl.make_block_ptr(q + (bos * HQ + i_hq) * K, (T, K), (HQ*K, 1), (i_s, 0), (BS, BK), (1, 0))
p_do = tl.make_block_ptr(do + (bos * HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
p_lse = tl.make_block_ptr(lse + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
p_delta = tl.make_block_ptr(delta + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
# [BS]
o_q = i_s + tl.arange(0, BS)
m_q = o_q < T
# [BS, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BS, BV]
b_do = tl.load(p_do, boundary_check=(0, 1))
# [BS]
b_lse = tl.load(p_lse, boundary_check=(0,))
b_delta = tl.load(p_delta, boundary_check=(0,))
# [BT, BS]
b_s = tl.dot(b_k, tl.trans(b_q)) * scale * RCP_LN2
if USE_G:
p_gq = tl.make_block_ptr(g_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_s,), (BS,), (0,))
b_gq = tl.load(p_gq, boundary_check=(0,)).to(tl.float32)
b_s += b_gq[None, :] - b_gk[:, None]
if USE_WINDOW:
b_p = tl.where((o_q[None, :] - o_k[:, None] < W) & m_q[None, :], exp2(b_s - b_lse[None, :]), 0)
else:
b_p = tl.where(m_q[None, :], exp2(b_s - b_lse[None, :]), 0)
# [BT, BS] @ [BS, BV] -> [BT, BV]
b_dv += tl.dot(b_p.to(b_do.dtype), b_do)
# [BT, BV] @ [BV, BS] -> [BT, BS]
b_dp = tl.dot(b_v, tl.trans(b_do))
# [BT, BS]
b_ds = b_p * (b_dp - b_delta[None, :])
# [BT, BS] @ [BS, BK] -> [BT, BK]
b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)
if USE_G:
b_dg -= tl.sum(b_ds, 1)
b_dk = b_dk * scale
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
if USE_G:
p_dg = tl.make_block_ptr(dg_cumsum + bos * HQ + i_hq, (T,), (HQ,), (i_t * BT,), (BT,), (0,))
tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0,))
@dispatch('attn')
def parallel_attn_fwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g_cumsum: torch.Tensor,
sink_bias: torch.Tensor | None,
scale: float,
window_size: int | None = None,
cu_seqlens: torch.LongTensor | None = None,
chunk_indices: torch.LongTensor | None = None,
):
B, T, H, K, V = *k.shape, v.shape[-1]
HQ = q.shape[2]
G = HQ // H
BT = 128
if check_shared_mem('hopper', q.device.index):
BS = min(64, max(16, triton.next_power_of_2(T)))
BK = min(256, max(16, triton.next_power_of_2(K)))
BV = min(256, max(16, triton.next_power_of_2(V)))
num_warps = 8
elif check_shared_mem('ampere', q.device.index):
BS = min(32, max(16, triton.next_power_of_2(T)))
BK = min(256, max(16, triton.next_power_of_2(K)))
BV = min(128, max(16, triton.next_power_of_2(V)))
num_warps = 4
else:
BS = min(32, max(16, triton.next_power_of_2(T)))
BK = min(256, max(16, triton.next_power_of_2(K)))
BV = min(64, max(16, triton.next_power_of_2(V)))
num_warps = 2
NK = triton.cdiv(K, BK)
NV = triton.cdiv(V, BV)
if chunk_indices is None and cu_seqlens is not None:
chunk_indices = prepare_chunk_indices(cu_seqlens, BT)
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
assert NK == 1, "The key dimension can not be larger than 256"
o = torch.empty(B, T, HQ, V, dtype=v.dtype, device=q.device)
lse = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
grid = (NV, NT, B * HQ)
parallel_attn_fwd_kernel[grid](
q=q,
k=k,
v=v,
o=o,
g_cumsum=g_cumsum,
sink_bias=sink_bias,
lse=lse,
scale=scale,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
B=B,
T=T,
W=window_size,
H=H,
HQ=HQ,
G=G,
K=K,
V=V,
BT=BT,
BS=BS,
BK=BK,
BV=BV,
num_warps=num_warps,
)
return o, lse
def parallel_attn_bwd_preprocess(
o: torch.Tensor,
do: torch.Tensor,
):
V = o.shape[-1]
delta = torch.empty_like(o[..., 0], dtype=torch.float)
parallel_attn_bwd_kernel_preprocess[(delta.numel(),)](
o=o,
do=do,
delta=delta,
B=triton.next_power_of_2(V),
V=V,
)
return delta
@dispatch('attn')
def parallel_attn_bwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
o: torch.Tensor,
g_cumsum: torch.Tensor,
lse: torch.Tensor,
do: torch.Tensor,
sink_bias: torch.Tensor | None = None,
scale: float = None,
window_size: int | None = None,
chunk_size: int = 128,
cu_seqlens: torch.LongTensor | None = None,
chunk_indices: torch.LongTensor | None = None,
):
B, T, H, K, V = *k.shape, v.shape[-1]
HQ = q.shape[2]
G = HQ // H
# dq/dk are reduced over the full value dim in one program (no cross-program accumulation),
# so BV must span all of V (NV == 1). Don't cap it here -- the forward can, the backward can't.
if check_shared_mem('hopper'):
BT = 128
BS = 64
BK = max(triton.next_power_of_2(K), 16)
BV = max(triton.next_power_of_2(V), 16)
num_warps = 8
elif check_shared_mem('ampere'):
BS = 32
BK = max(triton.next_power_of_2(K), 16)
BV = max(triton.next_power_of_2(V), 16)
BT = 128 if K <= 64 else 64
num_warps = 4
else:
BT = 64
BS = 32
BK = max(triton.next_power_of_2(K), 16)
BV = max(triton.next_power_of_2(V), 16)
num_warps = 2
if chunk_indices is None and cu_seqlens is not None:
chunk_indices = prepare_chunk_indices(cu_seqlens, BT)
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
NV = triton.cdiv(V, BV)
delta = parallel_attn_bwd_preprocess(o, do)
dq = torch.empty(B, T, HQ, K, dtype=k.dtype if H == HQ else torch.float, device=q.device)
dk = torch.empty(B, T, HQ, K, dtype=k.dtype if H == HQ else torch.float, device=q.device)
dv = torch.empty(B, T, HQ, V, dtype=v.dtype if H == HQ else torch.float, device=q.device)
grid = (NV, NT, B * HQ)
dg_cumsum, dg_cumsum_k = None, None
if g_cumsum is not None:
dg_cumsum = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
dg_cumsum_k = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
parallel_attn_bwd_kernel_dq[grid](
q=q,
k=k,
v=v,
g_cumsum=g_cumsum,
lse=lse,
delta=delta,
do=do,
dq=dq,
dg_cumsum=dg_cumsum,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
scale=scale,
T=T,
W=window_size,
B=B,
H=H,
HQ=HQ,
G=G,
K=K,
V=V,
BT=BT,
BS=BS,
BK=BK,
BV=BV,
num_warps=num_warps,
)
parallel_attn_bwd_kernel_dkv[grid](
q=q,
k=k,
v=v,
g_cumsum=g_cumsum,
lse=lse,
delta=delta,
do=do,
dk=dk,
dv=dv,
dg_cumsum=dg_cumsum_k,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
scale=scale,
T=T,
W=window_size,
B=B,
H=H,
HQ=HQ,
G=G,
K=K,
V=V,
BT=BT,
BS=BS,
BK=BK,
BV=BV,
num_warps=num_warps,
)
dk = reduce(dk, 'b t (h g) k -> b t h k', g=G, reduction='sum')
dv = reduce(dv, 'b t (h g) v -> b t h v', g=G, reduction='sum')
if g_cumsum is not None:
dg_cumsum.add_(dg_cumsum_k)
dsink_bias = None
if sink_bias is not None:
p_sink_bias = torch.exp2(sink_bias[None, None, :] - lse)
dsink_bias = -(p_sink_bias * delta).sum((0, 1))
return dq, dk, dv, dg_cumsum, dsink_bias
@torch.compile
class ParallelAttentionFunction(torch.autograd.Function):
@staticmethod
@contiguous
@autocast_custom_fwd
def forward(ctx, q, k, v, g, sink_bias, scale, window_size, cu_seqlens, chunk_indices=None):
ctx.dtype = q.dtype
g_cumsum = chunk_global_cumsum(g, cu_seqlens=cu_seqlens, scale=RCP_LN2) if g is not None else None
sink_bias = sink_bias * RCP_LN2 if sink_bias is not None else None
o, lse = parallel_attn_fwd(
q=q,
k=k,
v=v,
g_cumsum=g_cumsum,
sink_bias=sink_bias,
scale=scale,
window_size=window_size,
cu_seqlens=cu_seqlens,
chunk_indices=chunk_indices,
)
ctx.save_for_backward(q, k, v, o, g_cumsum, lse, sink_bias)
ctx.scale = scale
ctx.window_size = window_size
ctx.cu_seqlens = cu_seqlens
return o.to(q.dtype)
@staticmethod
@contiguous
@autocast_custom_bwd
def backward(ctx, do):
q, k, v, o, g_cumsum, lse, sink_bias = ctx.saved_tensors
dq, dk, dv, dg, dsink_bias = parallel_attn_bwd(
q=q,
k=k,
v=v,
o=o,
g_cumsum=g_cumsum,
lse=lse,
do=do,
sink_bias=sink_bias,
scale=ctx.scale,
window_size=ctx.window_size,
cu_seqlens=ctx.cu_seqlens,
)
if dg is not None:
dg = chunk_global_cumsum(dg, cu_seqlens=ctx.cu_seqlens, reverse=True)
return dq.to(q), dk.to(k), dv.to(v), dg, dsink_bias, None, None, None, None
def parallel_attn(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g: torch.Tensor | None = None,
scale: float | None = None,
window_size: int | None = None,
cu_seqlens: torch.LongTensor | None = None,
chunk_indices: torch.LongTensor | None = None,
*,
sink_bias: torch.Tensor | None = None,
**kwargs
) -> torch.Tensor:
r"""
Args:
q (torch.Tensor):
queries of shape `[B, T, HQ, K]`.
k (torch.Tensor):
keys of shape `[B, T, H, K]`.
GQA will be applied if HQ is divisible by H.
v (torch.Tensor):
values of shape `[B, T, H, V]`.
g (Optional[torch.Tensor]):
log decay factors of shape `[B, T, HQ]`.
scale (Optional[float]):
Scale factor for attention scores.
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
window_size (Optional[int]):
Sliding window size. If provided, each query at position i only attends to
keys in `[i - window_size + 1, i]`. If `None`, full causal attention is used.
Default: `None`.
cu_seqlens (torch.LongTensor):
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
consistent with the FlashAttention API.
sink_bias (Optional[torch.Tensor]):
Per-query-head attention-sink bias logits of shape `[HQ]` — one
learnable scalar per query head, as introduced by GPT-OSS.
Augments the softmax denominator with `exp(sink_bias[h])` without
adding a corresponding key/value entry, so the model can route
attention mass to a learnable "no-op" target:
p_i = exp(s_i) / (sum_j exp(s_j) + exp(sink_bias[h]))
o = sum_i p_i * v_i # sink slot contributes no value
When `None`, standard softmax is used. Reserved name: the future
`sink_tokens_*` kwargs will support Xiao 2024-style K/V sink tokens
and may be combined with `sink_bias`.
Returns:
o (torch.Tensor):
Outputs of shape `[B, T, HQ, V]`.
"""
if 'head_first' in kwargs:
raise DeprecationWarning(
"head_first has been removed. Inputs must be in `[B, T, H, ...]` format.",
)
if scale is None:
scale = k.shape[-1] ** -0.5
if cu_seqlens is not None and q.shape[0] != 1:
raise ValueError(
f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`. "
f"Please flatten variable-length inputs before processing.",
)
if sink_bias is not None:
assert sink_bias.shape == (q.shape[2],), "sink_bias must have shape [HQ]"
o = ParallelAttentionFunction.apply(
q, k, v, g, sink_bias, scale, window_size, cu_seqlens, chunk_indices
)
return o