92. Decaying Causal Attention medium
Implement decaying causal attention. Given query matrix Q, key matrix K,
and value matrix V, each of shape seq_len × d_model, and a scalar
decay factor gamma ∈ (0, 1], compute the unnormalized causal attention output
where position n attends to all past positions m ≤ n with weight
gamman−m:
Unlike standard softmax attention, there is no normalization — the weights decay geometrically from the current position backward. This is the parallel form of the Retention mechanism (RetNet), used as a recurrence-friendly alternative to attention in sequence models.
Causal Decay Mask D[n,m] = γ^(n−m) m=0 m=1 m=2 m=3 n=0 n=1 n=2 n=3 1 γ 1 γ² γ 1 γ³ γ² γ 1 Computation Q [S, D] query K [S, D] key V [S, D] value QKᵀ / √D attn scores [S,S] ⊙ decay mask weighted [S,S] lower triangular @ output [S, D] weighted @ VImplementation Requirements
- Implement the
solvefunction; do not change its signature. - Do not use external libraries beyond those provided.
- Write the result into
output.
Example
Example 1 — with seq_len = 2, d_model = 4, gamma = 0.5:
Attention scores : Causal decay mask for , else : Weighted attention : Output :
Constraints
- 1 ≤
seq_len≤ 8,192 - 1 ≤
d_model≤ 256 - 0 <
gamma≤ 1 - All tensors are
float32on GPU. - Performance is measured with
seq_len= 4,096,d_model= 64
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 seq_len,
int d_model, float gamma) {}
From LeetGPU, CC BY-NC-ND 4.0.