Coding attention mechanisms¶
import torch
inputs = torch.tensor(
[[0.43, 0.15, 0.89], # Your (x^1)
[0.55, 0.87, 0.66], # journey (x^2)
[0.57, 0.85, 0.64], # starts (x^3)
[0.22, 0.58, 0.33], # with (x^4)
[0.77, 0.25, 0.10], # one (x^5)
[0.05, 0.80, 0.55]] # step (x^6)
)
The token we want to relate to every other token is the query token. The simplest form of attention is to calculate the dot product between the query token and the other token. This value is conventionally indicated with $\omega$.
# Use the second token as our query token.
query_token = inputs[1]
print(f"Query token: {query_token}")
Query token: tensor([0.5500, 0.8700, 0.6600])
# Store attention scores for second input token as query token,
# use a tensor equal in length to the input tokens tensor.
attention_scores2 = torch.empty(inputs.shape[0])
# Calculate the attention scores
for i, input_token in enumerate(inputs):
attention_scores2[i] = query_token @ input_token
print(f"{i}: {input_token} -> {attention_scores2[i]:.4}")
0: tensor([0.4300, 0.1500, 0.8900]) -> 0.9544 1: tensor([0.5500, 0.8700, 0.6600]) -> 1.495 2: tensor([0.5700, 0.8500, 0.6400]) -> 1.475 3: tensor([0.2200, 0.5800, 0.3300]) -> 0.8434 4: tensor([0.7700, 0.2500, 0.1000]) -> 0.707 5: tensor([0.0500, 0.8000, 0.5500]) -> 1.087
# We can doublecheck that a dot product is just an elementwise product followed by summation.
def dot_product(a, b):
result = 0
for i, j in zip(a, b):
result += i*j
return result
for i, input_token in enumerate(inputs):
attention_scores2[i] = dot_product(query_token, input_token)
print(f"{i}: {input_token} -> {attention_scores2[i]:.4}")
0: tensor([0.4300, 0.1500, 0.8900]) -> 0.9544 1: tensor([0.5500, 0.8700, 0.6600]) -> 1.495 2: tensor([0.5700, 0.8500, 0.6400]) -> 1.475 3: tensor([0.2200, 0.5800, 0.3300]) -> 0.8434 4: tensor([0.7700, 0.2500, 0.1000]) -> 0.707 5: tensor([0.0500, 0.8000, 0.5500]) -> 1.087
# Next we will normalize our attention scores so that they sum up to 1 as a matter of convenience.
# Note that the method we'll use here assumes that all elements in all vectors are greater than zero.
attention_weights2 = attention_scores2 / attention_scores2.sum()
print(f"Normalized weights: {attention_weights2}")
print(f"Sum: {attention_weights2.sum():.2}")
Normalized weights: tensor([0.1455, 0.2278, 0.2249, 0.1285, 0.1077, 0.1656]) Sum: 1.0
# In practice softmax is a more robust choice.
attention_weights2 = torch.exp(attention_scores2) / torch.exp(attention_scores2).sum()
print(f"Normalized weights: {attention_weights2}")
print(f"Sum: {attention_weights2.sum():.2}")
Normalized weights: tensor([0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581]) Sum: 1.0
# Our naive implementation is subject to numerical instability, better to use the OOTB function.
attention_weights2 = torch.softmax(attention_scores2, dim=0)
print(f"Normalized weights: {attention_weights2}")
print(f"Sum: {attention_weights2.sum():.2}")
Normalized weights: tensor([0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581]) Sum: 1.0
Now we can produce our context vector for our query token $z_2$ which corresponds our second input token. We calculate this by taking the sum of all input tokens $x_i$ multiplied by their corresponding attention weights with respect to our query token $\alpha_{2i}$
# We use torch.zeros_like() to ensure we start with a zero vector
context_vector2 = torch.zeros_like(query_token)
context_vector2
tensor([0., 0., 0.])
for token, weight in zip(inputs, attention_weights2):
context_vector2 += token * weight
context_vector2
tensor([0.4419, 0.6515, 0.5683])
We can now generalize the prior to calculate all of the attention scores, attention weights, and context vectors for each of the input tokens.
def do_attention(input_tokens):
output_context_vectors = torch.zeros_like(input_tokens)
for i, query_token in enumerate(input_tokens):
# Store an attention score for the query relative to each input token.
query_attention_scores = torch.zeros(input_tokens.shape[0])
for j, input_token in enumerate(input_tokens):
query_attention_scores[j] = query_token @ input_token
print(f"Attention: {query_attention_scores}")
query_attention_weights = torch.softmax(query_attention_scores, dim=0)
query_context_vector = torch.zeros_like(query_token)
for token, weight in zip(input_tokens, query_attention_weights):
query_context_vector += token * weight
output_context_vectors[i] = query_context_vector
return output_context_vectors
result = do_attention(inputs)
Attention: tensor([0.9995, 0.9544, 0.9422, 0.4753, 0.4576, 0.6310]) Attention: tensor([0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865]) Attention: tensor([0.9422, 1.4754, 1.4570, 0.8296, 0.7154, 1.0605]) Attention: tensor([0.4753, 0.8434, 0.8296, 0.4937, 0.3474, 0.6565]) Attention: tensor([0.4576, 0.7070, 0.7154, 0.3474, 0.6654, 0.2935]) Attention: tensor([0.6310, 1.0865, 1.0605, 0.6565, 0.2935, 0.9450])
We can make this more efficient because our attention score calculation is really a dot product between two tensors.
print(inputs)
print(inputs.T)
tensor([[0.4300, 0.1500, 0.8900],
[0.5500, 0.8700, 0.6600],
[0.5700, 0.8500, 0.6400],
[0.2200, 0.5800, 0.3300],
[0.7700, 0.2500, 0.1000],
[0.0500, 0.8000, 0.5500]])
tensor([[0.4300, 0.5500, 0.5700, 0.2200, 0.7700, 0.0500],
[0.1500, 0.8700, 0.8500, 0.5800, 0.2500, 0.8000],
[0.8900, 0.6600, 0.6400, 0.3300, 0.1000, 0.5500]])
print(inputs[0])
print(inputs.T[:,0])
tensor([0.4300, 0.1500, 0.8900]) tensor([0.4300, 0.1500, 0.8900])
def do_attention(input_tokens):
output_context_vectors = torch.zeros_like(input_tokens)
output_attention_scores = input_tokens @ input_tokens.T
output_attention_weights = torch.zeros_like(output_attention_scores)
for i, query_token in enumerate(input_tokens):
query_attention_weights = torch.softmax(output_attention_scores[i], dim=0)
output_attention_weights[i] = query_attention_weights
query_context_vector = torch.zeros_like(query_token)
for token, weight in zip(input_tokens, query_attention_weights):
query_context_vector += token * weight
output_context_vectors[i] = query_context_vector
return (output_attention_scores, output_attention_weights, output_context_vectors)
attention_scores, attention_weights, context_vectors = do_attention(inputs)
print(f"Attention scores:\n{attention_scores}")
print(f"\nAttention weights:\n{attention_weights}")
print(f"\nContext vectors:\n{context_vectors}")
Attention scores:
tensor([[0.9995, 0.9544, 0.9422, 0.4753, 0.4576, 0.6310],
[0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865],
[0.9422, 1.4754, 1.4570, 0.8296, 0.7154, 1.0605],
[0.4753, 0.8434, 0.8296, 0.4937, 0.3474, 0.6565],
[0.4576, 0.7070, 0.7154, 0.3474, 0.6654, 0.2935],
[0.6310, 1.0865, 1.0605, 0.6565, 0.2935, 0.9450]])
Attention weights:
tensor([[0.2098, 0.2006, 0.1981, 0.1242, 0.1220, 0.1452],
[0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581],
[0.1390, 0.2369, 0.2326, 0.1242, 0.1108, 0.1565],
[0.1435, 0.2074, 0.2046, 0.1462, 0.1263, 0.1720],
[0.1526, 0.1958, 0.1975, 0.1367, 0.1879, 0.1295],
[0.1385, 0.2184, 0.2128, 0.1420, 0.0988, 0.1896]])
Context vectors:
tensor([[0.4421, 0.5931, 0.5790],
[0.4419, 0.6515, 0.5683],
[0.4431, 0.6496, 0.5671],
[0.4304, 0.6298, 0.5510],
[0.4671, 0.5910, 0.5266],
[0.4177, 0.6503, 0.5645]])
We can also pull our weights calculation out of the slow python loop and let torch.softmax() produce the result efficiently.
def do_attention(input_tokens):
output_context_vectors = torch.zeros_like(input_tokens)
output_attention_scores = input_tokens @ input_tokens.T
output_attention_weights = torch.softmax(output_attention_scores, dim=1)
for i, query_token in enumerate(input_tokens):
query_attention_weights = output_attention_weights[i]
query_context_vector = torch.zeros_like(query_token)
for token, weight in zip(input_tokens, query_attention_weights):
query_context_vector += token * weight
output_context_vectors[i] = query_context_vector
return (output_attention_scores, output_attention_weights, output_context_vectors)
attention_scores, attention_weights, context_vectors = do_attention(inputs)
print(f"Attention scores:\n{attention_scores}")
print(f"\nAttention weights:\n{attention_weights}")
print(f"\nContext vectors:\n{context_vectors}")
Attention scores:
tensor([[0.9995, 0.9544, 0.9422, 0.4753, 0.4576, 0.6310],
[0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865],
[0.9422, 1.4754, 1.4570, 0.8296, 0.7154, 1.0605],
[0.4753, 0.8434, 0.8296, 0.4937, 0.3474, 0.6565],
[0.4576, 0.7070, 0.7154, 0.3474, 0.6654, 0.2935],
[0.6310, 1.0865, 1.0605, 0.6565, 0.2935, 0.9450]])
Attention weights:
tensor([[0.2098, 0.2006, 0.1981, 0.1242, 0.1220, 0.1452],
[0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581],
[0.1390, 0.2369, 0.2326, 0.1242, 0.1108, 0.1565],
[0.1435, 0.2074, 0.2046, 0.1462, 0.1263, 0.1720],
[0.1526, 0.1958, 0.1975, 0.1367, 0.1879, 0.1295],
[0.1385, 0.2184, 0.2128, 0.1420, 0.0988, 0.1896]])
Context vectors:
tensor([[0.4421, 0.5931, 0.5790],
[0.4419, 0.6515, 0.5683],
[0.4431, 0.6496, 0.5671],
[0.4304, 0.6298, 0.5510],
[0.4671, 0.5910, 0.5266],
[0.4177, 0.6503, 0.5645]])
If you look at how we're creating the context vectors you can see that it can be replaced with matrix multiplication, albeit with a few transposes to make the geometry work.
def do_attention(input_tokens):
output_attention_scores = input_tokens @ input_tokens.T
output_attention_weights = torch.softmax(output_attention_scores, dim=1)
output_context_vectors = (input_tokens.T @ output_attention_weights.T).T
return (output_attention_scores, output_attention_weights, output_context_vectors)
attention_scores, attention_weights, context_vectors = do_attention(inputs)
print(f"Attention scores:\n{attention_scores}")
print(f"\nAttention weights:\n{attention_weights}")
print(f"\nContext vectors:\n{context_vectors}")
Attention scores:
tensor([[0.9995, 0.9544, 0.9422, 0.4753, 0.4576, 0.6310],
[0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865],
[0.9422, 1.4754, 1.4570, 0.8296, 0.7154, 1.0605],
[0.4753, 0.8434, 0.8296, 0.4937, 0.3474, 0.6565],
[0.4576, 0.7070, 0.7154, 0.3474, 0.6654, 0.2935],
[0.6310, 1.0865, 1.0605, 0.6565, 0.2935, 0.9450]])
Attention weights:
tensor([[0.2098, 0.2006, 0.1981, 0.1242, 0.1220, 0.1452],
[0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581],
[0.1390, 0.2369, 0.2326, 0.1242, 0.1108, 0.1565],
[0.1435, 0.2074, 0.2046, 0.1462, 0.1263, 0.1720],
[0.1526, 0.1958, 0.1975, 0.1367, 0.1879, 0.1295],
[0.1385, 0.2184, 0.2128, 0.1420, 0.0988, 0.1896]])
Context vectors:
tensor([[0.4421, 0.5931, 0.5790],
[0.4419, 0.6515, 0.5683],
[0.4431, 0.6496, 0.5671],
[0.4304, 0.6298, 0.5510],
[0.4671, 0.5910, 0.5266],
[0.4177, 0.6503, 0.5645]])
This can be further simplified using the reversal rule: $(AB)^T = B^TA^T$
And then we can remove the transposes entirely because $(X^T)^T = X$
def do_attention(input_tokens):
output_attention_scores = input_tokens @ input_tokens.T
output_attention_weights = torch.softmax(output_attention_scores, dim=1)
output_context_vectors = output_attention_weights @ input_tokens
return (output_attention_scores, output_attention_weights, output_context_vectors)
attention_scores, attention_weights, context_vectors = do_attention(inputs)
print(f"Attention scores:\n{attention_scores}")
print(f"\nAttention weights:\n{attention_weights}")
print(f"\nContext vectors:\n{context_vectors}")
Attention scores:
tensor([[0.9995, 0.9544, 0.9422, 0.4753, 0.4576, 0.6310],
[0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865],
[0.9422, 1.4754, 1.4570, 0.8296, 0.7154, 1.0605],
[0.4753, 0.8434, 0.8296, 0.4937, 0.3474, 0.6565],
[0.4576, 0.7070, 0.7154, 0.3474, 0.6654, 0.2935],
[0.6310, 1.0865, 1.0605, 0.6565, 0.2935, 0.9450]])
Attention weights:
tensor([[0.2098, 0.2006, 0.1981, 0.1242, 0.1220, 0.1452],
[0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581],
[0.1390, 0.2369, 0.2326, 0.1242, 0.1108, 0.1565],
[0.1435, 0.2074, 0.2046, 0.1462, 0.1263, 0.1720],
[0.1526, 0.1958, 0.1975, 0.1367, 0.1879, 0.1295],
[0.1385, 0.2184, 0.2128, 0.1420, 0.0988, 0.1896]])
Context vectors:
tensor([[0.4421, 0.5931, 0.5790],
[0.4419, 0.6515, 0.5683],
[0.4431, 0.6496, 0.5671],
[0.4304, 0.6298, 0.5510],
[0.4671, 0.5910, 0.5266],
[0.4177, 0.6503, 0.5645]])
# Check that weights sum to 1
attention_weights.sum(dim=1)
tensor([1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000])
Query, Key, Value¶
Now we'll take a more realistic self attention mechanism. For didactic simplicity, we will use 2-d output vectors. We will start off focusing on a single input token $x_2$; create weight matrices for the query, key, and value $W_q, W_k, W_v$; then obtain the corresponding query, key, and value vectors $q_2, k_2, v_2$ — these correspond to the our input token, the second in the series.
Our flow so far goes something like this:
- $W_E$: get the "dictionary definition" of the token in a vacuum. Since a token isn't necessarily an entire word this definition is a bit loopy from a human perspective, but the basic idea is something like "'are' can be a verb, but it could also be the end of share, rare, etc."
- Position: add additional information about the token's position. Quintessentially, if it comes first in a sentence in English it is more likely to be the subject, to give one example of why we want to enrich the token with positional information.
- First attention: now we start putting the token "in context." If the token is "are" then we might need to know if it's the verb "are," or the end of something else like "share" or "rare." Just as we don't fully know what's going on in hidden layers of a neural network, we don't fully know what's going on in the attention mechanisms. But it's conceivably something like "well first of all, is this a verb?" To answer that, we transform the token into "attention space" to produce a "query;" we then use that "query" to lookup relevant "keys" in the "database" (our context); we then combine the "values" of those keys to produce a "context" vector that, in theory, gives us the answer to the verb question.
- Second attention: maybe we ask if it's part of a noun like "share," as in "a share of a company."
- Third attention: maybe we ask if it's part of an adjective like "rare."
And so on and so fourth.
x_2 = inputs[1] # query token, second input token
d_in = inputs.shape[1] # input vector length
d_out = 2 # output vector length for q_2, k_2, v_2
torch.manual_seed(123)
W_q = torch.rand(d_in, d_out)
W_q
tensor([[0.2961, 0.5166],
[0.2517, 0.6886],
[0.0740, 0.8665]])
W_k = torch.rand(d_in, d_out)
W_v = torch.rand(d_in, d_out)
q_2 = x_2 @ W_q
q_2
tensor([0.4306, 1.4551])
k_2 = x_2 @ W_k
v_2 = x_2 @ W_v
We will need the keys and values for all inputs in order to calculate $z_2$, we can obtain that with $X W_k$ and $X W_v$ where $X$ is our tensor of input vectors.
keys = inputs @ W_k
keys
tensor([[0.3669, 0.7646],
[0.4433, 1.1419],
[0.4361, 1.1156],
[0.2408, 0.6706],
[0.1827, 0.3292],
[0.3275, 0.9642]])
values = inputs @ W_v
values
tensor([[0.1855, 0.8812],
[0.3951, 1.0037],
[0.3879, 0.9831],
[0.2393, 0.5493],
[0.1492, 0.3346],
[0.3221, 0.7863]])
Now we need the unscaled attention scores, $\omega$. $\omega_{22}$ represents of the attention score for the second input token $x_2$ relative to itself, and is equal to $q_2 k_2$.
keys2 = keys[1]
attn_score_22 = q_2 @ keys2
attn_score_22
tensor(1.8524)
We can generalize this with matrix math to obtain all attention scores for our input token $x_2$ relative to all other tokens. The operation is $q_2 K^T$ where $K$ is the tensor of all our key vectors.
attn_scores_2 = q_2 @ keys.T
attn_scores_2 # quick check: second element matches prior result
tensor([1.2705, 1.8524, 1.8111, 1.0795, 0.5577, 1.5440])
To get the attention weights, we will first scale the attention scores, dividing them by the square root of the dimension of the key vectors; then we will apply softmax().
attn_weights_2 = torch.softmax(attn_scores_2 / d_out**0.5, dim=0)
attn_weights_2
tensor([0.1500, 0.2264, 0.2199, 0.1311, 0.0906, 0.1820])
What we've been doing is "scaled dot product attention." As embedding dimensions grow, naive softmax behaves more like a dirac impulse function (output like $[0, 0, 0, 1, ..., 0]$), which causes degenerate training conditions (vanishing gradients). Scaling the attention scores by the square root of the embedding dimension helps the softmax behave more appropriately and keeps training on track.
To get our context vector $z_2$, we multiply each value vector $v_i$ with its corresponding scaled attention weight $\alpha_i$ and then sum them. So $z_2 = \sum v_i \alpha_i$.
values
tensor([[0.1855, 0.8812],
[0.3951, 1.0037],
[0.3879, 0.9831],
[0.2393, 0.5493],
[0.1492, 0.3346],
[0.3221, 0.7863]])
attn_weights_2
tensor([0.1500, 0.2264, 0.2199, 0.1311, 0.0906, 0.1820])
z_2 = torch.zeros_like(values[0])
z_2
tensor([0., 0.])
for value, weight in zip(values, attn_weights_2):
z_2 += value * weight
z_2
tensor([0.3061, 0.8210])
Of course we can readily see that this is just a dot product: $z_2 = \alpha V$ where $V$ is our tensor of of value vectors.
z_2 = attn_weights_2 @ values
z_2
tensor([0.3061, 0.8210])
In keeping with the theme of this notebook, what we have done for one token we will now do in general for all tokens.
import torch.nn as nn
class SimpleAttentionV1(nn.Module):
def __init__(self, d_in, d_out):
super().__init__()
self.W_q = nn.Parameter(torch.rand([d_in, d_out]))
self.W_k = nn.Parameter(torch.rand([d_in, d_out]))
self.W_v = nn.Parameter(torch.rand([d_in, d_out]))
def forward(self, X):
queries = X @ self.W_q
keys = X @ self.W_k
values = X @ self.W_v
attn_scores = queries @ keys.T
# Attention weight matrix: "how much attention each token should pay to
# every other token"
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
Z = attn_weights @ values # tensor of context vectors
return Z
torch.manual_seed(123)
attention = SimpleAttentionV1(d_in, d_out)
print(attention.forward(inputs))
tensor([[0.2996, 0.8053],
[0.3061, 0.8210],
[0.3058, 0.8203],
[0.2948, 0.7939],
[0.2927, 0.7891],
[0.2990, 0.8040]], grad_fn=<MmBackward0>)
We can use torch.nn.Linear to improve training, since it uses a more sophisticated weight initialization scheme. It implements $y=xA^T+b$, where $b$ is the bias. If we disable the bias, then it just does $y=xA^T$, letting us use it as a drop-in replacement for our current usage of torch.nn.Parameter.
import torch.nn as nn
class SimpleAttentionV2(nn.Module):
def __init__(self, d_in, d_out, use_qkv_bias=False):
super().__init__()
self.W_q = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_k = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_v = nn.Linear(d_in, d_out, bias=use_qkv_bias)
def forward(self, X):
queries = self.W_q(X)
keys = self.W_k(X)
values = self.W_v(X)
attn_scores = queries @ keys.T
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
Z = attn_weights @ values # tensor of context vectors
return Z
torch.manual_seed(789)
attention = SimpleAttentionV2(d_in, d_out)
print(attention.forward(inputs))
tensor([[-0.0739, 0.0713],
[-0.0748, 0.0703],
[-0.0749, 0.0702],
[-0.0760, 0.0685],
[-0.0763, 0.0679],
[-0.0754, 0.0693]], grad_fn=<MmBackward0>)
Exercise 3.1 Comparing SelfAttention_v1 and SelfAttention_v2¶
Note that nn.Linear in SelfAttention_v2 uses a different weight initialization scheme as nn.Parameter(torch.rand(d_in, d_out)) used in SelfAttention_v1, which causes both mechanisms to produce different results. To check that both implementations, SelfAttention_v1 and SelfAttention_v2, are otherwise similar, we can transfer the weight matrices from a SelfAttention_v2 object to a SelfAttention_v1, such that both objects then produce the same results.
Your task is to correctly assign the weights from an instance of SelfAttention_v2 to an instance of SelfAttention_v1. To do this, you need to understand the relationship between the weights in both versions. (Hint: nn.Linear stores the weight matrix in a transposed form.) After the assignment, you should observe that both instances produce the same outputs.
torch.manual_seed(123)
attention1 = SimpleAttentionV1(d_in, d_out)
print("ATTENTION 1:")
print(attention1.forward(inputs))
torch.manual_seed(789)
attention2 = SimpleAttentionV2(d_in, d_out)
print("\nATTENTION 2:")
print(attention2.forward(inputs))
attention1.W_q.data = attention2.W_q.weight.T
attention1.W_k.data = attention2.W_k.weight.T
attention1.W_v.data = attention2.W_v.weight.T
print("\nATTENTION 1'")
print(attention1.forward(inputs))
ATTENTION 1:
tensor([[0.2996, 0.8053],
[0.3061, 0.8210],
[0.3058, 0.8203],
[0.2948, 0.7939],
[0.2927, 0.7891],
[0.2990, 0.8040]], grad_fn=<MmBackward0>)
ATTENTION 2:
tensor([[-0.0739, 0.0713],
[-0.0748, 0.0703],
[-0.0749, 0.0702],
[-0.0760, 0.0685],
[-0.0763, 0.0679],
[-0.0754, 0.0693]], grad_fn=<MmBackward0>)
ATTENTION 1'
tensor([[-0.0739, 0.0713],
[-0.0748, 0.0703],
[-0.0749, 0.0702],
[-0.0760, 0.0685],
[-0.0763, 0.0679],
[-0.0754, 0.0693]], grad_fn=<MmBackward0>)
Our attention weights currently allow a token to "pay attention" to a future token. For various reasons this screws up language modeling tasks. What we want to do is "knock out" "future" weights for any given token.
This can be intuitively understood by first considering what our attention weights tensor looks like:
torch.manual_seed(789)
attention = SimpleAttentionV2(d_in, d_out)
queries = attention.W_q(inputs)
keys = attention.W_k(inputs)
values = attention.W_v(inputs)
attn_scores = queries @ keys.T
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
print(attn_weights)
tensor([[0.1921, 0.1646, 0.1652, 0.1550, 0.1721, 0.1510],
[0.2041, 0.1659, 0.1662, 0.1496, 0.1665, 0.1477],
[0.2036, 0.1659, 0.1662, 0.1498, 0.1664, 0.1480],
[0.1869, 0.1667, 0.1668, 0.1571, 0.1661, 0.1564],
[0.1830, 0.1669, 0.1670, 0.1588, 0.1658, 0.1585],
[0.1935, 0.1663, 0.1666, 0.1542, 0.1666, 0.1529]],
grad_fn=<SoftmaxBackward0>)
The first row is the attention weights for the first token. It should only see itself. The second row is the attention weights for the second token. It should only see itself, and the first token. Etc.
In effect, we want to zero-out the upper-right triangle of weights. We can imagine a mask of 0's and 1's like the following:
context_length = inputs.shape[0]
ones = torch.ones(context_length, context_length)
mask = torch.tril(ones)
mask
tensor([[1., 0., 0., 0., 0., 0.],
[1., 1., 0., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 1., 0., 0.],
[1., 1., 1., 1., 1., 0.],
[1., 1., 1., 1., 1., 1.]])
Indeed, we can element-wise multiply this mask against our weights to achieve the desired knock-out. Then we just normalize the remain elements row-wise to ensure numerical stability.
attn_weights_masked = attn_weights * mask
attn_weights_masked
tensor([[0.1921, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.2041, 0.1659, 0.0000, 0.0000, 0.0000, 0.0000],
[0.2036, 0.1659, 0.1662, 0.0000, 0.0000, 0.0000],
[0.1869, 0.1667, 0.1668, 0.1571, 0.0000, 0.0000],
[0.1830, 0.1669, 0.1670, 0.1588, 0.1658, 0.0000],
[0.1935, 0.1663, 0.1666, 0.1542, 0.1666, 0.1529]],
grad_fn=<MulBackward0>)
attn_weights_row_sums_inv = 1.0 / attn_weights_masked.sum(dim=-1)
print(attn_weights_row_sums_inv)
print(attn_weights_row_sums_inv.shape)
tensor([5.2049, 2.7026, 1.8666, 1.4760, 1.1883, 1.0000],
grad_fn=<MulBackward0>)
torch.Size([6])
# The above operation worked but it produced a dimensionless vector as as result.
# When we do broadcasting later we will want this to be a "proper" column vector,
# so we use keepdim=True to keep the original 6 row layout and just collapse
# down to a single column.
attn_weights_row_sums_inv = 1.0 / attn_weights_masked.sum(dim=-1, keepdim=True)
print(attn_weights_row_sums_inv)
print(attn_weights_row_sums_inv.shape)
tensor([[5.2049],
[2.7026],
[1.8666],
[1.4760],
[1.1883],
[1.0000]], grad_fn=<MulBackward0>)
torch.Size([6, 1])
# This is a broadcast operation and will scale each row of
# the masked weights tensor by the corresponding element of the
# weights vector
attn_weights_masked_normed = attn_weights_masked * attn_weights_row_sums_inv
attn_weights_masked_normed
tensor([[1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.5517, 0.4483, 0.0000, 0.0000, 0.0000, 0.0000],
[0.3800, 0.3097, 0.3103, 0.0000, 0.0000, 0.0000],
[0.2758, 0.2460, 0.2462, 0.2319, 0.0000, 0.0000],
[0.2175, 0.1983, 0.1984, 0.1888, 0.1971, 0.0000],
[0.1935, 0.1663, 0.1666, 0.1542, 0.1666, 0.1529]],
grad_fn=<MulBackward0>)
We can be more efficient about all of this if we:
- Knock-out the upper-right of the attention scores.
- Knock-out with $-\infty$ instead of 0.
- Then do the
softmaxto produce the attention weights.
This will get us to the same place in fewer operations.
torch.manual_seed(789)
attention = SimpleAttentionV2(d_in, d_out)
queries = attention.W_q(inputs)
keys = attention.W_k(inputs)
values = attention.W_v(inputs)
attn_scores = queries @ keys.T
context_length = inputs.shape[0]
ones = torch.ones(context_length, context_length)
mask = torch.triu(ones).bool()
mask
tensor([[ True, True, True, True, True, True],
[False, True, True, True, True, True],
[False, False, True, True, True, True],
[False, False, False, True, True, True],
[False, False, False, False, True, True],
[False, False, False, False, False, True]])
# This won't quite work, we can't have all True in the first row,
# so we use diagonal=1 to shift the diagonal axis and get the right shape.
mask = torch.triu(ones, diagonal=1).bool()
mask
tensor([[False, True, True, True, True, True],
[False, False, True, True, True, True],
[False, False, False, True, True, True],
[False, False, False, False, True, True],
[False, False, False, False, False, True],
[False, False, False, False, False, False]])
# We can use this tensor of bools with masked_fill() to swap every element
# in attn_scores that with -inf when the corresponding element in the mask
# is True.
attn_scores_masked = torch.masked_fill(attn_scores, mask, -torch.inf)
attn_scores_masked
tensor([[0.2899, -inf, -inf, -inf, -inf, -inf],
[0.4656, 0.1723, -inf, -inf, -inf, -inf],
[0.4594, 0.1703, 0.1731, -inf, -inf, -inf],
[0.2642, 0.1024, 0.1036, 0.0186, -inf, -inf],
[0.2183, 0.0874, 0.0882, 0.0177, 0.0786, -inf],
[0.3408, 0.1270, 0.1290, 0.0198, 0.1290, 0.0078]],
grad_fn=<MaskedFillBackward0>)
# Now we just apply the softmax.
attn_weights_masked = torch.softmax(attn_scores_masked / keys.shape[-1]**0.5, dim=-1)
attn_weights_masked
tensor([[1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.5517, 0.4483, 0.0000, 0.0000, 0.0000, 0.0000],
[0.3800, 0.3097, 0.3103, 0.0000, 0.0000, 0.0000],
[0.2758, 0.2460, 0.2462, 0.2319, 0.0000, 0.0000],
[0.2175, 0.1983, 0.1984, 0.1888, 0.1971, 0.0000],
[0.1935, 0.1663, 0.1666, 0.1542, 0.1666, 0.1529]],
grad_fn=<SoftmaxBackward0>)
The last trick we'll look at is dropout, where we randomly knock out weights to help preventing overfitting during training. If we knock out $N$ weights where $N = [0, 1)$, we need to scale the remaining weights by $1 / (1-N)$ to maintain balanced weights. PyTorch provides the Dropout class for this purpose.
# An example of what the Dropout class does.
context_length = inputs.shape[0]
dropout_05 = torch.nn.Dropout(0.5)
fake_weights = dropout_05(torch.ones(context_length, context_length))
fake_weights
tensor([[2., 2., 0., 0., 2., 2.],
[0., 0., 2., 0., 0., 2.],
[0., 0., 2., 2., 0., 0.],
[2., 2., 0., 2., 2., 2.],
[0., 2., 2., 0., 0., 0.],
[2., 2., 0., 0., 0., 0.]])
# Apply dropout to our previous weights.
torch.manual_seed(123)
attn_weights_masked_dropped = dropout_05(attn_weights_masked)
attn_weights_masked_dropped
tensor([[2.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.7599, 0.6194, 0.6206, 0.0000, 0.0000, 0.0000],
[0.0000, 0.4921, 0.4925, 0.0000, 0.0000, 0.0000],
[0.0000, 0.3966, 0.0000, 0.3775, 0.0000, 0.0000],
[0.0000, 0.3327, 0.3331, 0.3084, 0.3331, 0.0000]],
grad_fn=<MulBackward0>)
Now we can update our simple attention mechanism with the causal and dropout capabilities we've explored.
class SimpleAttentionV3(nn.Module):
def __init__(self, d_in, d_out, context_length, dropout_pct, use_qkv_bias=False):
super().__init__()
self.W_q = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_k = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_v = nn.Linear(d_in, d_out, bias=use_qkv_bias)
ones = torch.ones(context_length, context_length)
self.mask = torch.triu(ones, diagonal=1).bool()
self.dropout = torch.nn.Dropout(dropout_pct)
def forward(self, X):
queries = self.W_q(X)
keys = self.W_k(X)
values = self.W_v(X)
attn_scores = queries @ keys.T
attn_scores_masked = torch.masked_fill(attn_scores, self.mask, -torch.inf)
attn_weights = torch.softmax(attn_scores_masked / keys.shape[-1]**0.5, dim=-1)
attn_weights_dropped = self.dropout(attn_weights)
Z = attn_weights_dropped @ values # tensor of context vectors
return Z
torch.manual_seed(123)
attention = SimpleAttentionV3(d_in, d_out, inputs.shape[0], 0.0)
attention.forward(inputs)
tensor([[-0.4519, 0.2216],
[-0.5874, 0.0058],
[-0.6300, -0.0632],
[-0.5675, -0.0843],
[-0.5526, -0.0981],
[-0.5299, -0.1081]], grad_fn=<MmBackward0>)
A further improvement we can make is to use a PyTorch buffer for the mask. This will keep it on the same device (CPU or GPU) as the rest of our architecture to ensure training efficiency. Also, if we use the "trailing underscore" variant of masked_fill then it will operate in-place (PyTorch convention).
class SimpleAttentionV4(nn.Module):
def __init__(self, d_in, d_out, context_length, dropout_pct, use_qkv_bias=False):
super().__init__()
self.W_q = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_k = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_v = nn.Linear(d_in, d_out, bias=use_qkv_bias)
ones = torch.ones(context_length, context_length)
self.register_buffer("mask", torch.triu(ones, diagonal=1).bool())
self.dropout = torch.nn.Dropout(dropout_pct)
def forward(self, X):
queries = self.W_q(X)
keys = self.W_k(X)
values = self.W_v(X)
attn_scores = queries @ keys.T
attn_scores.masked_fill_(self.mask, -torch.inf)
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
attn_weights_dropped = self.dropout(attn_weights)
Z = attn_weights_dropped @ values # tensor of context vectors
return Z
torch.manual_seed(123)
attention = SimpleAttentionV4(d_in, d_out, inputs.shape[0], 0.0)
attention.forward(inputs)
tensor([[-0.4519, 0.2216],
[-0.5874, 0.0058],
[-0.6300, -0.0632],
[-0.5675, -0.0843],
[-0.5526, -0.0981],
[-0.5299, -0.1081]], grad_fn=<MmBackward0>)
Finally, we want to ensure our attention mechanism can work with batched inputs. This only requires lightly modifying the forward pass. Everything is going to mostly Just Work. The one catch is when we transpose the keys tensor: since it will now be a batch of matrices, we need to be sure to transpose each matrix independently, and not the overall batch.
We'll create our example batch just by stacking our input tokens twice.
batch = torch.stack((inputs, inputs), dim = 0)
batch
tensor([[[0.4300, 0.1500, 0.8900],
[0.5500, 0.8700, 0.6600],
[0.5700, 0.8500, 0.6400],
[0.2200, 0.5800, 0.3300],
[0.7700, 0.2500, 0.1000],
[0.0500, 0.8000, 0.5500]],
[[0.4300, 0.1500, 0.8900],
[0.5500, 0.8700, 0.6600],
[0.5700, 0.8500, 0.6400],
[0.2200, 0.5800, 0.3300],
[0.7700, 0.2500, 0.1000],
[0.0500, 0.8000, 0.5500]]])
batch.shape # shows [batch count, context length, embedding dimension]
torch.Size([2, 6, 3])
# We'll call this mechanism worthy of a new name: CausalAttention.
class CausalAttention(nn.Module):
def __init__(self, d_in, d_out, context_length, dropout_pct, use_qkv_bias=False):
super().__init__()
self.W_q = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_k = nn.Linear(d_in, d_out, bias=use_qkv_bias)
self.W_v = nn.Linear(d_in, d_out, bias=use_qkv_bias)
ones = torch.ones(context_length, context_length)
self.register_buffer("mask", torch.triu(ones, diagonal=1).bool())
self.dropout = torch.nn.Dropout(dropout_pct)
def forward(self, X):
batch_count, num_tokens, embed_dim = X.shape
queries = self.W_q(X)
keys = self.W_k(X)
values = self.W_v(X)
attn_scores = queries @ keys.transpose(1, 2)
# During creation, we established our maximum input capacity: our context
# length. The actual amount of input (length of the prompt + response)
# will usually be much shorter. This is the number of tokens, and we
# slice our mask to work with whatever that amount is.
attn_scores.masked_fill_(self.mask[:num_tokens, :num_tokens], -torch.inf)
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
attn_weights_dropped = self.dropout(attn_weights)
Z = attn_weights_dropped @ values # tensor of context vectors
return Z
torch.manual_seed(123)
context_length = batch.shape[1]
ca = CausalAttention(d_in, d_out, context_length, 0.0)
context_vecs = ca(batch)
print("context_vecs.shape:", context_vecs.shape)
context_vecs.shape: torch.Size([2, 6, 2])
Next we want to implement multi-head attention: basically, multiple attention "heads" running parallel, learning different things similar to how layers in a neural network learn different things. We can do this with a simple wrapper class.
class MultiHeadAttentionWrapper(nn.Module):
def __init__(self, d_in, d_out, context_length, dropout_pct, num_heads, use_qkv_bias=False):
super().__init__()
self.heads = nn.ModuleList([
CausalAttention(d_in, d_out, context_length, dropout_pct, use_qkv_bias)
for _ in range(num_heads)
])
def forward(self, X):
return torch.cat([
head.forward(X) for head in self.heads
], dim = -1)
multi_head_attention = MultiHeadAttentionWrapper(d_in, d_out, context_length, 0.0, 2)
multi_head_attention.forward(batch)
tensor([[[0.4772, 0.1063, 0.4566, 0.2729],
[0.5891, 0.3257, 0.5792, 0.3011],
[0.6202, 0.3860, 0.6249, 0.3102],
[0.5478, 0.3589, 0.5691, 0.2785],
[0.5321, 0.3428, 0.5543, 0.2520],
[0.5077, 0.3493, 0.5337, 0.2499]],
[[0.4772, 0.1063, 0.4566, 0.2729],
[0.5891, 0.3257, 0.5792, 0.3011],
[0.6202, 0.3860, 0.6249, 0.3102],
[0.5478, 0.3589, 0.5691, 0.2785],
[0.5321, 0.3428, 0.5543, 0.2520],
[0.5077, 0.3493, 0.5337, 0.2499]]], grad_fn=<CatBackward0>)
Below is example usage code from the book with the following expected output:
tensor([[[-0.4519, 0.2216, 0.4772, 0.1063],
[-0.5874, 0.0058, 0.5891, 0.3257],
[-0.6300, -0.0632, 0.6202, 0.3860],
[-0.5675, -0.0843, 0.5478, 0.3589],
[-0.5526, -0.0981, 0.5321, 0.3428],
[-0.5299, -0.1081, 0.5077, 0.3493]],
[[-0.4519, 0.2216, 0.4772, 0.1063],
[-0.5874, 0.0058, 0.5891, 0.3257],
[-0.6300, -0.0632, 0.6202, 0.3860],
[-0.5675, -0.0843, 0.5478, 0.3589],
[-0.5526, -0.0981, 0.5321, 0.3428],
[-0.5299, -0.1081, 0.5077, 0.3493]]], grad_fn=<CatBackward0>)
context_vecs.shape: torch.Size([2, 6, 4])
torch.manual_seed(123)
context_length = batch.shape[1] # This is the number of tokens
d_in, d_out = 3, 2
mha = MultiHeadAttentionWrapper(
d_in, d_out, context_length, 0.0, num_heads=2
)
context_vecs = mha(batch)
print(context_vecs)
print("context_vecs.shape:", context_vecs.shape)
tensor([[[-0.4519, 0.2216, 0.4772, 0.1063],
[-0.5874, 0.0058, 0.5891, 0.3257],
[-0.6300, -0.0632, 0.6202, 0.3860],
[-0.5675, -0.0843, 0.5478, 0.3589],
[-0.5526, -0.0981, 0.5321, 0.3428],
[-0.5299, -0.1081, 0.5077, 0.3493]],
[[-0.4519, 0.2216, 0.4772, 0.1063],
[-0.5874, 0.0058, 0.5891, 0.3257],
[-0.6300, -0.0632, 0.6202, 0.3860],
[-0.5675, -0.0843, 0.5478, 0.3589],
[-0.5526, -0.0981, 0.5321, 0.3428],
[-0.5299, -0.1081, 0.5077, 0.3493]]], grad_fn=<CatBackward0>)
context_vecs.shape: torch.Size([2, 6, 4])
Exercise 3.2 Returning two-dimensional embedding vectors¶
Change the input arguments for the MultiHeadAttentionWrapper(..., num_ heads=2) call such that the output context vectors are two-dimensional instead of four dimensional while keeping the setting num_heads=2. Hint: You don’t have to modify the class implementation; you just have to change one of the other input arguments.
torch.manual_seed(123)
context_length = batch.shape[1] # This is the number of tokens
d_in, d_out = 3, 1
mha = MultiHeadAttentionWrapper(
d_in, d_out, context_length, 0.0, num_heads=2
)
context_vecs = mha(batch)
print(context_vecs)
print("context_vecs.shape:", context_vecs.shape)
tensor([[[-0.5740, 0.2216],
[-0.7320, 0.0155],
[-0.7774, -0.0546],
[-0.6979, -0.0817],
[-0.6538, -0.0957],
[-0.6424, -0.1065]],
[[-0.5740, 0.2216],
[-0.7320, 0.0155],
[-0.7774, -0.0546],
[-0.6979, -0.0817],
[-0.6538, -0.0957],
[-0.6424, -0.1065]]], grad_fn=<CatBackward0>)
context_vecs.shape: torch.Size([2, 6, 2])
Next we will create an all-in-one causal multihead attention class. This is, once again, going to mostly be a matter of linear algebra / tensor manipulation magic. In particular we will be using the view() function a lot. It's worth exploring that.
t = torch.linspace(1, 4, 4)
t
tensor([1., 2., 3., 4.])
t.view([2, 2])
tensor([[1., 2.],
[3., 4.]])
t.view([1, 4])
tensor([[1., 2., 3., 4.]])
t.view([4, 1])
tensor([[1.],
[2.],
[3.],
[4.]])
try:
t.view([3, 5])
except Exception as e:
print(e)
shape '[3, 5]' is invalid for input of size 4
t = torch.stack([torch.linspace(1+i*4, 4+i*4, 4) for i in range(4)])
t
tensor([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[13., 14., 15., 16.]])
t.shape
torch.Size([4, 4])
t.view(2, 8)
tensor([[ 1., 2., 3., 4., 5., 6., 7., 8.],
[ 9., 10., 11., 12., 13., 14., 15., 16.]])
t.view(8, 2)
tensor([[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 10.],
[11., 12.],
[13., 14.],
[15., 16.]])
try:
t.view(3, 4)
except Exception as e:
print(e)
shape '[3, 4]' is invalid for input of size 16
t = torch.stack([torch.stack([torch.linspace(1+i*4+j*16, 4+i*4+j*16, 4) for i in range(4)]) for j in range (2)])
t
tensor([[[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[13., 14., 15., 16.]],
[[17., 18., 19., 20.],
[21., 22., 23., 24.],
[25., 26., 27., 28.],
[29., 30., 31., 32.]]])
t.shape
torch.Size([2, 4, 4])
t.view(2, 2, 8)
tensor([[[ 1., 2., 3., 4., 5., 6., 7., 8.],
[ 9., 10., 11., 12., 13., 14., 15., 16.]],
[[17., 18., 19., 20., 21., 22., 23., 24.],
[25., 26., 27., 28., 29., 30., 31., 32.]]])
t.view(2, 8, 2)
tensor([[[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 10.],
[11., 12.],
[13., 14.],
[15., 16.]],
[[17., 18.],
[19., 20.],
[21., 22.],
[23., 24.],
[25., 26.],
[27., 28.],
[29., 30.],
[31., 32.]]])
t.view(2, 16)
tensor([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.,
15., 16.],
[17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30.,
31., 32.]])
t.view(2, 2, 2, 4)
tensor([[[[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.]],
[[ 9., 10., 11., 12.],
[13., 14., 15., 16.]]],
[[[17., 18., 19., 20.],
[21., 22., 23., 24.]],
[[25., 26., 27., 28.],
[29., 30., 31., 32.]]]])
You can see that the basic rule of thumb is the product of the dimensions of our tensor must equal the product of the dimensions of the view. So long as that's observed, we can get quite creative, even adding additional dimensions. This is how we'll be able to take a big chunk of Queries and "split" them into sub-chunks corresponding to different attention heads.
num_samples = 2
num_tokens = 6
num_heads = 2
num_outs = 4 # must be a multiple of num_heads
head_dim = num_outs // num_heads
num_sample_elements = num_tokens * num_outs
t = torch.stack([torch.stack([torch.linspace(1+i*num_outs+j*num_sample_elements, 4+i*num_outs+j*num_sample_elements, num_outs) for i in range(num_tokens)]) for j in range (num_samples)])
t
tensor([[[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[13., 14., 15., 16.],
[17., 18., 19., 20.],
[21., 22., 23., 24.]],
[[25., 26., 27., 28.],
[29., 30., 31., 32.],
[33., 34., 35., 36.],
[37., 38., 39., 40.],
[41., 42., 43., 44.],
[45., 46., 47., 48.]]])
t.shape
torch.Size([2, 6, 4])
Now we need to be able to split apart those heads. This is grungy engineering work. Having a mental model of nested for loops always works. First we'll create a view which will separate things correctly, but they will be unproductively interleaved. Then we'll do a transpose along axes 1 and 2 — you can think of this as "I filled in this array with 4 nested for loops, and I'm going to swap the positions of loops 1 and 2 (assuming zero-based numbering)." This will arrange the separated components optimally.
u = t.view(num_samples, num_tokens, num_heads, head_dim)
u
tensor([[[[ 1., 2.],
[ 3., 4.]],
[[ 5., 6.],
[ 7., 8.]],
[[ 9., 10.],
[11., 12.]],
[[13., 14.],
[15., 16.]],
[[17., 18.],
[19., 20.]],
[[21., 22.],
[23., 24.]]],
[[[25., 26.],
[27., 28.]],
[[29., 30.],
[31., 32.]],
[[33., 34.],
[35., 36.]],
[[37., 38.],
[39., 40.]],
[[41., 42.],
[43., 44.]],
[[45., 46.],
[47., 48.]]]])
u.shape
torch.Size([2, 6, 2, 2])
v = u.transpose(1, 2)
v
tensor([[[[ 1., 2.],
[ 5., 6.],
[ 9., 10.],
[13., 14.],
[17., 18.],
[21., 22.]],
[[ 3., 4.],
[ 7., 8.],
[11., 12.],
[15., 16.],
[19., 20.],
[23., 24.]]],
[[[25., 26.],
[29., 30.],
[33., 34.],
[37., 38.],
[41., 42.],
[45., 46.]],
[[27., 28.],
[31., 32.],
[35., 36.],
[39., 40.],
[43., 44.],
[47., 48.]]]])
v.shape
torch.Size([2, 2, 6, 2])
num_samples = 2 # Samples per batch
num_tokens = 4 # Tokens per sample
context_length = 8 # Max tokens context can contain
token_dim = 5 # Elements per token
num_attn_heads = 3 # Heads per attention mechanism
attn_out_dim = 6 # must be a multiple of num_attn_heads, total attention output dim
attn_head_dim = attn_out_dim // num_attn_heads # out dim of each attention head
torch.manual_seed(123)
input_tokens = torch.rand([num_tokens, token_dim])
input_tokens
tensor([[0.2961, 0.5166, 0.2517, 0.6886, 0.0740],
[0.8665, 0.1366, 0.1025, 0.1841, 0.7264],
[0.3153, 0.6871, 0.0756, 0.1966, 0.3164],
[0.4017, 0.1186, 0.8274, 0.3821, 0.6605]])
batch = torch.stack([input_tokens for _ in range(num_samples)])
batch
tensor([[[0.2961, 0.5166, 0.2517, 0.6886, 0.0740],
[0.8665, 0.1366, 0.1025, 0.1841, 0.7264],
[0.3153, 0.6871, 0.0756, 0.1966, 0.3164],
[0.4017, 0.1186, 0.8274, 0.3821, 0.6605]],
[[0.2961, 0.5166, 0.2517, 0.6886, 0.0740],
[0.8665, 0.1366, 0.1025, 0.1841, 0.7264],
[0.3153, 0.6871, 0.0756, 0.1966, 0.3164],
[0.4017, 0.1186, 0.8274, 0.3821, 0.6605]]])
W_q = torch.rand([token_dim, attn_out_dim])
W_q
tensor([[0.8536, 0.5932, 0.6367, 0.9826, 0.2745, 0.6584],
[0.2775, 0.8573, 0.8993, 0.0390, 0.9268, 0.7388],
[0.7179, 0.7058, 0.9156, 0.4340, 0.0772, 0.3565],
[0.1479, 0.5331, 0.4066, 0.2318, 0.4545, 0.9737],
[0.4606, 0.5159, 0.4220, 0.5786, 0.9455, 0.8057]])
W_k = torch.rand([token_dim, attn_out_dim])
W_v = torch.rand([token_dim, attn_out_dim])
attn_mask = torch.triu(
torch.ones(context_length, context_length),
diagonal=1
).bool()
attn_mask
tensor([[False, True, True, True, True, True, True, True],
[False, False, True, True, True, True, True, True],
[False, False, False, True, True, True, True, True],
[False, False, False, False, True, True, True, True],
[False, False, False, False, False, True, True, True],
[False, False, False, False, False, False, True, True],
[False, False, False, False, False, False, False, True],
[False, False, False, False, False, False, False, False]])
attn_dropout = torch.nn.Dropout(0.5)
queries = batch @ W_q
queries
tensor([[[0.7127, 1.2013, 1.1948, 0.6228, 0.9624, 1.3963],
[1.2129, 1.1763, 1.1498, 1.3643, 1.1429, 1.4725],
[0.6889, 1.0975, 1.1014, 0.5981, 1.1177, 1.1885],
[1.3305, 1.4684, 1.5541, 1.2292, 1.0822, 1.5513]],
[[0.7127, 1.2013, 1.1948, 0.6228, 0.9624, 1.3963],
[1.2129, 1.1763, 1.1498, 1.3643, 1.1429, 1.4725],
[0.6889, 1.0975, 1.1014, 0.5981, 1.1177, 1.1885],
[1.3305, 1.4684, 1.5541, 1.2292, 1.0822, 1.5513]]])
keys = batch @ W_k
values = batch @ W_v
queries = queries.view(num_samples, num_tokens, num_attn_heads, attn_head_dim).transpose(1, 2)
queries
tensor([[[[0.7127, 1.2013],
[1.2129, 1.1763],
[0.6889, 1.0975],
[1.3305, 1.4684]],
[[1.1948, 0.6228],
[1.1498, 1.3643],
[1.1014, 0.5981],
[1.5541, 1.2292]],
[[0.9624, 1.3963],
[1.1429, 1.4725],
[1.1177, 1.1885],
[1.0822, 1.5513]]],
[[[0.7127, 1.2013],
[1.2129, 1.1763],
[0.6889, 1.0975],
[1.3305, 1.4684]],
[[1.1948, 0.6228],
[1.1498, 1.3643],
[1.1014, 0.5981],
[1.5541, 1.2292]],
[[0.9624, 1.3963],
[1.1429, 1.4725],
[1.1177, 1.1885],
[1.0822, 1.5513]]]])
keys = keys.view(num_samples, num_tokens, num_attn_heads, attn_head_dim).transpose(1, 2)
values = values.view(num_samples, num_tokens, num_attn_heads, attn_head_dim).transpose(1, 2)
keys
tensor([[[[0.3671, 1.2434],
[1.1323, 1.1772],
[0.5731, 1.1472],
[0.7897, 1.1078]],
[[1.2310, 0.9408],
[1.3236, 0.8235],
[0.9893, 0.4851],
[1.3844, 1.0354]],
[[0.6597, 0.7240],
[0.8641, 0.8381],
[0.7415, 0.9611],
[0.9271, 1.0909]]],
[[[0.3671, 1.2434],
[1.1323, 1.1772],
[0.5731, 1.1472],
[0.7897, 1.1078]],
[[1.2310, 0.9408],
[1.3236, 0.8235],
[0.9893, 0.4851],
[1.3844, 1.0354]],
[[0.6597, 0.7240],
[0.8641, 0.8381],
[0.7415, 0.9611],
[0.9271, 1.0909]]]])
keys.transpose(2, 3)
tensor([[[[0.3671, 1.1323, 0.5731, 0.7897],
[1.2434, 1.1772, 1.1472, 1.1078]],
[[1.2310, 1.3236, 0.9893, 1.3844],
[0.9408, 0.8235, 0.4851, 1.0354]],
[[0.6597, 0.8641, 0.7415, 0.9271],
[0.7240, 0.8381, 0.9611, 1.0909]]],
[[[0.3671, 1.1323, 0.5731, 0.7897],
[1.2434, 1.1772, 1.1472, 1.1078]],
[[1.2310, 1.3236, 0.9893, 1.3844],
[0.9408, 0.8235, 0.4851, 1.0354]],
[[0.6597, 0.8641, 0.7415, 0.9271],
[0.7240, 0.8381, 0.9611, 1.0909]]]])
attn_scores = queries @ keys.transpose(2,3)
attn_scores
tensor([[[[1.7554, 2.2212, 1.7866, 1.8936],
[1.9078, 2.7581, 2.0445, 2.2609],
[1.6175, 2.0721, 1.6538, 1.7598],
[2.3142, 3.2351, 2.4470, 2.6773]],
[[2.0566, 2.0942, 1.4841, 2.2988],
[2.6989, 2.6453, 1.7994, 3.0043],
[1.9185, 1.9503, 1.3798, 2.1440],
[3.0696, 3.0692, 2.1339, 3.4242]],
[[1.6458, 2.0019, 2.0555, 2.4154],
[1.8200, 2.2216, 2.2625, 2.6658],
[1.5978, 1.9620, 1.9710, 2.3328],
[1.8370, 2.2353, 2.2933, 2.6955]]],
[[[1.7554, 2.2212, 1.7866, 1.8936],
[1.9078, 2.7581, 2.0445, 2.2609],
[1.6175, 2.0721, 1.6538, 1.7598],
[2.3142, 3.2351, 2.4470, 2.6773]],
[[2.0566, 2.0942, 1.4841, 2.2988],
[2.6989, 2.6453, 1.7994, 3.0043],
[1.9185, 1.9503, 1.3798, 2.1440],
[3.0696, 3.0692, 2.1339, 3.4242]],
[[1.6458, 2.0019, 2.0555, 2.4154],
[1.8200, 2.2216, 2.2625, 2.6658],
[1.5978, 1.9620, 1.9710, 2.3328],
[1.8370, 2.2353, 2.2933, 2.6955]]]])
# Clip the attention mask the number of tokens
attn_mask[:num_tokens, :num_tokens]
tensor([[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, False]])
# Apply the attention mask
attn_scores.masked_fill_(attn_mask[:num_tokens, :num_tokens], -torch.inf)
attn_scores
tensor([[[[1.7554, -inf, -inf, -inf],
[1.9078, 2.7581, -inf, -inf],
[1.6175, 2.0721, 1.6538, -inf],
[2.3142, 3.2351, 2.4470, 2.6773]],
[[2.0566, -inf, -inf, -inf],
[2.6989, 2.6453, -inf, -inf],
[1.9185, 1.9503, 1.3798, -inf],
[3.0696, 3.0692, 2.1339, 3.4242]],
[[1.6458, -inf, -inf, -inf],
[1.8200, 2.2216, -inf, -inf],
[1.5978, 1.9620, 1.9710, -inf],
[1.8370, 2.2353, 2.2933, 2.6955]]],
[[[1.7554, -inf, -inf, -inf],
[1.9078, 2.7581, -inf, -inf],
[1.6175, 2.0721, 1.6538, -inf],
[2.3142, 3.2351, 2.4470, 2.6773]],
[[2.0566, -inf, -inf, -inf],
[2.6989, 2.6453, -inf, -inf],
[1.9185, 1.9503, 1.3798, -inf],
[3.0696, 3.0692, 2.1339, 3.4242]],
[[1.6458, -inf, -inf, -inf],
[1.8200, 2.2216, -inf, -inf],
[1.5978, 1.9620, 1.9710, -inf],
[1.8370, 2.2353, 2.2933, 2.6955]]]])
# Apply softmax.
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
attn_weights
tensor([[[[1.0000, 0.0000, 0.0000, 0.0000],
[0.3541, 0.6459, 0.0000, 0.0000],
[0.2937, 0.4050, 0.3013, 0.0000],
[0.1884, 0.3612, 0.2069, 0.2435]],
[[1.0000, 0.0000, 0.0000, 0.0000],
[0.5095, 0.4905, 0.0000, 0.0000],
[0.3696, 0.3780, 0.2525, 0.0000],
[0.2631, 0.2630, 0.1358, 0.3381]],
[[1.0000, 0.0000, 0.0000, 0.0000],
[0.4295, 0.5705, 0.0000, 0.0000],
[0.2781, 0.3598, 0.3621, 0.0000],
[0.1805, 0.2392, 0.2492, 0.3312]]],
[[[1.0000, 0.0000, 0.0000, 0.0000],
[0.3541, 0.6459, 0.0000, 0.0000],
[0.2937, 0.4050, 0.3013, 0.0000],
[0.1884, 0.3612, 0.2069, 0.2435]],
[[1.0000, 0.0000, 0.0000, 0.0000],
[0.5095, 0.4905, 0.0000, 0.0000],
[0.3696, 0.3780, 0.2525, 0.0000],
[0.2631, 0.2630, 0.1358, 0.3381]],
[[1.0000, 0.0000, 0.0000, 0.0000],
[0.4295, 0.5705, 0.0000, 0.0000],
[0.2781, 0.3598, 0.3621, 0.0000],
[0.1805, 0.2392, 0.2492, 0.3312]]]])
# Apply dropout.
attn_weights = attn_dropout(attn_weights)
attn_weights
tensor([[[[0.0000, 0.0000, 0.0000, 0.0000],
[0.7081, 0.0000, 0.0000, 0.0000],
[0.0000, 0.8100, 0.6026, 0.0000],
[0.3767, 0.0000, 0.4138, 0.4870]],
[[2.0000, 0.0000, 0.0000, 0.0000],
[1.0189, 0.9811, 0.0000, 0.0000],
[0.7391, 0.0000, 0.5050, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000]],
[[2.0000, 0.0000, 0.0000, 0.0000],
[0.8589, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000],
[0.3609, 0.0000, 0.4984, 0.0000]]],
[[[2.0000, 0.0000, 0.0000, 0.0000],
[0.7081, 0.0000, 0.0000, 0.0000],
[0.0000, 0.8100, 0.6026, 0.0000],
[0.3767, 0.0000, 0.4138, 0.0000]],
[[2.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.9811, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.5261, 0.2715, 0.6762]],
[[0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 1.1411, 0.0000, 0.0000],
[0.5562, 0.0000, 0.7242, 0.0000],
[0.3609, 0.4783, 0.0000, 0.0000]]]])
# Get context vectors.
context_vectors = attn_weights @ values
# Context vectors are currently ordered by sample, head, token.
print(context_vectors.shape)
print(context_vectors)
torch.Size([2, 3, 4, 2])
tensor([[[[0.0000, 0.0000],
[0.8014, 0.8063],
[1.3796, 1.4467],
[1.4316, 1.5524]],
[[2.6005, 1.5609],
[2.5099, 2.0316],
[1.5102, 1.0696],
[0.0000, 0.0000]],
[[1.6098, 1.8948],
[0.6914, 0.8138],
[0.0000, 0.0000],
[0.5742, 0.8256]]],
[[[2.2635, 2.2773],
[0.8014, 0.8063],
[1.3796, 1.4467],
[0.7215, 0.8641]],
[[2.6005, 1.5609],
[1.1851, 1.2364],
[0.0000, 0.0000],
[1.7927, 1.8986]],
[[0.0000, 0.0000],
[1.0900, 1.0020],
[0.8599, 1.2298],
[0.7475, 0.7620]]]])
# Reorder to sample, token, head.
context_vectors = context_vectors.transpose(1, 2)
context_vectors
tensor([[[[0.0000, 0.0000],
[2.6005, 1.5609],
[1.6098, 1.8948]],
[[0.8014, 0.8063],
[2.5099, 2.0316],
[0.6914, 0.8138]],
[[1.3796, 1.4467],
[1.5102, 1.0696],
[0.0000, 0.0000]],
[[1.4316, 1.5524],
[0.0000, 0.0000],
[0.5742, 0.8256]]],
[[[2.2635, 2.2773],
[2.6005, 1.5609],
[0.0000, 0.0000]],
[[0.8014, 0.8063],
[1.1851, 1.2364],
[1.0900, 1.0020]],
[[1.3796, 1.4467],
[0.0000, 0.0000],
[0.8599, 1.2298]],
[[0.7215, 0.8641],
[1.7927, 1.8986],
[0.7475, 0.7620]]]])
# Now we can concatenate along the last dimension to produce
# a tensor of complete context vectors grouped by sample. This is
# easily doable with a view that drops the last two dimensions
# and substitutes the total attention output dimension.
# But note that our previous operations will have broken contiguity
# so view() won't work straightaway.
try:
context_vectors.view(num_samples, num_tokens, attn_out_dim)
except Exception as e:
print(e)
view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
# So we'll have to first make the tensor contiguous before we can create
# the view.
context_vectors = context_vectors.contiguous().view(num_samples, num_tokens, attn_out_dim)
context_vectors
tensor([[[0.0000, 0.0000, 2.6005, 1.5609, 1.6098, 1.8948],
[0.8014, 0.8063, 2.5099, 2.0316, 0.6914, 0.8138],
[1.3796, 1.4467, 1.5102, 1.0696, 0.0000, 0.0000],
[1.4316, 1.5524, 0.0000, 0.0000, 0.5742, 0.8256]],
[[2.2635, 2.2773, 2.6005, 1.5609, 0.0000, 0.0000],
[0.8014, 0.8063, 1.1851, 1.2364, 1.0900, 1.0020],
[1.3796, 1.4467, 0.0000, 0.0000, 0.8599, 1.2298],
[0.7215, 0.8641, 1.7927, 1.8986, 0.7475, 0.7620]]])
# Finally we can project these vectors into their final output space.
# This would be with another trainable tensor, NxN where N = the total
# attention output dimension. Intuitively we can think of this tensor as
# learning how to combine the insights of the individual attention heads.
attn_out_proj = torch.rand(attn_out_dim, attn_out_dim)
attn_out_proj
# In our actual implementation we'll use a full linear layer so a bias term
# will be included as well.
tensor([[0.9355, 0.6260, 0.3534, 0.6638, 0.4563, 0.1091],
[0.3069, 0.7274, 0.5164, 0.6845, 0.2073, 0.9727],
[0.2913, 0.6066, 0.2557, 0.2588, 0.7239, 0.3604],
[0.1829, 0.2956, 0.8646, 0.8010, 0.8044, 0.0733],
[0.7355, 0.6248, 0.1638, 0.5158, 0.6000, 0.2299],
[0.2890, 0.9078, 0.4596, 0.4947, 0.1836, 0.2010]])
context_vectors_proj = context_vectors @ attn_out_proj
context_vectors_proj
tensor([[[2.7747, 4.7651, 3.1490, 3.6911, 4.4518, 1.8026],
[2.8436, 4.3822, 3.5851, 4.1201, 4.5482, 2.2477],
[2.3703, 3.1484, 2.5455, 3.1537, 2.8830, 2.1804],
[2.4766, 3.1337, 1.7810, 2.7175, 1.4711, 1.9641]],
[[3.8596, 5.1125, 3.9903, 4.9847, 4.6430, 3.5137],
[2.6598, 3.7633, 2.7106, 3.4389, 3.2232, 1.8414],
[2.7225, 3.5698, 1.9407, 2.9581, 1.6711, 2.0026],
[2.5796, 3.8879, 3.2737, 3.8177, 3.9217, 2.0295]]])
So that illustrates the basic mechanics. All that remains is to translate them into a proper class. This is essentially a light adaptation of our previous Causal Attention class.
class MultiHeadAttention(nn.Module):
def __init__(self, input_dim, output_dim, context_length, dropout_pct, num_heads, use_bias=False):
super().__init__()
assert output_dim % num_heads == 0, "output_dim must be a multiple of num_heads"
self.num_heads = num_heads
self.head_dim = output_dim // num_heads
self.output_dim = output_dim
self.W_q = nn.Linear(input_dim, output_dim, bias=use_bias)
self.W_k = nn.Linear(input_dim, output_dim, bias=use_bias)
self.W_v = nn.Linear(input_dim, output_dim, bias=use_bias)
self.output_proj = nn.Linear(output_dim, output_dim)
self.dropout = torch.nn.Dropout(dropout_pct, inplace=True)
ones = torch.ones(context_length, context_length)
self.register_buffer("mask", torch.triu(ones, diagonal=1).bool())
def forward(self, batch):
num_samples, num_tokens, token_dim = batch.shape
queries = self.W_q(batch)
keys = self.W_k(batch)
values = self.W_v(batch)
queries = queries.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
keys = keys.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
values = values.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
attn_scores = queries @ keys.transpose(2, 3)
attn_scores.masked_fill_(self.mask[:num_tokens, :num_tokens], -torch.inf)
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
self.dropout(attn_weights) # Dropout in-place
context_vectors = attn_weights @ values
context_vectors = context_vectors.transpose(1, 2)
context_vectors = context_vectors.contiguous().view(num_samples, num_tokens, self.output_dim)
output = self.output_proj(context_vectors)
return output
inputs = torch.tensor(
[[0.43, 0.15, 0.89], # Your (x^1)
[0.55, 0.87, 0.66], # journey (x^2)
[0.57, 0.85, 0.64], # starts (x^3)
[0.22, 0.58, 0.33], # with (x^4)
[0.77, 0.25, 0.10], # one (x^5)
[0.05, 0.80, 0.55]] # step (x^6)
)
batch = torch.stack((inputs, inputs), dim=0)
batch.shape
torch.Size([2, 6, 3])
torch.manual_seed(123)
batch_size, context_length, d_in = batch.shape
d_out = 2
mha = MultiHeadAttention(d_in, d_out, context_length, 0.0, num_heads=2)
context_vecs = mha(batch)
print(context_vecs)
print("context_vecs.shape:", context_vecs.shape)
tensor([[[0.3190, 0.4858],
[0.2943, 0.3897],
[0.2856, 0.3593],
[0.2693, 0.3873],
[0.2639, 0.3928],
[0.2575, 0.4028]],
[[0.3190, 0.4858],
[0.2943, 0.3897],
[0.2856, 0.3593],
[0.2693, 0.3873],
[0.2639, 0.3928],
[0.2575, 0.4028]]], grad_fn=<ViewBackward0>)
context_vecs.shape: torch.Size([2, 6, 2])
Expected result:
tensor([[[0.3190, 0.4858],
[0.2943, 0.3897],
[0.2856, 0.3593],
[0.2693, 0.3873],
[0.2639, 0.3928],
[0.2575, 0.4028]],
[[0.3190, 0.4858],
[0.2943, 0.3897],
[0.2856, 0.3593],
[0.2693, 0.3873],
[0.2639, 0.3928],
[0.2575, 0.4028]]], grad_fn=<ViewBackward0>)
context_vecs.shape: torch.Size([2, 6, 2])
Exercise 3.3 Initializing GPT-2 size attention modules¶
Using the MultiHeadAttention class, initialize a multi-head attention module that has the same number of attention heads as the smallest GPT-2 model (12 attention heads). Also ensure that you use the respective input and output embedding sizes similar to GPT-2 (768 dimensions). Note that the smallest GPT-2 model supports a context length of 1,024 tokens.
mha_gpt2 = MultiHeadAttention(
input_dim=768, output_dim=768, # These are equal values in GPT models
context_length=1024, dropout_pct=0.0, num_heads=12)