手撕 Self-Attention 矩阵计算
题目
手撕 Self-Attention 矩阵计算
参考答案
点击展开参考答案
- 公式:
Attention(Q, K, V) = softmax(QK^T / √d_k) · V - 代码(PyTorch):
-
- import torch
- import torch.nn.functional as F
- def self_attention(Q, K, V, mask=None):
- 追问:多头怎么实现?(答:把 d_model 拆成 n_heads 份,每份独立做 attention,最后 concat)
- 追问:Q/K/V 是怎么来的?(答:输入 embedding 分别乘三个投影矩阵 W_q, W_k, W_v)