LeetKernels
ProblemsStart solving
Problems

82. Linear Recurrence medium

Given two matrices a and x, each of shape [B, L] (batch size × sequence length), compute the linear recurrence h of shape [B, L] defined by: h[b, 0] = x[b, 0] and h[b, t] = a[b, t] × h[b, t−1] + x[b, t] for t ≥ 1. All values are float32. This operation is the core computational primitive of State Space Models (SSMs) such as Mamba, S4, and H3.

Linear Recurrence: h[t] = a[t] · h[t-1] + x[t] h[0] h[1] h[2] h[3] ×a[1] ×a[2] ×a[3] x[0] x[1] x[2] x[3] + + + + …

Implementation Requirements

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

Examples

Example 1 — exponential decay (a = 0.5, single impulse):

a=[0.5​0.5​0.5​0.5​],x=[1.0​0.0​0.0​0.0​] h=[1.0​0.5​0.25​0.125​]

Example 2 — prefix sum (a = 1, unit inputs):

a=[1.0​1.0​1.0​1.0​],x=[1.0​1.0​1.0​1.0​] h=[1.0​2.0​3.0​4.0​]

Full example with B = 2, L = 4:

a=[0.51.0​0.51.0​0.51.0​0.51.0​],x=[1.01.0​0.01.0​0.01.0​0.01.0​] h=[1.01.0​0.52.0​0.253.0​0.1254.0​]

Constraints

  • 1 ≤ B ≤ 256 (batch size)
  • 1 ≤ L ≤ 65,536 (sequence length)
  • All values in a and x are float32
  • Performance is measured with B = 64, L = 16,384

Starter code (CUDA)

#include <cuda_runtime.h>

// a, x, h are device pointers
extern "C" void solve(const float* a, const float* x, float* h, int B, int L) {}

Solve it on your GPU

Previous: INT4 Weight-Only Quantized MatMulNext: SwiGLU MLP Block

From LeetGPU, CC BY-NC-ND 4.0.