PIXELBANKv9.1.0
Menu

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:

Input:
N = 64, D = 32
Output:
True
Reasoning:
  • The input values N = 64 and D = 32 are used to allocate inputs q, K, and V on the GPU, with q being a vector of length D and K and V being matrices of size N x D.
  • The attention scores are computed as scores = sum(K * q, axis=1) * scale, where scale = 1 / sqrt(D), resulting in a vector of length N with scores representing the similarity between q and each row of K.
  • A stable softmax function is applied to the attention scores, producing a probability distribution over the N keys: softmax(scores)=exp(scores)โˆ‘i=1Nexp(scoresi)softmax(scores) = \frac{exp(scores)}{\sum_{i=1}^{N} exp(scores_i)}.
  • The final output is computed as the weighted sum of the rows of V using the softmax probabilities, and the result is compared to a PyTorch reference implementation using torch.allclose, yielding the output True if 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]
๐Ÿ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Triton Single-Query Attention Kernel - Hard | PixelBank