LeetKernels
ProblemsStart solving
Problems

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:

output[n]=m=0∑n​γn−m⋅dmodel​​Q[n]⋅K[m]​⋅V[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 @ V

Implementation Requirements

  • Implement the solve function; 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:

Q=[11​11​00​00​],K=[10​01​00​00​],V=[44​88​1212​1616​]

Attention scores QK⊤/4​: A=[0.50.5​0.50.5​] Causal decay mask Dnm​=0.5n−m for n≥m, else 0: D=[10.5​01​] Weighted attention A⊙D: [0.50.25​00.5​] Output (A⊙D)V: output=[23​46​69​812​]

Constraints

  • 1 ≤ seq_len ≤ 8,192
  • 1 ≤ d_model ≤ 256
  • 0 < gamma ≤ 1
  • All tensors are float32 on 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) {}

Solve it on your GPU

Previous: Causal Depthwise Conv1dNext: Llama Transformer Block

From LeetGPU, CC BY-NC-ND 4.0.