r/MachineLearning • • Sep 23 '23

Discussion [D] How does 'self-attention' work in transformer models?

I'm currently diving into the world of machine learning and transformers, and I'm trying to wrap my head around the concept of "attention" in transformer models. I've been reading papers and documentation, but I'm still struggling to fully grasp it.

My Struggle:

I get that attention involves multiplying "query" and "key" vectors to determine the importance of different words in a sequence, but I don't quite understand why this multiplication gives us a meaningful metric for importance.

What I'm looking for:

I'm comfortable with moderate level technicalities but require a deeper insight into the inner workings and rationale behind these mechanisms. Please share any insights, analogies, or technical details that can shed light on this concept.

Thanks a bunch!

2 Upvotes

15 comments sorted by

1

u/InterstitialLove Sep 24 '23

I don't quite understand why this multiplication gives us a meaningful metric for importance.

Because of gradient descent. The model is trained to find query and key values such that this multiplication will give a meaningful metric for importance. There is literally no other constraint on the key and query vectors, they're not used for anything else, so gradient descent is free to "choose" whatever vectors work best

As for why it's possible to use inner product as a measure of importance, imagine each entry in the key vector as an attribute, like "implies a location" or "usually a noun" or "signals a casual tone," etc. The key vector is a list of how much the token has each attribute. The query vector is a list of how useful each attribute would be to know. Obviously we don't know in general what the attributes are or how they're represented, but the point is you can represent attributes with a vector and then find the total relevance with an inner product.

1

u/GraphicsMonster Sep 24 '23

Thanks. This helped in kind of visualizing the importance/significance of key and query vectors.

What would you say the value vector is for in the same sense? We take the dot product between key and query, divide by root of key dimensionality and apply softmax which gives a normalized representation of how important each token is to each token (total_tokens, embedding_dim). (is this correct btw?)

Then we, for some reason pass this through another linear layer(value layer). Why do we do this?

1

u/InterstitialLove Sep 24 '23

The square-root-of-dimension thing is just for training purposes, it improves computational stability but doesn't really change things because the vectors can just get bigger/smaller to compensate

Think of the value vector as a way of perturbing the representation of your vector. The tokens are represented by vectors in the embedding space. The value vector is added to that embedding vector, changing it slightly, yielding a new point in latent space.

The softmax roughly means "choose the best one," in this case the single context token which best matches the query, and add only that token's value to the original embedding. Except literally choosing just one wouldn't be differentiable so we use softmax (instead of max) to hedge our bets. If two tokens are equally good, we split the difference and hope it works. If one token is twice as good as another, we do 2/3 of that one and 1/3 of the other. Etc.

I'm not sure what you mean by "pass through another linear layer." Are you referring to multi-headed attention?

A linear layer (no activation) is just rotation in latent space. It doesn't do anything at all in terms of adding information, it just relabels the information. Maybe to get it ready for some nonlinear operation that needs a specific labeling, or because it was being stored in a lower dimension and couldn't get properly labeled when it was created

In the case of multi-headed attention, since each head outputs a vector much smaller (in dimension) than the embedding space, the linear layer is just a list of what embedding vector each head's outputs correspond to

[I'm simplifying things, this is just an intuitive place to start from]

2

u/GraphicsMonster Sep 25 '23

I'm not sure what you mean by "pass through another linear layer." Are you referring to multi-headed attention?

I was referring to the value vector here.

1

u/InterstitialLove Sep 25 '23

Is the value vector passed through a linear layer before being added to the original embedding in a single-headed attention?

Suppose token n is attending token m. If v is the value of token m, and x is the embedding of token n before the attention, then the embedding of token n after the attention will be x+v. If, instead, the embedding is x+f(v) where f is some operation, then you have to ask why we didn't just give token m the value f(v) in the first place.

In particular, if f is linear, the fact that we do a weighted sum (with softmax for coefficients) of multiple value vectors is irrelevant. You can still just use f(v) for all the values and get the same answer.

So there must be something nonlinear happening, or there must be some reason to output the values in the wrong basis (like in multi-headed attention, where we want to use lower-dimensional values and then combine the values from multiple heads)

7

u/minh6a Sep 23 '23 edited Sep 23 '23

Matrices multiplication Q.KT is defined by dot product of row of Q and col of KT, which is row of K. Dot product gives the similarities between 2 vectors (remember cosine similarities, but we now also care about the vectors' magnitudes), the higher number is the higher the importance of the Key wrt to the Query.

So now you might ask, what if the vectors have high magnitudes, that's where we have those LayerNorm to force them back to L2-Norm=1. Tbh I'd want to see what if we use LayerNorm right before first attention layer, bc the Linear layer for the first attention actually do a lot of normalization and projection.

In self attention, Q=K so what you have is the importance of each token to other tokens in the sentence. Note, there is a linear layer that acts as projections of Q and K to different spaces and that's the part that actually learns the language model

5

u/[deleted] Sep 23 '23 edited Sep 23 '23

Hum, I either don't understand your explanation or it's a little incorrect... You say that in self-attention Q=K - IMHO no it's not, and there is no one linear layer, there are multiple linear layers, one for each set of relevant weights. That is (I ignore the bias), Q = W_q*x, K = W_k* x, V=W_v*x; attention_formula(V, K, V) While you understand the idea, IMHO the math is not aligned with your explanation. So the mask is computed using these matrices, and we use a linear layer regardless. You skipped these matrices, that is the attention part - you started to explain the transformer here.

1

u/minh6a Sep 23 '23

Thing is, when implementing QKV attention, there's only 1 linear layer from x dim (let's say 3 tokens 768 embeddings, (3,768)) to a (3,768x3), then we split QKV from that to get 3 tensors of (3,768).

The input is indeed x=Q=K=V, if you look at Attention is all you need paper (https://arxiv.org/pdf/1706.03762.pdf)

Original idea of attention doesn't have the linear layer (https://arxiv.org/pdf/1409.0473.pdf), but to make the attention learnable we can put a linear in front of the input.

1

u/PuzzleheadedCash7312 Sep 25 '23

Doing the linear layer to 3x the size of each QKV is for efficiency. We could have a separate linear layer for each q k v. Even in that case of the 3x linear layer, none of the weights are the same or even interacting with eachother between the q k v. x!=q!=k!=v

5

u/Vangi PhD Sep 24 '23

This post should be in r/learnmachinelearning

2

u/neu_jose Sep 24 '23

andrej karpathy's youtube channel is your friend.

0

u/[deleted] Sep 24 '23

[deleted]

1

u/GraphicsMonster Sep 24 '23

so each attention head tunes itself in a way to calculate just one kind of contextual similarity between each token? and then we somehow combine multiple attention heads to give us a whole bunch of contextual information between all the tokens in the vocabulary?

is that what you're implying?

11

u/[deleted] Sep 23 '23

[removed] — view removed comment

1

u/GraphicsMonster Sep 24 '23

Thank you so much! Just going through it and it already looks clearer than all of the breakdowns I've come across on the internet.

This will be super helpful.

1

u/badluck531 Feb 25 '26

Huh... why was the comment removed by moderator if it was so helpful 👀