The recurrence looks inherently sequential, but each step is an affine map , and composing affine maps is associative. Representing step by the pair , applying and then is the single pair
so every prefix can be computed with a parallel scan. Write a Triton kernel that computes the recurrence along the last axis of a (rows, L) tensor with tl.associative_scan and this combine function.
Required functions:
@triton.jit
def linear_combine(a1, b1, a2, b2):
@triton.jit
def linear_recurrence_kernel(a_ptr, b_ptr, h0_ptr, h_ptr, L, stride_ar, stride_al, stride_br, stride_bl, stride_hr, stride_hl, HAS_H0: tl.constexpr, BLOCK_L: tl.constexpr):
def linear_recurrence_triton(a, b, h0=None) -> torch.Tensor:
a and b are float32 CUDA tensors of shape (rows, L) with 1 <= L <= 8192; they may be non-contiguous views, so pass their strides. h0 is an optional (rows,) tensor holding the state before the first step; without it the state before the first step is zero.h of shape (rows, L) with .linear_combine receives the earlier element's pair followed by the later element's pair and returns the composed pair as two values.BLOCK_L = triton.next_power_of_2(L) lanes covers the row; lanes at positions >= L must hold the identity element (1, 0).HAS_H0 is set, fold the initial state into the first element before scanning.tl.associative_scan accepts a tuple of blocks and returns a tuple of scanned blocks; the second one is h.(0, 0) would silently zero the carried state.h0_ptr must still be a valid pointer when HAS_H0 is false; any tensor will do, it is never read.num_warps=8.