Triton Single-Query Attention Kernel
Problem Statement
Implement scaled dot-product attention for a single query against N keys/values of dimension D (small enough to fit one block). Compute out = softmax(q · Kᵀ / sqrt(D)) @ V, a length-D vector.
Background
This is a compact version of the fused-attention tutorial. Steps: load q (D,) and K (N, D); scores = sum(K * q, axis=1) * scale; stable softmax over the N scores; weighted sum of V (N, D) rows by the attention weights.
Your Task
Implement attention_kernel and run(N=64, D=32) comparing to a torch reference.
How it is tested
Your solution must define a top-level function run(...) that allocates inputs on the GPU, launches your Triton kernel, and returns a boolean from torch.allclose(triton_out, torch_reference, ...). The grader prints run(...); the expected output is True.
Example
N = 64, D = 32
True
- The input values
N = 64andD = 32are used to allocate inputsq,K, andVon the GPU, withqbeing a vector of lengthDandKandVbeing matrices of sizeN x D. - The attention scores are computed as
scores = sum(K * q, axis=1) * scale, wherescale = 1 / sqrt(D), resulting in a vector of lengthNwith scores representing the similarity betweenqand each row ofK. - A stable softmax function is applied to the attention scores, producing a probability distribution over the
Nkeys: . - The final output is computed as the weighted sum of the rows of
Vusing the softmax probabilities, and the result is compared to a PyTorch reference implementation usingtorch.allclose, yielding the outputTrueif the results match within a certain tolerance.
Constraints
- Single program (grid = (1,)) handling one query vs N keys
- scale = 1/sqrt(D); stable softmax over the N scores (subtract max)
- out[d] = sum_n weight[n] * V[n, d]