Attention Operators¶
Every op on this page is used the same way: construct it once, then call it. The
constructor takes what the kernel is compiled with; the call takes the tensors.
Both are documented under each op — __init__ and forward, where forward is
what runs when you call op(...).
Multi-Head Attention¶
tileops.attention.MHAPagedFwdOp
¶
Paged Multi-Head Attention (MHA) decode with dynamic KV cache. Layout: Q \([batch \times seqlen\_q \times heads \times dim]\) (BSHD);
k_cache, v_cache physical cache [seqlen_kv, heads, dim]; block_table [batch, num_pages]; cache_seqlens [batch].
A causal call aligns the queries to the end of each request's cache: query i sees
the keys up to position i + cache_seqlens - seqlen_q. A query that sees no key
outputs zeros. The op takes no sm_scale; scores are scaled by dim ** -0.5.
__init__
¶
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
page_size(int) –Rows per cache page; a positive multiple of 16 that divides
N_kv. -
is_causal(bool, default:False) –Align the queries to the end of each request's cache and mask later keys.
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Attend each request's query tokens to its cache.
Parameters:
-
q(Tensor) –(B, S_q, H, D)queries, float16 or bfloat16. -
k_cache(Tensor) –(N_kv, H, D)key cache in the query dtype. -
v_cache(Tensor) –(N_kv, H, D)value cache in the query dtype. -
block_table(Tensor) –int32(B, W); keynof requestbis rowblock_table[b, n // page_size] * page_size + n % page_sizeof the cache. -
cache_seqlens(Tensor) –int32(B,), the keys each request holds, at mostW * page_size.
Returns:
-
Tensor–o(B, S_q, H, D)in the query dtype.
Grouped-Query Attention¶
tileops.attention.GQADenseBwdOp
¶
Grouped-Query Attention (GQA) backward over dense tensors. Layout: BSHD.
The backward of :class:GQADenseWithLSEFwdOp over a square call (\(S_q = S_{kv} = S\)):
o and lse are the pair that forward returns, and the parameters mean what the
forward's do. lse is the float32 natural-log log-sum-exp of each query row's scaled
scores, [B, H, S]; a row with lse -inf saw no key and gets zero gradients.
The in-tree kernels serve no window and no softcap; a call with a window that hides
a key, or with a cap, is refused when a kernel is selected, naming the limit. Pass them
anyway, equal to the forward's, so a refused call says why.
__init__
¶
__init__(
is_causal=False,
window_size_left=-1,
window_size_right=-1,
sm_scale=None,
softcap=None,
*,
target=None
)
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
is_causal(bool, default:False) –Apply the causal mask. Default
False, as inflash_attn_func. -
window_size_left(int, default:-1) –Keys admitted left of a query row;
-1means unlimited. The in-tree kernels serve only-1or a window reaching every key. -
window_size_right(int, default:-1) –Keys admitted right of a query row;
-1means unlimited. The in-tree kernels serve only-1or a window reaching every key. -
sm_scale(float | None, default:None) –Score scale, or
NoneforD ** -0.5,Dthe head dimension ofqandk. -
softcap(float | None, default:None) –Score cap of the forward;
Noneor0disables it. The in-tree kernels serve only a disabled cap. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
Raises:
-
ValueError–softcapis negative.
forward
¶
Return the gradients of q, k and v.
Parameters:
-
do(Tensor) –Gradient of the loss with respect to
o,[B, S, H, D], same dtype asq. -
q(Tensor) –Queries,
[B, S, H, D],float16orbfloat16. -
k(Tensor) –Keys,
[B, S, H_kv, D], same dtype asq. -
v(Tensor) –Values,
[B, S, H_kv, D], same dtype asq. -
o(Tensor) –The forward output,
[B, S, H, D], same dtype asq. -
lse(Tensor) –The forward's natural-log log-sum-exp,
[B, H, S],float32.
Returns:
-
tuple[Tensor, Tensor, Tensor]–(dq, dk, dv), shaped likeq,kandv, in their dtype.
tileops.attention.GQADenseFwdOp
¶
Grouped-Query Attention (GQA) over dense \(Q\)/\(K\)/\(V\) tensors, layout BSHD.
Every batch entry has one query length \(S_q\) and one KV length \(S_{kv}\). The \(H\) query
heads form \(H_{kv}\) groups of \(g = H / H_{kv}\); head \(h\) reads KV head
\(r(h) = \lfloor h / g \rfloor\). Query row \(i\) sits at KV position
\(p_i = i + S_{kv} - S_q\). With \(\alpha\) = sm_scale (default \(1/\sqrt D\)),
\(c\) = softcap and \(\sigma_h = \exp(\mathrm{sinks}_h)\), or \(0\) without sinks:
Key \(j\) is in the visible set \(\mathcal V_i\) when is_causal is off or \(j \le p_i\),
and it lies within window_size_left keys left and window_size_right keys right
of \(p_i\), -1 meaning unlimited. \(Q'\) and \(K'\) are \(Q\) and \(K\) times q_scale and
k_scale for FP8 input, rotated under pos_encoding_mode="rope" at positions \(p_i\)
and \(j\); \(V'\) is \(V\) times v_scale. A sink is neither scaled nor capped, and the
in-tree kernels serve sinks on SM90, and on SM89 for FP16/BF16 prefill and decode
without fused RoPE for decode. Accumulation is FP32; the output takes the input dtype,
or out_dtype for FP8 input.
__init__
¶
__init__(
is_causal=False,
window_size_left=-1,
window_size_right=-1,
sm_scale=None,
softcap=None,
pos_encoding_mode="none",
rotary_dim=None,
rope_layout="neox",
out_dtype=None,
*,
target=None
)
Configure the op. Tensor shapes and input dtype come from each call.
Parameters:
-
is_causal(bool, default:False) –Apply the causal mask, bottom-right aligned. Default
False, as inflash_attn_func. -
window_size_left(int, default:-1) –Keys admitted left of the query row's KV position \(p_i\);
-1means unlimited. -
window_size_right(int, default:-1) –Keys admitted right of \(p_i\);
-1means unlimited. -
sm_scale(float | None, default:None) –Score scale \(\alpha\).
Nonemeans \(1 / \sqrt{D}\), \(D\) the head dimension ofqandkin the current call. A scale whose product with \(\log_2 e\) rounds to zero in FP32 weighs every visible key equally. -
softcap(float | None, default:None) –Positive cap \(c\) replacing each raw score \(z\) with \(c \tanh(z / c)\).
Noneor0disables capping. -
pos_encoding_mode(str, default:'none') –"none", or"rope"to fuse the rotary embedding into attention. -
rotary_dim(int | None, default:None) –Rotated width of each head; even, at most \(D\), default the full head dimension. Valid only with
pos_encoding_mode="rope". -
rope_layout(str, default:'neox') –"neox"(rotate split halves) or"interleaved"(rotate adjacent pairs). -
out_dtype(dtype | None, default:None) –Output dtype. An FP8 call cannot return FP8 and the two 16-bit types are equally valid, so
float16orbfloat16must be named here; a 16-bit call has nothing to choose and accepts onlyNoneor its own input dtype. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
Raises:
-
ValueError–softcapis negative.
forward
¶
forward(
q,
k,
v,
q_scale=None,
k_scale=None,
v_scale=None,
rope_cos=None,
rope_sin=None,
sinks=None,
)
Run dense GQA attention over one set of \(Q\)/\(K\)/\(V\) tensors.
\(Q\), \(K\), and \(V\) are laid out row-major in BSHD axis order, so the
head dimension is the contiguous one. Every input must be on the same
device as q; a non-contiguous input is copied to a contiguous one
before the kernel runs.
Parameters:
-
q(Tensor) –Queries, \([B \times S_q \times H \times D]\);
float16,bfloat16, orfloat8_e4m3fn. -
k(Tensor) –Keys, \([B \times S_{kv} \times H_{kv} \times D]\), same dtype as
q. -
v(Tensor) –Values, \([B \times S_{kv} \times H_{kv} \times D]\), same dtype as
q. -
q_scale(Tensor | None, default:None) –FP8 dequantization scales for
q, one per batch and KV head, \([B \times H_{kv}]\),float32. The three scales are required together for FP8 input and invalid otherwise. -
k_scale(Tensor | None, default:None) –Scales for
k, one per batch and KV head, \([B \times H_{kv}]\),float32. -
v_scale(Tensor | None, default:None) –Scales for
v, one per batch and KV head, \([B \times H_{kv}]\),float32. -
rope_cos(Tensor | None, default:None) –RoPE cosine table indexed by KV position and rotated pair, \([P \times d_r / 2]\) with \(P \ge S_{kv}\) and \(d_r\) =
rotary_dim, in the output dtype. The two tables are required together withpos_encoding_mode="rope"and invalid otherwise. -
rope_sin(Tensor | None, default:None) –RoPE sine table, same layout, shape, and dtype as
rope_cos. -
sinks(Tensor | None, default:None) –Optional
float32logits, shape[H], shared across batches and query positions. Each contributes no value. Supported by in-tree kernels on SM90 for prefill and decode, and on SM89 for FP16/BF16 prefill and decode (without fused RoPE for decode).
Returns:
-
Tensor–Attention output, \([B \times S_q \times H \times D]\), laid out
-
Tensor–like
qand contiguous. Its dtype isout_dtypefor FP8 input, -
Tensor–and the input dtype otherwise.
Raises:
-
ValueError–Shapes, dtypes, devices, or optional-input combinations violate the contract above, or no in-tree kernel serves the call; the message names the limit each kernel refused.
tileops.attention.GQADenseWithLSEFwdOp
¶
Dense Grouped-Query Attention (GQA) forward that also returns each query row's
log-sum-exp, the pair :class:GQADenseBwdOp takes.
It computes the output of :class:GQADenseFwdOp over 16-bit \(Q\)/\(K\)/\(V\) with the
same causal mask, window, score scale and softcap, and adds
the natural-log log-sum-exp of the scaled, capped and masked logits. Its reference is
flash_attn_interface._flash_attn_forward, the forward of FlashAttention-3's
training path; softmax_scale is sm_scale here and causal is is_causal.
The in-tree kernels serve it on SM90 for prefill (\(S_q > 1\)) without a window; any other call is refused when a kernel is selected.
__init__
¶
__init__(
is_causal=False,
window_size_left=-1,
window_size_right=-1,
sm_scale=None,
softcap=None,
*,
target=None
)
Configure the op. Tensor shapes and input dtype come from each call.
Parameters:
-
is_causal(bool, default:False) –Apply the causal mask, bottom-right aligned.
-
window_size_left(int, default:-1) –Keys admitted left of the query row's KV position;
-1means unlimited. -
window_size_right(int, default:-1) –Keys admitted right of it;
-1means unlimited. -
sm_scale(float | None, default:None) –Score scale.
Nonemeans \(1 / \sqrt{D}\), \(D\) the head dimension ofqandkin the current call. A scale whose product with \(\log_2 e\) rounds to zero in FP32 weighs every visible key equally. -
softcap(float | None, default:None) –Positive cap \(c\) replacing each raw score \(z\) with \(c \tanh(z / c)\).
Noneor0disables capping. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
Raises:
-
ValueError–softcapis negative.
forward
¶
Run dense GQA attention and return its output with each row's log-sum-exp.
Parameters:
-
q(Tensor) –Queries, \([B \times S_q \times H \times D]\);
float16orbfloat16. -
k(Tensor) –Keys, \([B \times S_{kv} \times H_{kv} \times D]\), same dtype as
q. -
v(Tensor) –Values, \([B \times S_{kv} \times H_{kv} \times D]\), same dtype as
q.
Returns:
-
Tensor–(o, lse).ois the attention output, \([B \times S_q \times H \times D]\) -
Tensor–in the input dtype.
lseisfloat32, \([B \times H \times S_q]\),-inf -
tuple[Tensor, Tensor]–for a row that sees no key.
Raises:
-
ValueError–Shapes, dtypes or devices violate the contract above, or no in-tree kernel serves the call; the message names the limit each kernel refused.
tileops.attention.GQAPagedFwdOp
¶
Grouped-Query Attention (GQA) over a caller-owned paged KV cache.
Packed Q and its cumulative sequence lengths cover both prefill and decode.
block_table maps logical pages to physical entries in k_cache and
v_cache. This Op reads the cache only: allocation, append, and mutation
remain runtime responsibilities. The in-tree kernels serve a call in which Q
and the cache share a float16 or bfloat16 dtype, or in which the cache, and
optionally Q, is float8_e4m3fn, over any positive page size and any mix of
per-request query lengths, a request with no query token included. Optional
float32 sinks contribute a logit per query head to the softmax denominator only:
they are not scaled or softcapped; -inf disables a sink and +inf makes that
head's output zero. A query row with no visible key returns zero, including when its
sink is disabled. RoPE rotates Q and cached K in NeoX or interleaved layout,
including a partial rotary width. The table must cover every request's cache length.
An FP8 operand is dequantized by its float32 scales: q_scale per request and KV
head, k_scale and v_scale per tensor or per request and KV head. Its stored
values enter the products exactly, in a 16-bit type, and the probabilities stay
16-bit; with an FP8 query the products run in float16 whatever out_dtype is. RoPE
rotates the dequantized query and keys, rounded to the output dtype.
The Hopper RoPE path may allocate up to 512 MiB of temporary storage per call: the rotated Q and rotated key channels (all of the dequantized K and V over an FP8 cache). Under CUDA Graph capture, the graph pool retains that storage. Its allocation is bounded by the page-table and rotary-table extents; preparation writes only live cache pages, including the last page's padding. Calls exceeding this budget use fused rotation without expanded KV storage. Device lengths stay live replay inputs; choosing and preparing this path requires no host readback.
Append with PagedKVCacheWriteFwdOp using physical slots, then read with
post-append lengths. For rotated caches, apply RoPEFwdOp at the token positions to
new Q/K before writing and use pos_encoding_mode="none" to avoid double
rotation. FP8 writes quantize new K/V before attention, so attention reads those
tokens at FP8 precision.
The Hopper FP8-query prefill path keeps up to 64 MiB per call geometry and stream for the partial outputs of short requests whose keys it splits across work items; a captured graph takes its own copy from the graph pool.
The caller guarantees well-formed cu_seqlens_q and in-range block_table and
cache_seqlens, or passes validate_inputs=True, which checks them on the CPU on
every call.
__init__
¶
__init__(
is_causal=False,
window_size_left=-1,
window_size_right=-1,
sm_scale=None,
softcap=None,
out_dtype=None,
pos_encoding_mode="none",
rotary_dim=None,
rope_layout="neox",
*,
validate_inputs=False,
target=None
)
Configure paged GQA semantics without owning or mutating the cache.
Parameters:
-
is_causal(bool, default:False) –Apply a bottom-right-aligned causal mask per request. Default
False, as in flash-attn. -
window_size_left(int, default:-1) –Visible keys to the left;
-1is unlimited. -
window_size_right(int, default:-1) –Visible keys to the right;
-1is unlimited. -
sm_scale(float | None, default:None) –Score scale, or
Nonefor1 / sqrt(D),Dthe head dimension ofqand the keys. -
softcap(float | None, default:None) –Positive score cap;
Noneor zero disables it. -
out_dtype(dtype | None, default:None) –Output dtype, inferred from the input when omitted.
-
pos_encoding_mode(str, default:'none') –"none"or"rope". -
rotary_dim(int | None, default:None) –Even rotated width;
Noneuses the full head dimension. -
rope_layout(str, default:'neox') –"neox"or"interleaved". -
validate_inputs(bool, default:False) –Check on the CPU that
cu_seqlens_qstarts at 0, never decreases and ends at the query token count, and thatblock_tableandcache_seqlenslie in their manifest ranges. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
forward(
q,
k_cache,
v_cache,
block_table,
cache_seqlens,
cu_seqlens_q,
q_scale=None,
k_scale=None,
v_scale=None,
rope_cos=None,
rope_sin=None,
sinks=None,
)
Run read-only paged GQA over packed Q and rank-4 KV pages.
Parameters:
-
q(Tensor) –Packed queries [total_q, heads, dim]. The Hopper warp-specialized prefill reads them in place when each token's heads are packed and the tokens lie a whole number of 16-byte vectors apart, at least a row, as the columns of a fused projection do. Its RoPE preparation, flat rows over one KV head, FP8 caches and the split-scan and decode kernels read a packed copy.
-
k_cache(Tensor) –Key pages [num_pages, page_size, heads_kv, dim].
-
v_cache(Tensor) –Value pages [num_pages, page_size, heads_kv, dim].
-
block_table(Tensor) –Physical page of each request's logical page [batch, pages].
-
cache_seqlens(Tensor) –Each request's cached length, its query tokens included [batch].
-
cu_seqlens_q(Tensor) –Request boundaries in the packed queries [batch + 1].
-
q_scale(Tensor | None, default:None) –Dequantization scale of an FP8 query [batch, heads_kv].
-
k_scale(Tensor | None, default:None) –Dequantization scale of an FP8 key cache.
-
v_scale(Tensor | None, default:None) –Dequantization scale of an FP8 value cache.
-
rope_cos(Tensor | None, default:None) –Rotary cosine table when
pos_encoding_mode='rope'. -
rope_sin(Tensor | None, default:None) –Rotary sine table when
pos_encoding_mode='rope'. -
sinks(Tensor | None, default:None) –Optional float32 logits [heads], added to the softmax denominator only.
Returns:
-
Tensor–The attention output [total_q, heads, dim].
tileops.attention.GQAVarlenFwdOp
¶
Grouped-Query Attention (GQA) over packed THD tensors.
cu_seqlens_q and cu_seqlens_kv delimit each request. The interface
covers both prefill and decode; tensor geometry and sequence metadata come
from each call, while mask, score, out_dtype, and RoPE semantics are fixed at
construction. The BUILTIN path implements 16-bit regular and sliding-window
attention, with or without fused RoPE. Optional float32 sinks contribute a
logit per query head to the softmax denominator only: they are not scaled or
softcapped; -inf disables a sink and +inf makes that head's output zero.
A query row with no visible key returns zero, including when its sink is disabled.
float8_e4m3fn Q/K/V are dequantized by one q_scale, k_scale and
v_scale per request and KV head, and name a 16-bit out_dtype; the FP8
result carries the error of a single e4m3 rounding of the softmax weights, so it
agrees with the 16-bit path to about 2% relative.
By default the op does not check the contents of cu_seqlens_q and
cu_seqlens_kv. The kernels read and write the packed tensors at the positions the
offsets name. Malformed offsets can cause out-of-bounds accesses or incorrect results.
The caller guarantees well-formed offsets, or passes validate_inputs=True, which
checks them on every call at the cost of a device synchronization and cannot run
inside CUDA Graph capture.
__init__
¶
__init__(
is_causal=False,
window_size_left=-1,
window_size_right=-1,
sm_scale=None,
softcap=None,
out_dtype=None,
pos_encoding_mode="none",
rotary_dim=None,
rope_layout="neox",
*,
validate_inputs=False,
target=None
)
Configure packed variable-length GQA semantics.
Parameters:
-
is_causal(bool, default:False) –Apply a bottom-right-aligned causal mask per request. Default
False, as in flash-attn. -
window_size_left(int, default:-1) –Visible keys to the left;
-1is unlimited. -
window_size_right(int, default:-1) –Visible keys to the right;
-1is unlimited. -
sm_scale(float | None, default:None) –Score scale, or
Nonefor1 / sqrt(D),Dthe head dimension ofqand the keys. -
softcap(float | None, default:None) –Positive score cap;
Noneor zero disables it. -
out_dtype(dtype | None, default:None) –Output dtype, inferred from the input when omitted.
-
pos_encoding_mode(str, default:'none') –"none"or"rope". -
rotary_dim(int | None, default:None) –Even rotated width;
Noneuses the full head dimension. -
rope_layout(str, default:'neox') –"neox"or"interleaved". -
validate_inputs(bool, default:False) –Check cumulative offsets against packed tensors on the CPU.
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
forward(
q,
k,
v,
cu_seqlens_q,
cu_seqlens_kv,
q_scale=None,
k_scale=None,
v_scale=None,
rope_cos=None,
rope_sin=None,
sinks=None,
)
Run packed Varlen GQA; Q/K/V use [total_tokens, heads, dim].
Parameters:
-
q(Tensor) –Packed queries, \([T_q \times H \times D]\);
float16,bfloat16orfloat8_e4m3fn. -
k(Tensor) –Packed keys, \([T_{kv} \times H_{kv} \times D]\), same dtype as
q. -
v(Tensor) –Packed values, \([T_{kv} \times H_{kv} \times D]\), same dtype as
q. -
cu_seqlens_q(Tensor) –int32offsets of each request's queries, \([B + 1]\). -
cu_seqlens_kv(Tensor) –int32offsets of each request's keys and values, \([B + 1]\). -
q_scale(Tensor | None, default:None) –FP8 dequantization scales for
q, one per request and KV head, \([B \times H_{kv}]\),float32. The three scales are required together for FP8 input and invalid otherwise. -
k_scale(Tensor | None, default:None) –Scales for
k, \([B \times H_{kv}]\),float32. -
v_scale(Tensor | None, default:None) –Scales for
v, \([B \times H_{kv}]\),float32. -
rope_cos(Tensor | None, default:None) –RoPE cosine table indexed by position and rotated pair, \([P \times R / 2]\) with \(R\) =
rotary_dim(default \(D\)), in the output dtype. The two tables are required together withpos_encoding_mode="rope"and invalid otherwise. -
rope_sin(Tensor | None, default:None) –RoPE sine table, same shape and dtype as
rope_cos. -
sinks(Tensor | None, default:None) –Optional
float32logits, \([H]\), one per query head.
Returns:
-
Tensor–Attention output, \([T_q \times H \times D]\), in
out_dtypewhen given, -
Tensor–else in the dtype of
q.
Multi-Head Latent Attention¶
tileops.attention.MLADenseDecodeFwdOp
¶
Multi-Head Latent Attention (MLA) decode against a per-request KV cache. Layout: BSHD.
The op takes no sm_scale; scores are scaled by (D + PE) ** -0.5, with D and
PE the last extents of q and q_pe.
__init__
¶
Build the op; shapes and dtypes arrive with each call. A subclass with manifest parameters assigns them first and then calls this.
It selects and builds no kernel and reads no device property: an op constructs wherever it is imported, and a device it cannot run on is refused at the first call.
Parameters:
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
Raises:
-
ValueError–A manifest parameter is outside its signature, or an implementation breaks its kernel interface's contract.
-
TypeError–An implementation breaks its kernel interface's contract.
forward
¶
Attend each request's one query token to its whole cache.
Parameters:
-
q(Tensor) –(B, H, D)latent queries, float16 or bfloat16. -
q_pe(Tensor) –(B, H, PE)rope queries in the query dtype. -
k(Tensor) –(B, N_kv, H_kv, D)latent keys, also the values, in the query dtype. -
k_pe(Tensor) –(B, N_kv, H_kv, PE)rope keys in the query dtype.
Returns:
-
Tensor–o(B, H, D)in the query dtype.
tileops.attention.MLADenseBwdOp
¶
Multi-Head Latent Attention (MLA) prefill backward over fixed-length requests, after the latent is decompressed. Layout: BSHD.
Every head has its own D_qk-wide query and key and its own D_v-wide value: the
caller has expanded the shared rope part of the key to every head. o and lse are
the forward's, lse the natural-log log-sum-exp of each query row's scaled scores. Query
i sits at key position i + S_kv - S_q; a query that sees no key has lse
-inf and a zero gradient.
When S_q == S_kv, :class:MLAVarlenFwdOp over B requests of length S feeds it:
o.view(B, S, H, D_v) and lse.view(H, B, S).transpose(0, 1); a call with
S_q != S_kv supplies its own o and lse. The key is the joined
k = cat(k_nope, k_pe broadcast over heads); the gradient of k_pe is
dk[..., DN:] summed over heads.
__init__
¶
Configure the op. Tensor shapes and input dtype come from each call.
Parameters:
-
is_causal(bool, default:False) –Whether a query row reads only keys at or before its own position. Default
False, matching the forward. -
sm_scale(float | None, default:None) –Score scale, or
NoneforD_qk ** -0.5, the query-key head dimension including the rope part. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Back-propagate do through one dense attention call.
Parameters:
-
do(Tensor) –(B, S_q, H, D_v)gradient of the loss with respect too, in the query dtype. -
q(Tensor) –(B, S_q, H, D_qk)queries, float16 or bfloat16. -
k(Tensor) –(B, S_kv, H, D_qk)keys in the query dtype;S_kv > 0. -
v(Tensor) –(B, S_kv, H, D_v)values in the query dtype. -
o(Tensor) –(B, S_q, H, D_v)forward output in the query dtype. -
lse(Tensor) –float32(B, H, S_q)natural-log log-sum-exp of the forward.
Returns:
-
Tensor–dq(B, S_q, H, D_qk),dk(B, S_kv, H, D_qk)anddv -
Tensor–(B, S_kv, H, D_v), in the query dtype.
tileops.attention.MLAPagedFwdOp
¶
Multi-Head Latent Attention (MLA) decode over a paged latent cache, absorbed form.
The cache holds one row per token, kv_c followed by k_pe, shared by every query
head: the key is the whole row and the value its first kv_lora_rank columns. The
S_q query tokens of a request are its last S_q cache positions (one for decode,
more for multi-token prediction drafts). lse is the float32 natural-log log-sum-exp
of each row's scaled scores, (B, H, S_q) head-major as flash-attn returns it, for a
caller merging partial results. With an FP8 cache
the scores and the output are multiplied by kv_scale; the cached values are used
exactly. A cache row past a request's cache_seqlens never reaches a result,
whatever it holds.
__init__
¶
Configure the op. Tensor shapes and dtypes come from each call.
Parameters:
-
kv_lora_rank(int) –Width of the value: the cache row's first columns.
-
is_causal(bool, default:False) –Whether a query token sees only the keys at or before its position. Default
False, as in FlashInfer's MLA wrapper. -
sm_scale(float | None, default:None) –Score scale, or
NoneforDK ** -0.5,DKthe whole cache row width (latent plus rope part). -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Attend each request's query tokens to its cache.
Parameters:
-
q(Tensor) –(B, S_q, H, DK)queries, latent part then rope part, float16 or bfloat16. -
kv_cache(Tensor) –(NP, PS, DK)latent cache in the query dtype or float8_e4m3fn. -
block_table(Tensor) –int32(B, W); keynof requestbis rown % PSof pageblock_table[b, n // PS]. -
cache_seqlens(Tensor) –int32(B,), the keys each request holds. -
kv_scale(Tensor | None, default:None) –float32(1,)dequantization scale, required exactly when the cache is float8_e4m3fn.
Returns:
-
Tensor–o(B, S_q, H, kv_lora_rank)in the query dtype andlse -
Tensor–(B, H, S_q)float32.
tileops.attention.MLAVarlenBwdOp
¶
Multi-Head Latent Attention (MLA) prefill backward over packed requests, after the latent is decompressed. Layout: THD.
Every head has its own D_qk-wide query and key and its own D_v-wide value: the
caller has expanded the shared rope part of the key to every head. Each request attends
only to its own keys. o and lse are the forward's, lse the natural-log
log-sum-exp of each query row's scaled scores, head-major. Query i of a request sits
at key position i + kv_len - q_len; a query that sees no key has lse -inf and
a zero gradient.
When every request's query and key lengths match, :class:MLAVarlenFwdOp feeds it: its
o and lse pass through unchanged; otherwise the caller supplies o and lse.
The key is the joined k = cat(k_nope, k_pe broadcast over heads); the gradient of
k_nope is dk[..., :DN] and that of k_pe is dk[..., DN:] summed over heads.
The caller guarantees well-formed offsets, or passes validate_inputs=True, which
checks them on the CPU on every call.
__init__
¶
Configure the op. Tensor shapes and input dtype come from each call.
Parameters:
-
is_causal(bool, default:False) –Whether a query row reads only keys at or before its own position. Default
False, matching the forward. -
sm_scale(float | None, default:None) –Score scale, or
NoneforD_qk ** -0.5, the query-key head dimension including the rope part. -
validate_inputs(bool, default:False) –Check on the CPU that each offset tensor starts at 0, never decreases and ends at its packed length.
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Back-propagate do through one packed attention call.
Parameters:
-
do(Tensor) –(T_q, H, D_v)gradient of the loss with respect too, in the query dtype. -
q(Tensor) –(T_q, H, D_qk)packed queries, float16 or bfloat16. -
k(Tensor) –(T_kv, H, D_qk)packed keys in the query dtype. -
v(Tensor) –(T_kv, H, D_v)packed values in the query dtype. -
o(Tensor) –(T_q, H, D_v)forward output in the query dtype. -
lse(Tensor) –float32(H, T_q)natural-log log-sum-exp of the forward. -
cu_seqlens_q(Tensor) –int32(B + 1,)request offsets intoq, from 0 toT_q, nondecreasing. -
cu_seqlens_kv(Tensor) –int32(B + 1,)request offsets intokandv, from 0 toT_kv, nondecreasing.
Returns:
-
Tensor–dq(T_q, H, D_qk),dk(T_kv, H, D_qk)anddv -
Tensor–(T_kv, H, D_v), in the query dtype.
tileops.attention.MLAVarlenFwdOp
¶
Multi-Head Latent Attention (MLA) prefill over packed requests, after the latent is decompressed. Layout: THD.
The key of head h is k_nope[:, h] followed by k_pe, which holds one row per
token and is shared by every head. Queries and keys are the same tokens, so one
cu_seqlens describes both and the causal mask sits on the diagonal. lse is
the float32 natural-log log-sum-exp of each row's scaled scores, (H, T_q)
head-major as flash-attn returns it and as :class:MLAVarlenBwdOp takes it.
The caller guarantees well-formed cu_seqlens, or passes validate_inputs=True,
which checks them on the CPU on every call.
__init__
¶
Configure the op. Tensor shapes and input dtype come from each call.
Parameters:
-
is_causal(bool, default:False) –Whether a query row reads only keys at or before its own position. Default
False, as inflash_attn_varlen_func. -
sm_scale(float | None, default:None) –Score scale, or
Nonefor(DN + PE) ** -0.5, the query-key head dimension including the rope part. -
validate_inputs(bool, default:False) –Check on the CPU that
cu_seqlensstarts at 0, never decreases and ends atT_q. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Attend each packed request's queries to its own keys.
Parameters:
-
q(Tensor) –(T_q, H, DN + PE)queries, latent part then rope part, float16 or bfloat16. -
k_nope(Tensor) –(T_q, H, DN)non-rope keys in the query dtype. -
k_pe(Tensor) –(T_q, PE)rope keys, shared by every head, in the query dtype. -
v(Tensor) –(T_q, H, DV)values in the query dtype. -
cu_seqlens(Tensor) –int32(B + 1,)request offsets into the packed tokens, from 0 toT_q, nondecreasing.
Returns:
-
Tensor–o(T_q, H, DV)andlse(H, T_q)float32,-inffor a row -
Tensor–that sees no key.
Native Sparse Attention¶
tileops.attention.NSACompressedVarlenFwdOp
¶
Native Sparse Attention (NSA) compression forward over a ragged batch.
Attends each token to the compressed chunk summaries of its own request and
returns both the output and the log-sum-exp: float32, natural log, (H, T_q)
head-major as flash-attn returns a packed one. A token whose request has closed no
chunk before it sees no key: its output is zero and its log-sum-exp -inf. FLA
writes 0 there and stores token-major (T_q, H).
Sequence layout is packed: cu_seqlens marks the request boundaries, so the batch
size and the chunk count come from the call rather than from construction.
__init__
¶
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
block_size(int) –Compression block size.
-
sm_scale(float | None, default:None) –Softmax scale applied to the QK product, or
NoneforDK ** -0.5. -
validate_inputs(bool, default:False) –Check on the CPU that
cu_seqlensandchunk_offsetsstart at 0, never decrease and end at the token and chunk counts. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Attend each token to its request's compressed chunks.
Parameters:
-
q(Tensor) –Queries, packed over the batch [c_seq_len, heads, dim_k].
-
k_cmp(Tensor) –Compressed keys [chunk_num, head_kv, dim_k].
-
v_cmp(Tensor) –Compressed values [chunk_num, head_kv, dim_v].
-
cu_seqlens(Tensor) –Request boundaries into the packed sequence [seq_num + 1].
-
chunk_offsets(Tensor) –Per-request chunk boundaries [seq_num + 1].
-
token_indices(Tensor) –Request id and in-request position per token [c_seq_len, 2].
Returns:
-
Tensor–(o, lse):o[c_seq_len, heads, dim_v]in the input dtype andlse -
Tensor–[heads, c_seq_len]float32.
tileops.attention.NSATopKVarlenFwdOp
¶
Native Sparse Attention (NSA) block selection over a ragged batch.
Scores each compressed chunk against the query and returns, per token and per KV
head, the selected_block_num block ids the sparse forward will attend to.
Follows FLA: the first, previous and current blocks score one per query head;
other blocks use normalized attention summed across the GQA group. Rank raw
scores descending, with unspecified tie selection/order and trailing -1 padding.
Q is scaled and rounded to its input dtype before the float32 dot product.
Sequence layout is packed: q holds every request's tokens back to back and
cu_seqlens marks the boundaries, so the batch size and the chunk count come from
the call rather than from construction.
__init__
¶
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
selected_block_num(int) –Blocks to keep per token and KV head.
-
block_size(int) –Compression block size.
-
sm_scale(float | None, default:None) –Multiplies Q in its input dtype before the QK product, as in FLA, or
NoneforD ** -0.5. -
validate_inputs(bool, default:False) –Check on the CPU that
cu_seqlensandchunk_offsetsstart at 0, never decrease and end at the token and chunk counts. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Select the blocks each token attends to.
Parameters:
-
q(Tensor) –Queries, packed over the batch [c_seq_len, heads, dim].
-
k_cmp(Tensor) –Compressed keys [chunk_num, head_kv, dim].
-
cu_seqlens(Tensor) –Request boundaries into the packed sequence [seq_num + 1].
-
chunk_offsets(Tensor) –Per-request chunk boundaries [seq_num + 1].
-
token_indices(Tensor) –Request id and in-request position per token [c_seq_len, 2].
Returns:
-
Tensor–Selected block ids [c_seq_len, head_kv, selected_block_num].
tileops.attention.NSAVarlenFwdOp
¶
Native Sparse Attention (NSA) sparse forward over a ragged batch.
Attends each token to the blocks NSATopKVarlenFwdOp selected for it. Sequence
layout is packed: cu_seqlens marks the request boundaries, so the batch size and
the block count come from the call rather than from construction.
A causal token sees the keys of its selected blocks up to its own position, a
non-causal one up to the end of its sequence; a block starting past that bound
contributes nothing, and a token no block gives a key outputs zeros. With
cu_seqlens_k each request's queries are the last of its keys, as in FLA's
parallel_nsa_fwd. A token's slots may come in any order; a slot past its
block_counts, or naming a block that starts past its last visible key (as a padding
id does), selects nothing. The kernels compute in float32, flush subnormals to zero, and
land the softmax weights in the input dtype before they multiply the values, as
FlashAttention does: inputs whose QK products, scaled scores or value sums pass
float32's range are not supported.
__init__
¶
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
block_size(int) –Tokens per selected block.
-
sm_scale(float | None, default:None) –Softmax scale applied to the QK product, or
NoneforD ** -0.5. -
is_causal(bool, default:True) –Whether a token sees keys only up to its own position. Default
True, as FLA'sparallel_nsa, which has no switch. -
validate_inputs(bool, default:False) –Check on the CPU that
cu_seqlensandcu_seqlens_kstart at 0, never decrease and end at the query and key counts, and thatblock_indicesandblock_countslie in their manifest ranges. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Attend each token to its selected blocks.
Parameters:
-
q(Tensor) –Queries, packed over the batch [c_seq_len, heads, dim].
-
k(Tensor) –Keys [c_seq_len, head_kv, dim], or one row per key with
cu_seqlens_k. -
v(Tensor) –Values, shaped as
k. -
block_indices(Tensor) –Selected block ids [c_seq_len, head_kv, selected_blocks].
-
block_counts(Tensor) –Valid block count per token and KV head [c_seq_len, head_kv].
-
cu_seqlens(Tensor) –Request boundaries into the packed sequence [batch + 1].
-
token_indices(Tensor) –Request id and in-request position per token [c_seq_len, 2].
-
cu_seqlens_k(Tensor | None, default:None) –Key boundaries [batch + 1];
Nonemeanscu_seqlens.
Returns:
-
Tensor–Attention output [c_seq_len, heads, dim].
DeepSeek Sparse Attention¶
tileops.attention.DSADenseFwdOp
¶
DeepSeek Sparse Attention (DSA) decode. Layout: BSHD.
With is_causal false only the indices select keys, and -1 pads; attn_sink adds
exp(attn_sink[h]) to head h's softmax denominator.
On SM90 the in-tree kernels serve a value dimension of 512 with a tail of 0 or 64 and a
multiple of 64 heads per kv head, with or without the causal mask and attn_sink.
Otherwise they serve causal calls without attn_sink, with a power-of-two value
dimension and a zero or power-of-two tail dimension, subject to shared-memory limits.
__init__
¶
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
dim_tail(int) –The dimension of the tail portion of the attention vectors.
-
stride_kv(int) –The stride for the key-value sequence.
-
q_start_index_s(int) –The start index for queries in the sequence.
-
sm_scale(float | None, default=None, default:None) –Scaling factor for the softmax function;
Nonemeans(D + dim_tail) ** -0.5, the query-key head dimension including the tail. -
is_causal(bool, default=True, default:True) –Whether an index past the query's position selects nothing.
Falselets the indices alone select keys, asflash_mla_sparse_fwddoes. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Performs the forward pass of the sparse attention operation.
Parameters:
-
q(Tensor) –The query tensor with shape (batch, seq_len, heads, dim + dim_tail).
-
kv(Tensor) –The key-value tensor with shape (batch, seq_len_kv, heads_kv, dim + dim_tail).
-
indices(Tensor) –Indices tensor for sparse attention.
-
attn_sink(Tensor | None, default:None) –float32logits (heads,) that join each head's softmax denominator.
Returns:
-
Tensor–torch.Tensor: The result of applying the sparse attention operation on the input tensors.
tileops.attention.DSAPagedFwdOp
¶
DeepSeek Sparse Attention (DSA) decode over a paged latent cache.
Each query row attends to the cache positions indices names, resolved through the
request's block_table page by page. A uint8 cache row is FlashMLA's
DeepSeek-V3.2 FP8 layout: 512 float8_e4m3fn latent values, one float32 scale per 128 of
them, then 64 bfloat16 rope values. The key is the dequantized latent and the rope; the
value is the dequantized latent. A bfloat16 cache row holds the key, q's width:
the value is its first head_dim_v columns. A position of -1, or at or past
cache_seqlens, is dead. attn_sink adds exp(attn_sink[h]) to head h's
softmax denominator and leaves lse unchanged.
The kernel rounds the dequantized key and the softmax weights to bfloat16 before their
matmuls, which accumulate in float32. lse is the natural-log sum of exponentials of
the scaled scores; a row with no live position returns zeros and lse -inf.
Serves a multiple of 64 heads and a cache below 2^32 bytes: the FP8 cache without
attn_sink and topk a multiple of 64 on SM89 and SM90, and bfloat16 rows of 512
value columns and 0 or 64 more key columns, with any topk, on SM90.
__init__
¶
Build the op. Shapes are taken from each call.
Parameters:
-
sm_scale(float | None, default:None) –Scale of the query-key scores;
Nonemeansq's width to the power -0.5, 576 for the FP8 row. -
head_dim_v(int, default:512) –The value width, the leading columns of the key; 512 for the FP8 row.
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Attend each query row to the cache rows its positions resolve to.
Parameters:
-
q(Tensor) –bfloat16(batch, seq_len, heads, dk). -
kv_cache(Tensor) –uint8(num_pages, page_size, 656)FP8 latent rows, orbfloat16(num_pages, page_size, dk)rows. -
block_table(Tensor) –int32(batch, table_width)page of each page slot. -
cache_seqlens(Tensor) –int32(batch,)cache length of each request. -
indices(Tensor) –int32(batch, seq_len, topk)positions; -1 pads. -
attn_sink(Tensor | None, default:None) –float32(heads,)logits that join each head's softmax denominator.
Returns:
-
Tensor–(o, lse):bfloat16(batch, seq_len, heads, head_dim_v)andfloat32 -
Tensor–(batch, heads, seq_len), the head-major layout flash-attn returns.
KV compression¶
tileops.attention.GatedPoolCompressFwdOp
¶
Pool every ratio positions of each request into one entry, advancing its ring in place.
Per channel, a window's entry is the softmax over its positions of score + ape
(ape indexed by the position's slot in the window) in float32, the weights and their
products with kv rounded to kv's dtype and summed in float32, rounded once to
bfloat16. A window of more than 16 positions with bfloat16 kv sums unrounded float32
products instead, within the entry's bfloat16 tolerance. The kernel flushes float32
subnormals to zero, a ring's score + ape rows among them. With overlap a window also
pools the first D channels of the previous window's positions, its own giving the
last D; the first window has no previous one.
C is 2 with overlap, else 1. Request i holds the packed tokens
cu_seqlens[i]:cu_seqlens[i + 1] at positions from start_pos[i]. The token at
position p with (p + 1) % ratio == 0 closes a window: valid is true at it and
entries holds the window's entry; elsewhere entries is unspecified. Positions
before start_pos[i] come from the ring of slot state_slots[i], row
p % (C * ratio), which holds kv in kv_state and score + ape in
score_state; the call writes the rows of the request's last C * ratio positions.
start_pos[i] 0 starts a request afresh; otherwise it is the end of the request's last
call or one position before it, rolling back the last token it passed. The entries and
the ring rows of a request's tokens do not depend on how the tokens split across calls: a
prefill and then one call a token give exactly what one call of them all gives, and calls
that each pass a token and a draft the next call rolls back give exactly what one call a
token gives. Distinct state_slots are the caller's obligation. The
caller guarantees well-formed cu_seqlens and state_slots in [0, NS), or
passes validate_inputs=True, which checks both on the CPU on every call.
__init__
¶
Build the op.
Parameters:
-
ratio(int) –The positions a window pools.
-
overlap(bool, default:False) –Whether a window also pools the previous window's first
Dchannels,kvandscorethen holding2 * Dchannels. -
validate_inputs(bool, default:False) –Check
cu_seqlensand thestate_slotsrange on the CPU before each call. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Pool the windows the tokens close and write their ring rows.
Parameters:
-
kv(Tensor) –Values
[T_q, C * D],float32orbfloat16;Cis 2 withoverlap, else 1. Any strides: the column halves of one[T_q, 2 * C * D]projection are read where they lie. -
score(Tensor) –Gate logits, as
kv. -
ape(Tensor) –Per-slot gate bias
[ratio, C * D],kv's dtype. -
kv_state(Tensor) –Ring of
kvrows[NS, C * ratio, C * D],float32; written. -
score_state(Tensor) –Ring of
score + aperows, askv_state; written. -
cu_seqlens(Tensor) –Packed offsets of the requests
[N + 1],int32. -
start_pos(Tensor) –Position of each request's first token
[N],int32. -
state_slots(Tensor) –Ring slot of each request
[N],int32.
Returns:
-
Tensor–entries[T_q, D]bfloat16, defined at the closing tokens, and -
Tensor–valid[T_q]bool, true at them.
Attention indexing¶
tileops.attention.FP8LightningIndexerFwdOp
¶
Lightning indexer logits over FP8 index keys.
For query s and key t of group g, the logit sums weights[s, h] times
relu(q[s, h] . k[t, g]) over the heads of group g, for keys inside the query's
window [starts[s], ends[s]). A bf16 call is quantized to FP8 by the op. An FP8 call
passes per-key scales in index_k_scale; k[t, g] is then the FP8 key times its
scale, which may be negative.
__init__
¶
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
clean_logits(bool, default:True) –Set the logits of keys outside a query's window to
-inf; otherwise those slots hold unspecified values. -
assume_nonnegative_scale(bool, default:False) –Skip sign checks on externally supplied key scales. Set this only when every supplied scale is nonnegative. Defaults to
False. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Score every key in each query's window.
Parameters:
-
index_q(Tensor) –Index queries,
(B, S, H, D), bfloat16 or float8_e4m3fn. -
index_k(Tensor) –Index keys,
(B, S_kv, G, D), the dtype ofindex_q;His a multiple ofG. -
weights(Tensor) –Per-head weights,
(S, H), float32. -
starts(Tensor) –First key of each query's window,
(S,), int32 in[0, S_kv]. -
ends(Tensor) –One past the last key of each query's window,
(S,), int32 in[0, S_kv]. -
index_k_scale(Tensor | None, default:None) –Per-key scales of FP8 keys,
(B, S_kv, G), float32; only with float8_e4m3fn inputs.Nonemakes the op quantize the keys.
Returns:
-
Tensor–logits,(B, S, S_kv, G), float32.
Merging attention states¶
tileops.attention.MergeAttentionStatesFwdOp
¶
Merge two attention states using their log-sum-exp weights.
The LSE base is natural by default; lse_base="2" reads and writes log2 LSE, as
FlashInfer's merge_state does. A state with LSE -inf contributes nothing. If
both states are empty, the result is a zero value and LSE -inf, where
merge_state returns NaN. Inputs are read-only.
The LSE keeps merge_state's token-major [tokens, heads] layout. The packed
attention forwards return a head-major [heads, tokens] LSE, as flash-attn does;
pass its transpose.
__init__
¶
Configure the LSE base and implementation target; dimensions are resolved per call.
Parameters:
-
lse_base(str, default:'e') –Logarithm base of the input and output LSE,
"e"or"2". -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Combine normalized values and log partition sums.
Parameters:
-
v_a(Tensor) –First partial value [tokens, heads, dim], FP16 or BF16.
-
s_a(Tensor) –First log-sum-exp in base
lse_base[tokens, heads], FP32. -
v_b(Tensor) –Second partial value, with the same shape and dtype as v_a.
-
s_b(Tensor) –Second log-sum-exp, with the same shape, dtype and base as s_a.
Returns:
-
tuple[Tensor, Tensor]–New (value, LSE) tensors with the respective input shapes and dtypes.
Paged KV Cache¶
tileops.attention.PagedKVCacheWriteFwdOp
¶
Scatter new K/V rows into the page pools in place, the write half of a paged cache.
The slots come from the caller as one flattened row index per token, -1 skipping
the token, so the pages a call writes need not be consecutive, need not be new, and
need not belong to one request: a prefix-caching server reuses a page it already holds
and a chunked prefill writes the pages it was just given. Distinct non-negative
slots below num_pages * page_size are the caller's obligation, and a call writes
nothing outside the slots it names; a slot past the pool writes nothing.
With an FP8 cache the rows are divided by their scale and cast to E4M3FN. NaN is
preserved; finite overflow and infinities saturate to the largest finite magnitude
with the same sign.
__init__
¶
Build the op; shapes and dtypes arrive with each call. A subclass with manifest parameters assigns them first and then calls this.
It selects and builds no kernel and reads no device property: an op constructs wherever it is imported, and a device it cannot run on is refused at the first call.
Parameters:
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
Raises:
-
ValueError–A manifest parameter is outside its signature, or an implementation breaks its kernel interface's contract.
-
TypeError–An implementation breaks its kernel interface's contract.
forward
¶
Write each token's key and value row into the page-pool row its slot names.
Parameters:
-
k(Tensor) –New keys,
(tokens, heads_kv, dim)in float16 or bfloat16. Read where it lies when each token's row is contiguous, as the columns of a fused projection are; copied otherwise. -
v(Tensor) –New values, the same shape and dtype, read as
kis. -
k_cache(Tensor) –The key page pool,
(num_pages, page_size, heads_kv, dim), written in place. Its dtype is the cache dtype: float16, bfloat16, or float8_e4m3fn. -
v_cache(Tensor) –The value page pool, the same shape and dtype, written in place.
-
slot_mapping(Tensor) –int64(tokens,); entrynispage * page_size + offset, the flattened row tokennwrites, or-1to skip it. -
k_scale(Tensor | None, default:None) –float32(1,)divisor of the stored keys, required exactly when the cache is float8_e4m3fn. -
v_scale(Tensor | None, default:None) –The same divisor for the stored values.
Returns:
-
None–None; both page pools are mutated and no other tensor is touched.
tileops.attention.PagedKVCacheGatherFwdOp
¶
Copy ragged cache ranges into out, optionally dequantizing FP8.
FP8 values are dequantized by one FP32 multiply and rounded once to the destination dtype. A non-contiguous destination uses a contiguous staging buffer and a copy back into the caller's view; its previous contents are never read.
The caller guarantees well-formed cu_seqlens and in-range block_table and
seq_starts, or passes validate_inputs=True, which checks them on the CPU on every
call.
__init__
¶
Configure cache gathering; shapes and optional inputs are resolved at each call.
Parameters:
-
out_dtype(dtype | None, default:None) –Destination dtype for FP8 dequantization; otherwise the cache dtype.
-
validate_inputs(bool, default:False) –Check on the CPU that
cu_seqlensstarts at 0, never decreases, ends atout's row count and holds no sequence longer than the tokens ablock_tablerow's pages hold, and thatblock_tableandseq_startslie in their manifest ranges. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Gather each request's logical cache range into its packed destination rows.
Parameters:
-
kv_cache(Tensor) –Contiguous cache \([NP \times PS \times *E]\), FP16, BF16 or FP8 E4M3.
-
block_table(Tensor) –Physical pages of logical request pages, int32 \([B \times W]\).
-
cu_seqlens(Tensor) –Packed destination boundaries, int32 \([B + 1]\).
-
seq_starts(Tensor | None, default:None) –Optional first logical cache position of each request, int32 \([B]\).
-
kv_scale(Tensor | None, default:None) –FP32 \([1]\) dequantization multiplier, required exactly for an FP8 cache.
-
out(Tensor) –Required write-only destination \([T_q \times *E]\), in
out_dtypeor the cache dtype; \(T_q\) iscu_seqlens[-1], which no input shape carries.
Returns:
-
Tensor–out, every element written; the cache is unchanged.
tileops.attention.MLAKVCacheWriteFwdOp
¶
Write the MLA latent and rope key of new tokens into a paged cache, in place.
Each token's row is its kv_c followed by its k_pe, the cache layout of
MLAPagedFwdOp. The slots come from the caller as one flattened row index per token,
-1 skipping the token; distinct non-negative slots are the caller's obligation, and
a call writes nothing outside the rows it names. With fuse_rope the k_pe half of
the row is rotated at the token's position as it is written; k_pe itself is not
modified. Each rotated value is computed in float32 and rounded once to the input dtype,
so it can differ by a step of that dtype from a rotation evaluated in 16-bit arithmetic.
With an FP8 cache the row is divided by kv_scale and cast to E4M3FN. NaN is preserved;
finite overflow and infinities saturate to the largest finite magnitude with the same
sign.
__init__
¶
Build the op; the cache geometry and dtypes arrive with each call.
Parameters:
-
fuse_rope(bool, default:False) –Rotate
k_peatpositionsfromcos_sin_cacheas it is written. The call then passes both tensors. -
rope_layout(str, default:'neox') –Which elements of
k_perotate together:"neox"pairs elementiwithi + PE / 2,"interleaved"pairs2iwith2i + 1. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Write each token's kv_c and k_pe into the cache row its slot names.
Parameters:
-
kv_c(Tensor) –The latent of the new tokens,
(tokens, DC)in float16 or bfloat16. -
k_pe(Tensor) –Their rope keys,
(tokens, PE)in the same dtype. -
kv_cache(Tensor) –The latent cache,
(num_pages, page_size, DC + PE), written in place. Its dtype is the cache dtype: float16 or bfloat16 matchingkv_c, or float8_e4m3fn. -
slot_mapping(Tensor) –int64(tokens,); entrynispage * page_size + offset, the flattened row tokennwrites, or-1to skip it. -
kv_scale(Tensor | None, default:None) –float32(1,)divisor of the stored values, required exactly when the cache is float8_e4m3fn. -
positions(Tensor | None, default:None) –int64(tokens,), thecos_sin_cacherow each token rotates by; required exactly whenfuse_rope. -
cos_sin_cache(Tensor | None, default:None) –(max_position, PE)in float16, bfloat16 or float32: thePE / 2cosines of a position, then itsPE / 2sines; required exactly whenfuse_rope.
Returns:
-
None–None; the cache is mutated and no other tensor is touched.