我正在学习从tensorflow官方文档Attention Is All You Need应用Transformer model for language understanding提出的转换模型。
如Positional encoding部分所述:
我的理解是将positional encoding vector
直接添加到embedding vector
。但是当我查看代码时,发现embedding vector
乘以一个常数。
Encoder部分中的代码如下:
class Encoder(tf.keras.layers.Layer):
def __init__(self, num_layers, d_model, num_heads, dff, input_vocab_size,
rate=0.1):
super(Encoder, self).__init__()
self.d_model = d_model
self.num_layers = num_layers
self.embedding = tf.keras.layers.Embedding(input_vocab_size, d_model)
self.pos_encoding = positional_encoding(input_vocab_size, self.d_model)
self.enc_layers = [EncoderLayer(d_model, num_heads, dff, rate)
for _ in range(num_layers)]
self.dropout = tf.keras.layers.Dropout(rate)
def call(self, x, training, mask):
seq_len = tf.shape(x)[1]
# adding embedding and position encoding.
x = self.embedding(x) # (batch_size, input_seq_len, d_model)
x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))
x += self.pos_encoding[:, :seq_len, :]
x = self.dropout(x, training=training)
for i in range(self.num_layers):
x = self.enc_layers[i](x, training, mask)
return x # (batch_size, input_seq_len, d_model)
我们可以在
x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))
之前看到x += self.pos_encoding[:, :seq_len, :]
。那么,为什么在Transformer模型中添加位置编码之前,将嵌入矢量乘以一个常数?
最佳答案
环顾四周,我发现了这个参数1:
关于python - 为什么在Transformer模型中将嵌入矢量乘以常数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56930821/