LeetKernels
ProblemsStart solving
Problems

53. Causal Self-Attention hard

Implement Causal (masked) Self-Attention for a given set of matrices. Given the query matrix Q of size M×d, key matrix K of size M×d, and value matrix V of size M×d, your program should compute the output matrix using the formula: Attentioncausal​(Q,K,V)=softmax(masked(d​QKT​))V

where mask is a causal mask that sets all positions corresponding to keys after the current query to −∞. $$ i.e., for query <code>i</code> and key <code>j</code>: \text{masked}(a_{ij}) = \begin{cases} a_{ij}, & j \le i \\ -\infty, & j > i \end{cases} $$ The softmax function is applied row-wise. Q, K, V, and output are all of data type float32; M, and d are of data type int32.

key position → query → 0 1 2 3 4 5 0 1 2 3 4 5 ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ -∞ attend masked

Implementation Requirements

  • Use only native features (external libraries are not permitted)
  • The solve function signature must remain unchanged
  • The final result must be stored in the output matrix output

Example 1:

Input:
Q (2×4): [1.00.0​0.01.0​0.00.0​0.00.0​] K (2×4): [1.00.0​0.01.0​0.00.0​0.00.0​] V (2×4): [1.05.0​2.06.0​3.07.0​4.08.0​]

Output:
output (2×4): [1.03.4898374​2.04.4898374​3.05.4898374​4.06.4898374​]

Example 2:

Input:
Q (2×2): [0.01.0​0.01.0​] K (2×2): [1.00.0​0.01.0​] V (2×2): [3.05.0​4.06.0​]

Output:
output (2×2): [3.04.0​4.05.0​]

Constraints

  • Matrix Q, K, and V are all of size M×d
  • 1 ≤ M ≤ 10000
  • 1 ≤ d ≤ 128
  • All elements in Q, K, and V are sampled from[-1.0, 1.0]
  • Data type for all matrices is float32
  • Performance is measured with M = 5,000

Starter code (CUDA)

#include <cuda_runtime.h>

// Q, K, V, output are device pointers
extern "C" void solve(const float* Q, const float* K, const float* V, float* output, int M, int d) {

}

Solve it on your GPU

Previous: Sigmoid Linear UnitNext: Swish-Gated Linear Unit

From LeetGPU, CC BY-NC-ND 4.0.