This is a great question, and it highlights an important distinction between how operations are implemented in the code and how they are conceptually described in the theory of self-attention. Let’s break this down step by step to clarify why attn_scores = queries @ keys.T is present, but queries = x @ W_q is not explicitly written in the code.
1. Understanding the Role of queries, keys, and values in Self-Attention
In the self-attention mechanism, the input tensor x is transformed into three representations: queries (Q), keys (K), and values (V). These transformations are typically described in the theory as matrix multiplications:
- Queries (Q): ( Q = x \cdot W_q )
- Keys (K): ( K = x \cdot W_k )
- Values (V): ( V = x \cdot W_v )
Here, ( W_q ), ( W_k ), and ( W_v ) are weight matrices that project the input x into the query, key, and value spaces, respectively. These projections are essential because they allow the model to learn different representations of the input for the attention mechanism.
2. Why queries = x @ W_q is Not Explicitly Written
In the code, you don’t see an explicit line like queries = x @ W_q because this operation is encapsulated within the nn.Linear layers defined in the __init__ method of the class. Let’s look at the relevant parts of the code:
class SelfAttention_v2(nn.Module):
def __init__(self, d_in, d_out, qkv_bias=False):
super().__init__()
self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
def forward(self, x):
keys = self.W_key(x)
queries = self.W_query(x)
values = self.W_value(x)
...
- The
nn.Linear layers (self.W_query, self.W_key, self.W_value) are PyTorch modules that internally perform the matrix multiplication ( x \cdot W ) (plus an optional bias term).
- When you call
self.W_query(x), it is equivalent to performing x @ W_q (where W_q is the weight matrix of the nn.Linear layer) and adding a bias if qkv_bias=True.
In other words, the line the implementation of , but it’s abstracted into the module for convenience, modularity, and to handle additional details like bias, gradients, and parameter initialization.