文章目录
Transformer
讲的最好的一篇(我认为) 用pytorch一步步实现
- 他的multihead应该是错的,不应该吧embediing分开,而应该有多个Q,K,V
错误解决方案请看这篇,或者中文版,并且讲述了bert,吧所有head的output拼在一起,并训练 W o W_o Wo使其回归到原来的大小
attention的输出是每一个词的embedding,somehow有其他词的attention。每个词是v1*attention_v1 + v2*attention_v2 …
第一层attention的每个词size都是embedding,其余的都是num_attention_heads
* size_per_head
The feed-forward layer is not expecting eight matrices
- 不完全是,Bert里面就没有进行“压缩”。 不一定需要 W o W^o Wo
Q和K长度要一致,V不一定
Bert
本篇基于tensorflow.2.4.1, 源码在library里面
直接看github上的源码, from Google-research
首先看前两个argument,from_tensor和to_tensor. 可以吧第一个理解为input句子,
- from_tensor 和 to_tensor
- batch_size: 多少个句子
- from_seq_length(每个句子多少个单词),
- from_width: 每个单词的长度*head的数量
- 源码其实已经压缩成了2d tensor, 为了方便矩阵相乘(line 823)
Bert只用self-attention, 在833行可以看到
attention_head = attention_layer(
from_tensor=layer_input,
to_tensor=layer_input
两行的input是一样的
W Q , W K , W V W^Q, W^K, W^V WQ,WK,WV在line 666-687被定义
query_layer = tf.layers.dense(
from_tensor_2d,
num_attention_heads * size_per_head,
activation=query_act,
name="query",
kernel_initializer=create_initializer(initializer_range))
...
接下来算attention
A t t e n t i o n ( Q , K , V ) = softmax ( Q K T d k ) V Attention(Q, K, V ) = \text{softmax}(\frac{QK^T}{ \sqrt d_k} )V Attention(Q,K,V)=softmax(d