-
A∈Rs2s1 where s2 and s1 are the index set, for example in a 5D tensor A∈Rijklm a possible index set could be s2={i,j} and s1={k,l,m}.
-
Bs2s1=flashs1(Qs2s1,Ks3s1,Vs3s1) is a flash attention operation over s1 index set of tensor set <Q,K,V>, and the resulting index set is the index set of Q s.t. B∈Rs2s1
Attention Operation
For this exercise we will simplify the target index sets to match the most common setup, i.e. Qs2s1∈R[M×d], Ks3s1∈R[N×d], Vs3s1∈R[N×d]
Note: In this doc, whenever we have to denote the exact dimensions instead of index set it will be denoted as .[...×...×…] where × symbol separates across different index sets.
Thus our operation becomes:
Bs2s1=attentions1(Qs2s1,Ks3s1,Vs3s1)B[M×d]=attentiond(Q[M×d],K[N×d],V[N×d])
S[M×N]=Q@KT=Q∗(M×d,N×d,M×N)K∈R[M×N]SrmaxM=NmaxS[M×N]∈RMSrm[m,n]=S[m,n]−Srmaxm∀[m,n]∈[M×N]P[M×N]=softmaxN(Srm[M×N])O[M×d]=P@V=P∗(M×N,N×d,M×d)V∈R[M×d]
Note: Notation abuse -> O⟺B
Simplifying Forward Pass
P[m,n]=∑nexp(S[m,n]−maxn(S[m,n]))exp(S[m,n]−maxn(S[m,n]))=∑nexp(S[m,n])exp(S[m,n])
Note: The independence over M in softmax the only aggregation is required over N dimension
Computation in chunk
Here we will first look at what is reuired to generate the output for a single query i.e. O[m,d]
O[m,d]=Pm∗(N,N×d,d)V=n∑P[m,n]⋅V[n,d]P[m,n]=softmaxn(S[m,n])=∑nexp(S[m,n])exp(S[m,n])O[m,d]=n∑P[m,n]⋅V[n,d]=n∑∑nexp(S[m,n])exp(S[m,n])⋅V[n,d]=∑nexp(S[m,n])1n∑exp(S[m,n])⋅V[n,d]
We want to process O[m,d]=∑N… over n sequentially to avoid whole sequence loading.
for the sequence just processed till n=j we can write:
Oj[m,d]=∑n∈[0…j]exp(S[m,n])1n∈[0…j]∑exp(S[m,n])⋅V[n,d]=lj1uj
Let’s say we proceed by a single setp n=j+1:
Oj+1[m,d]=∑n∈[0…j,j+1]exp(S[m,n])1n∈[0…j,j+1]∑exp(S[m,n])⋅V[n,d]=lj+exp(S[m,n=j+1])1(uj+exp(S[m,n=j+1])⋅V[n=j+1,d])=lj+1Oj[m,d]∗lj+lj+1exp(S[m,n=j+1])⋅V[n=j+1,d]
Thus we can compute the output simply by iterating over the N dimension for Om,d the final expression
O0[m,d]=l0exp(S[m,n=0])⋅V[n=0,d]Oj+1[m,d]=lj+1Oj[m,d]∗lj+lj+1exp(S[m,n=j+1])⋅V[n=j+1,d]l0=exp(S[m,n=0])lj+1=lj+exp(S[m,n=j+1])
WTF: exp can explode coz of high multiplication values
max operation is used for numerical stability of the softmax especially keeping exp from exploding.
Here next we will try to incorporated this stabilization technique in the above derived framework.
m0=S[m,n=0]mj+1=max(mj,S[m,n=j+1])l0=exp(S[m,n=0]−m0)lj+1=n∈[0…j,j+1]∑exp(S[m,n]−mj+1)lj+1=exp(mj+1−mj)exp(−mj)n∈[0…j]∑exp(S[m,n])+exp(S[m,n=j+1]−mj+1)lj+1=ljexp(mj−mj+1)+exp(S[m,n=j+1]−mj+1)O0[m,d]=l0exp(S[m,n=0]−m0)⋅V[n=0,d]Oj+1[m,d]=lj+1Oj[m,d]∗lj+lj+1exp(S[m,n=j+1]−mj+1)⋅V[n=j+1,d]