Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 1 addition & 1 deletion transformers_code/layers/mha.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def scaled_dot_product_attention(self, Q, K, V, mask=None):
# shape(K, V) = [B x seq_len x D/num_heads]
# shape(Q, K, V) = [B x num_heads x seq_len x D/num_heads]

Q_K_matmul = torch.matmul(Q, K.permute(0, 1, 3, 2))
Q_K_matmul = torch.matmul(Q, K.permute(0, 2, 1))
scores = Q_K_matmul / m.sqrt(self.d)
# shape(scores) = [B x num_heads x seq_len x seq_len]

Expand Down
Binary file not shown.
Binary file not shown.
2 changes: 2 additions & 0 deletions transformers_code_answers/examples/toy_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,5 @@
# %%
toy_scores = toy_scores.masked_fill(toy_mask == False, -1)
print("Toy Scores Masked: \n", toy_scores)

# %%
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
11 changes: 7 additions & 4 deletions transformers_code_answers/layers/mha.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,16 @@ def scaled_dot_product_attention(self, Q, K, V, mask=None):
# shape(K, V) = [B x seq_len x D/num_heads]
# shape(Q, K, V) = [B x num_heads x seq_len x D/num_heads]


Q_K_matmul = torch.matmul(Q, K.permute(0, 1, 3, 2))
scores = Q_K_matmul/m.sqrt(self.d)
# shape(scores) = [B x num_heads x seq_len x seq_len]

if mask is not None:
scores = scores.masked_fill(mask == False, -1e9)
multi_mask = mask.unsqueeze(1)
multi_mask = torch.hstack([multi_mask for _ in range(self.num_heads)])
#multi_mask = multi_mask.unsqueeze(2)
if multi_mask is not None:

scores = scores.masked_fill(multi_mask == False, -1e9)

attention_weights = F.softmax(scores, dim=-1)
# shape(attention_weights) = [B x num_heads x seq_len x seq_len]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}