The impact of normalization in the Transformer architecture
Deep Learning
Transformers
Mathematics
Over the last few months I have been studying the Deep Learning book by Christopher Bishop and Hugh Bishop. While studying the Transformer architecture (which I find fascinating for the many mathematical principles behind it, but I’ll leave that for other posts) I realized that when using the softmax function in the attention layer, it is extremely important for the inputs to be normalized. That sparked my curiosity about why, and it is the origin of this post.
When we talk about attention, we are talking about a concept where (in the world of words) we capture the semantic nature of each word with respect to all the others, within the context of a sentence.
12.1.5 Scaled Self-Attention
There is a small refinement we need to make to the self-attention layer. Recall that the gradients of the softmax function become exponentially smaller for inputs of large magnitude.
Proof
For an input:
z=[z1,…,zk]
We have:
P=Softmax(z)=∑j=1kezjezi
If we take:
Pi=Softmax(zi)=∑j=1kezjezi
Then, for P1:
P1=ez1+⋯+ezkez1
Now we want to know how much P1 changes with respect to z1:
∂z1∂P1
In the previous equation we can replace the denominator with:
S=ez1+⋯+ezk
Then:
P1=Sez1
or:
P1=ez1S−1
Now we apply the product rule:
∂z1∂P1=∂z1∂ez1S−1+ez1∂z1∂S−1
Taking into account:
∂x∂ex=ex
and:
∂x∂x−1=−x−2
We get:
∂z1∂P1=ez1S−1−ez1S−2∂z1∂S
But:
S=ez1+⋯+ezk
therefore:
∂z1∂S=ez1
Substituting:
∂z1∂P1=ez1S−1−ez1S−2ez1
Then:
∂z1∂P1=Sez1−S2e2z1
But:
P1=Sez1
and:
P12=S2e2z1
Therefore:
∂z1∂P1=P1−P12
Finally:
∂z1∂P1=P1(1−P1)
Now let’s see what happens.
If:
P1=1
then:
∂z1∂P1=1(1−1)≈0
If:
P1=0.99
then:
∂z1∂P1=0.99(1−0.99)=0.0099
That is, when P1 approaches 1, the gradient approaches 0.
Now let’s bring this to self-attention.
In self-attention we compute the scores:
QKT
If the vectors have a large magnitude, these scores can also have a large magnitude.
When these values go through softmax, we can end up with probabilities very close to 0 and 1.
For example:
P=[0.001,0.998,0.001]
At this point the function is saturated and its gradients are small.
That is why we make a small refinement:
Softmax(dkQKT)
We divide the scores by dk.
This reduces their magnitude before applying softmax.
With this we keep softmax from saturating so easily.
And that is where the name comes from:
Scaled Self-Attention.
The idea is quite simple:
large scores→saturated softmax→small gradients
That is why we need to scale the scores before applying softmax.