Put structure in the mask, and attention gets fast.
Low-rank mask, low cost. Like my diet: just chanterelles.
Structured Masked Attention (SMA)
Masked Attention (MA) is given by the relation [1]
(1)
where is a mask applied to the matrix using the elementwise Hadamard product (denoted by ). When the mask is structured one can most often apply multiplication with efficiently, and we refer to the masked attention as Structured Masked Attention (SMA). In the simplest case of being a lower triangular matrix filled with ones the SMA reduces to
(2)
which can be viewed as a weighted cumulative sum. While the above is a structured computation, it is not efficient unless itself has some structure. An example of when is structured is when it is of low-rank (i.e., ). The resulting SMA is a semiseparable matrix for which multiplication can be applied in linear time [2].
In general if is a low-rank matrix (of rank ) then multiplication with scales as -times the scaling of multiplication with as
(3)
for which we see that we need to perform multiplications with as well as diagonal multiplications.
1using LinearAlgebra2using Random3using Test4Random.seed!(42)5n, p = 10, 26U, V = randn(n,p), randn(n,p)7B = rand(n,n)8M = B .* (U*V')9x = randn(n)10@test M*x โ sum(i -> Diagonal(U[:,i])*(B*(Diagonal(V[:,i])) * x), 1:p)1. State-space models as structured matrices
First we recap that a state-space model is given by the equations
(4)
An alternative way to view the state-space model is through the lens of structured matrices. We take , corresponding to a zero state before the first input. In particular a state-space model up until time step can also be written using block matrices as well as block bidiagonal matrices as
(5)
We know that by simply iterating forwards in time we can compute the states in linear time. For the following generator representation, assume that each transition matrix , , is invertible. A structured representation of the inverse of the bidiagonal matrix can be constructed and applied in linear time for fixed state dimension, using
(6)
This type of matrix structure is called semiseparable [2]. Using this structured representation of we can compute the hidden states efficiently as
(7)
Similarly, the output can be computed by applying the output matrices in a blocked fashion to the hidden states, i.e.
(8)
1using SymSemiseparableMatrices2using BlockBandedMatrices3using LinearAlgebra4using Random5using Test6Random.seed!(42)78T = 10 # Sequence length9n = 6 # State size10input_dim = 1 # Dimension of forcing term1112A_blks = [rand()*I(n) for _ in 1:T-1] # Diagonal dynamics in Mamba 213D_blks = [I(n)/1.0 for i in 1:T] # Diagonal blocks are identity14C_blks = [rand(n,1) for _ in 1:T] # Measurements are scalars15B_blks = [rand(n,input_dim) for _ in 1:T] # Inputs are scalars16# Defining zeros blocks for the matrices17A_zero_blks = [zeros(n,n) for b in A_blks]18C_zero_blks = [zeros(n,1) for _ in 1:T-1]19B_zero_blks = [zeros(n,input_dim) for _ in 1:T-1] 20# Defining the block matrices21A = BlockTridiagonal(-A_blks,D_blks,A_zero_blks)22C = BlockTridiagonal(C_zero_blks,C_blks,C_zero_blks)23B = BlockTridiagonal(B_zero_blks,B_blks,B_zero_blks)2425# Computing states by iterating forward26x_blks = [randn(input_dim) for _ in 0:T-1] # input data27h_blks = [B_blks[1]*x_blks[1]] # initial hidden state28for i in 2:T29 push!(h_blks, A_blks[i-1]*h_blks[i-1] + B_blks[i]*x_blks[i])30end31y_blks = [C'*h for (C,h) in zip(C_blks,h_blks)] 3233# Computing states using semiseparable matrices34Ai_blks = [prod(reverse(A_blks[1:i-1]),init=1.0*I(n)) for i in 1:T]35U = vcat(Ai_blks...)36V = vcat(inv.(transpose.(Ai_blks))...)37# "SymSemiseparableCholesky" represents the matrix A^{-1} = tril(UV') 38Ai = SymSemiseparableCholesky(U', V')39x = vcat(x_blks...) # Collecting input data4041@test Ai*(B*x) โ vcat(h_blks...) # Checking hidden states42@test C'*(Ai*(B*x)) โ vcat(y_blks...) # Checking measurement2. State-space models as SMAs
In this section we aim to derive that the simplified SSM in the Mamba-2 paper is a special case of Structured Masked Attention (SMA) [1], i.e., that the multiplication
(9)
can be written differently as
(10)
The SSM in the Mamba-2 paper restricts the dynamics of to be scalar-times-identity dynamics in order for the mask to be structured [1]. In short this restriction means that the dynamics for all hidden states are independent but equal.
(11)
From a practical point-of-view this means that we can collect each index of the dynamics and treat them separately. The resulting -matrix can be described by a Kronecker product (depending on how we organize the states itโs either or ). In the following we choose to separate the states, resulting in having the form
(12)
For the following scalar generator representation, assume that for . Using that the inverse of a Kronecker product is the Kronecker product of the inverses it follows that
(13)
where we further used that the inverse of a bidiagonal matrix is semiseparable. Furthermore, we have to re-arrange and which results in
(14)
where and denote the th entries of and . The final multiplication will therefore look as
(15)
Finally, using the properties of the Hadamard product we get to the Structured Masked Attention form that we were looking for
(16)
This means that the SSM dynamics can be interpreted as a structured masked attention mechanism. Note that in the case of the dynamics being independent but different (i.e., we would have rather than just ) the SSM dynamics would result in a sum of masked attentions, i.e.,
(17)
1using SymSemiseparableMatrices2using LinearAlgebra3using Random4using Test5Random.seed!(42)67T = 10 # Sequence length8n = 6 # State size910# Here we treat the matrices in terms of their states and not sequence lengths11a_blks = rand(T-1)12a = Bidiagonal(ones(T), -a_blks, :L)13A = kron(I(n),a) # Kronecker product with identity1415# The blocks are now size equal to the sequence and a block for each state!16B_blks = [rand(T) for _ in 1:n]17C_blks = [rand(T) for _ in 1:n] 18# Collecting the blocks into the B and C19B = vcat(Diagonal.(B_blks)...)20C = vcat(Diagonal.(C_blks)...) 2122# We want to see if the full matrix M = C'*(A\B) can be written as23# structured masked attention, i.e.,24# M = (CB')\circ a^{-1}. For this we start by computing a^{-1}25ai = inv(a) # We ignore here that inv(a) is semiseparable26@test C'*(A\B) โ sum(i-> Diagonal(C_blks[i])*ai*Diagonal(B_blks[i]), 1:n)27@test C'*(A\B) โ sum(i->(C_blks[i]*B_blks[i]') .* ai, 1:n)2829# We can collect the terms and write it as Structured Masked Attention!30Cn = hcat(C_blks...)31Bn = hcat(B_blks...)32@test C'*(A\B) โ (Cn*Bn') .* ai3334# We can apply the semiseparable structure of the inverse when multiplying!35ai_blks = [prod(a_blks[1:i-1],init=1.0) for i in 1:T]36u = vcat(ai_blks...)37v = vcat(inv.(ai_blks)...)38# "SymSemiseparableCholesky" represents the matrix A^{-1} = tril(UV') 39ais = SymSemiseparableCholesky(u',v')40# Efficient products using the structure of "ais" and diagonal B and C41x = randn(T)42@test C'*(A\(B*x)) โ sum(i-> C_blks[i].*(ais*(B_blks[i].*x)), 1:n)Cite this post
@misc{paltorp2025structuredmaskedattention, author = {Paltorp, Mikkel}, title = {{Structured Masked Attention (SMA)}}, year = {2025}, month = jul, url = {https://mipals.github.io/pdf/2025/07-28-structured-masked-attention/sma.pdf}, note = {Blog post}}Bibliography
- [1] T. Dao and A. Gu, โTransformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality,โ in International Conference on Machine Learning (ICML), 2024. [Online]. Available: https://arxiv.org/abs/2405.21060
- [2] M. S. Andersen and T. Chen, โSmoothing Splines and Rank Structured Matrices: Revisiting the Spline Kernel,โ SIAM Journal on Matrix Analysis and Applications, vol. 41, no. 2, pp. 389โ412, 2020, doi: 10.1137/19M1267349.