Linear time invariant (LTI) state space models (SSM) or S4
Continious form
The state space model is defined by this simple equation. It maps a 1-D input signal x(t) to an N-D latent state h(t) before projecting to a 1-D output signal y(t).
h′(t)y(t)=A⋅h(t)+B⋅x(t)=C⋅h(t)+D⋅x(t)
A∈RN×N,B∈RN×1,C∈R1×N are learnable matrices, comprise the actual parameters of the SSM.
x(t)∈R is the 1-D input signal at time t∈R
Raw audio files, t∈R+, and x(t) is the amplitude at time t
Text token embeddings, t∈Z+, and the SSM is applied independently to each channel
y(t)∈R is the corresponding output of the model at time t∈R
Binary classification, V=1,t∈R+ and y(t)∈{0,1}
State vector h(t)∈RN encapsulates all prior inputs at time t
Discrete form
hkyk=A⋅hk−1+B⋅xk=C⋅hk+D⋅xk
The horizontal bars over SSM metrics indaties discretized parameters. This equation is now a sequence-to-sequence map x∈RL=(x0,…,xL−1)↦y∈RL=(y0,…,yL−1) instead of function-to-function. Moreover the state equation is now a recurrence in hk (hidden state), allowing the discrete SSM to be computed like an RNN.
Learn a “step size” parameter Δ∈R+ (in practice it is learned in the log space) and fixed choices for discretization functions: fA,fB,fC,fD, converts the state matrices into discretized approximations.
ABCD=fA(Δ,A)=fB(Δ,A,B)=fC(Δ,C)=fD(Δ,D)
Bilinear
ABC=(I−Δ/2⋅A)−1(I+Δ/2⋅A)=(I−Δ/2⋅A)−1ΔB=CPython
def discretize(A, B, C, step):
I = np.eye(A.shape[0])
BL = inv(I - (step / 2.0) * A)
Ab = BL @ (I + (step / 2.0) * A)
Bb = (BL * step) @ B
return Ab, Bb, C
你说 State Spaces 离散化我笑.jpg。首先 data dependent 的 decay 完全丧失了 LTI 的性质,非要叫 State Space 多多少少有点强行。其次个人完全不信离散化能有什么用。如果真有用,论文实现里也不至于把B的离散化直接简化成 linear attention 的外积形式了 12
Previous work found that simply modifying an SSM from a random matrix A to HiPPO improved its performance on the sequential MNIST classification benchmark from 60% to 98%.
Python
def make_HiPPO(N):
P = np.sqrt(1 + 2 * np.arange(N))
A = P[:, np.newaxis] * P[np.newaxis, :]
A = np.tril(A) - np.diag(np.arange(N))
return -A
The fundamental bottleneck in computing the discrete-time SSM is that it involves repeated matrix multiplication by A. For example, computing naively involves L successive multiplications by A, requiring O(N2L) matrix multiplications and O(NL) space.
Recall that the kernel has the form:
K=[K0,K1,…,KL−1], where Kj=CAjB∈R
When A is diagonal, A=exp(ΔA) is also diagonal, making the computation nearly trivial. For notational simplicity, let Ci denote the i-th element of vector C (i.e., [C]1,i), Bi denote the i-th element of vector B (i.e., [B]i,1), and Ai denote the i-th diagonal element of A (i.e., [A]i,i).
This calculation can be parallelized by work efficient scan.
[!NOTE]
In Mamba: Structure and Dimensions. Finally, we note that structured SSMs are so named because computing them efficiently also requires imposing structure on the A matrix. The most popular form of structure is diagonal (Gu, Gupta, et al. 2022; Gupta, Gu, and Berant 2022; Smith, Warrington, and Linderman 2023), which we also use.
Mamba SSM
Mamba (S6) removes linear time invariance for B,C,Δ. They’re now functions of xt, i.e. the parameters are selective.
B and C are first parametrized by xt, and then discretized.
Mamba Code Highlight
Fixed Initialization
A initialization
Python
# S4D real initialization# A shape = (d_inner, d_state) / (D, N)
A = repeat(
torch.arange(1, d_state + 1, dtype=torch.float32, device=device),
"n -> d n",
d=d_inner,
).contiguous()
A_log = torch.log(A) # Keep A_log in fp32
A_log = nn.Parameter(A_log)
A_log._no_weight_decay = True
A = -torch.exp(A_log.float()) # (d_inner, d_state)
Default initialization is based on HIPPO theroy, which defines the n-th element of A in the diagonal as −(n+1).
dinner independent A matrices act on each channel of the input x (shape B×dinner×L).
D initialization
Python
# D "skip" parameter# D shape = (D_inner, )
D = nn.Parameter(torch.ones(d_inner, device=device))
D._no_weight_decay = True
dt bias initialization
Python
# Initialize dt bias so that F.softplus(dt_bias) is between dt_min and dt_max
dt = torch.exp(
torch.rand(self.d_inner, **factory_kwargs) * (math.log(dt_max) - math.log(dt_min))
+ math.log(dt_min)
).clamp(min=dt_init_floor)
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
inv_dt = dt + torch.log(-torch.expm1(-dt))
with torch.no_grad():
self.dt_proj.bias.copy_(inv_dt)
# Our initialization would set all Linear.bias to zero, need to mark this one as _no_reinitself.dt_proj.bias._no_reinit = True
Forward
Python
batch, seqlen, dim = hidden_states.shape
# in_proj shape = (d_inner * 2, d_model)# hidden_states shape = (batch, seqlen, dim)# xz shape = (batch, d_inner * 2, seqlen), x and z are concatenated
xz = rearrange(
in_proj.weight @ rearrange(hidden_states, "b l d -> d (b l)"),
"d (b l) -> b d l",
l=seqlen,
)
Python
# x, z shape both are (batch, d_inner, seqlen)
x, z = xz.chunk(2, dim=1)
# x.shape = (batch, d_inner, seqlen)
x = act(conv1d(x))[..., :seqlen]
# x_dbl.shape = (batch * seqlen, dt_rank + d_state * 2)
x_dbl = x_proj(rearrange(x, "b d l -> (b l) d"))
# dt.shape = (batch * seqlen, dt_rank), B.shape = C.shape = (batch * seqlen, d_state)
dt, B, C = torch.split(x_dbl, [dt_rank, d_state, d_state], dim=-1)
# After projection, dt.shape = (d_inner, batch * seqlen)
dt = dt_proj.weight @ dt.t()
# dt.shape = (batch, d_inner, seqlen)
dt = rearrange(dt, "d (b l)-> b d l", l=seqlen)
B = rearrange(B, "(b l) dstate -> b dstate l", l=seqlen).contiguous()
C = rearrange(C, "(b l) dstate -> b dstate l", l=seqlen).contiguous()
y = selective_scan_ref(
x,
dt,
A,
B,
C,
D.float(),
z=z,
delta_bias=dt_proj.bias.float(),
delta_softplus=True,
return_last_state=True,
return_last_state=ssm_state is not None,
)
DiscretizeA. Mamba takes A of the ZOH form, which is exp(ΔA). Δ 在 N 维度广播(对 state space 每个维度施加相同步长)。对输入 x(t),每个维度独立的进行 SSM,A 有独立的 D 份,乘上 B 维度和 L 维度的步长,得到 A
[!NOTE]
Mamba: We remark that while the A parameter could also be selective, it ultimately affects the model only through its interaction with Δ via A=exp(ΔA) (the discretization). Thus selectivity in Δ is enough to ensure selectivity in (A,B), and is the main source of improvement. We hypothesize that making A selective in addition to (or instead of) Δ would have similar performance, and leave it out for simplicity.
先是 Δ=(B,D,L) 与 B=(B,N,L) 广播乘法,得到 B=(B,D,N,L),对 state space 每个维度施加相同步长,然后相当于得到了 B×D×L 个 B (每个的维度都是 N),然后再与 B×D×L 个 scaler x(t) 单独计算
Scan!!!
Python
for i in range(u.shape[2]): # L# ith [B, D, N] * [B, D, N] + ith [B, D, N]
x = deltaA[:, :, i] * x + deltaB_u[:, :, i]
y = torch.einsum('bdn,bn->bd', x, C[:, :, i])
if i == u.shape[2] - 1:
last_state = x
ys.append(y)
由于 A (以及 A(xt)) 已经是 diagonal, A(xt)⋅ht 也为 element wise product
Final Post Processing
Python
# y.shape = (B, D, L)
y = torch.stack(ys, dim=2)
# skip connection
out = y + u * rearrange(D, "d -> d 1")
out = out * F.silu(z)
CUDA work efficient scan
Tri Dao, FlashAttention, introduced hardware accelerated self-attention, bringing memory requirements from quadratic to linear and also provideing dramatic wall-clock time speedups.
The Blelloch parallel scan
For any binary associative operators, we have a parrallel scan for prefix ops.
(ci∗cj)∗ckApply the definition of ∗ :=[aj⊙ai,(aj⊗bi)⊕bj]∗ckApply the definition of ∗ again :=[aj⊙ai,(aj⊗bi)⊕bj]∗[ak,bk]=[ak⊙(aj⊙ai),(ak⊗((aj⊗bi)⊕bj))⊕bk]Associativity of ⊙ :=[(ak⊙aj)⊙ai,(ak⊗((aj⊗bi)⊕bj))⊕bk]⊗ distributes ak over ⊕ :=[(ak⊙aj)⊙ai,((ak⊗(aj⊗bi))⊕(ak⊗bj))⊕bk]Associativity of ⊕ :=[(ak⊙aj)⊙ai,(ak⊗(aj⊗bi))⊕((ak⊗bj)⊕bk)]Semi-associativity of ⊗ :=[(ak⊙aj)⊙ai,((ak⊙aj)⊗bi)⊕((ak⊗bj)⊕bk)]Apply the definition of ∗ :=[ai,bi]∗[ak⊙aj,(ak⊗bj)⊕bk]=ci∗(cj∗ck)
We now difine the ordered set
si=[pi,xi]=[a production,{b} segment]
In the case of Mamba, Set s0=[p0,x0]=[A,h0]=c0, and we have s1=[p1,x1]=[A2,Ah0+B(x1)⋅x1]=[A,h0]∗[a1,b1]=s0∗c1.
# Various importsfrom einops import einsum
import jax
# Jax.lax already has a convenient parallel scan implementation.import jax.lax as lax
import jax.numpy as jnp
key = jax.random.PRNGKey(seed=42)
B = 1 # batch size
L = 8192 # context length
N = 64 # hidden state size
D = 2 # num in channels
V = 1 # num out channels# Gets the various fake x_t inputs.def generate_random_xs(key, num_inputs=L, num_channels=D):
key, subkey = jax.random.split(key)
xs = jax.random.lognormal(subkey, shape=(L, D))
return key, xs
# Gets various fake A matrices. This isshape= actually constant in the paper,# but it doesn't have to be.def generate_random_As(key, num_inputs=L, state_size=N):
key, subkey = jax.random.split(key)
As = jax.random.lognormal(subkey, shape=(L, N, N))
return key, As
# Gets various fake B(x_t) matrices.def generate_random_Bxs(key, num_inputs=L, state_size=N, num_channels=D):
key, subkey = jax.random.split(key)
Bxs = jax.random.lognormal(subkey, shape=(L, N, D))
return key, Bxs
# Gets the b_t term.def get_bs(xs, Bxs):
return einsum(Bxs, xs, "l n d, l d -> l n")
# Jax plays nicest with jnp.arrays, so we'll stuff the values inside a# single array and just unpack things here. I suppose I could use PyTrees# but please forgive a bit of laziness/hackiness on my part.def extract(c, state_size):
assert c.ndim == 1assert c.shape[0] == state_size * state_size + state_size
return (
c[:state_size * state_size].reshape((state_size, state_size)),
c[-state_size:].reshape((state_size,))
)
The operator implementation and test logic
Python
def operator(c_prev, c_curr, num_inputs=L, state_size=N, num_channels=D):
prev_a, prev_b = extract(c_prev, state_size)
curr_a, curr_b = extract(c_curr, state_size)
return jnp.concatenate([
jnp.ravel(curr_a @ prev_a),
jnp.ravel(curr_a @ prev_b + curr_b)
])
vectorized_operator = jax.vmap(operator, in_axes=(0, 0), out_axes=0)
# Actually generate some fake test data.
key, xs = generate_random_xs(key)
key, Bxs = generate_random_Bxs(key)
key, As = generate_random_As(key)
bs = get_bs(xs, Bxs)
cs = jnp.concatenate([As.reshape(-1, N * N), bs], axis=1)
# %%timeit results on a freebie Google Colab VM:# 283 ms ± 16.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
lax_scanned = lax.associative_scan(vectorized_operator, cs)[:, -N:]
def naive_scan_hs(h_0, As, Bxs, xs):
output = [h_0]
for a, bx, x in zip(As, Bxs, xs):
b = einsum(bx, x, "n d, d -> n")
output.append(a @ output[-1] + b)
return output[1:]
# %%timeit results on a freebie Google Colab VM:# 3.34 s ± 313 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
naive_hs = jnp.vstack(
naive_scan_hs(jnp.zeros((N,)), As, Bxs, xs)
)
# The following returns Array(True, dtype=bool)! Which means that# we're getting identical results, (allowing for some floating point# imprecision), regardless of if we're using the naive iterative# implementation, or the fast parallel implementation.
jnp.allclose(naive_hs, lax_scanned)
Vision Mamba
Vim
VMamba
LocalMamba
Mamba2
[!TIP]
(剧透)大家可以期待一下之后变得越来越像Linear Attention的Mamba2,通过shared data-dependent decay for each head写成matmul的方式来继续scale up N(越来越像RetNet/GLA了)