【问题标题】:Attention does not seem to be applied at TransformerEncoderLayer and MultiheadAttention PyTorch在 TransformerEncoderLayer 和 MultiheadAttention PyTorch 上似乎没有应用注意力
【发布时间】:2022-01-02 18:34:10
【问题描述】:

在我的输入中的一个位置更改某些内容不会影响我的变压器编码器其他位置的输出。我在 PyTorch 中单独做了一个测试:

# My encoder layer
encoder_layer = nn.TransformerEncoderLayer(d_model=8, nhead=2)
# Turn off dropout
encoder_layer.eval()
# Random input
src = torch.rand(2, 10, 8)
# Predict the output
out_0 = encoder_layer(src)
# Change the values at one of the positions (position 3 in this case)
src[:,3,:] += 1
# Predict once again the output
out_1 = encoder_layer(src)
# Check at which positions the outcomes are different between the two cases
# I summed in the embedding space direction
print(np.sum(np.abs(out_0.detach().numpy()),axis=-1) - np.sum(np.abs(out_1.detach().numpy()),axis=-1))

输出:

[[ 0. 0.  0.  -0.15470695  0.   0. 0.  0.     0.  0.   ]
 [ 0.   0.  0.  -0.27988768  0.  0.0.   0.   0.   0.   ]]

不过,这在 TensorFlow 中确实有效:

# My encoder layer
encoder_layer = TransformerBlock(8, 2, 8)
# Random input
src = np.random.randn(2, 10, 8)
# Predict the output
out_0 = encoder_layer(src, training=False)
# Change the values at one of the positions (position 3 in this case)
src[:,3,:] += 1
# Predict once again the output
out_1 = encoder_layer(src, training=False)
# Check at which positions the outcomes are different between the two cases
# I summed in the embedding space direction
print(np.sum(np.abs(out_0),axis=-1) )

输出:

[[6.4196725 6.775745  6.946576  7.26213   6.473065  5.520765  6.201167
  7.1266503 6.3147016 6.614853 ]
 [5.565378  7.030789  6.768366  6.6065626 6.7277775 7.480627  6.6785836
  6.4560523 6.4248576 6.6436586]]

我的问题是:为什么在 PyTorch 中更改一个输入的输入不会影响所有位置的值?

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    来自documentation

    • batch_first - 如果True,则输入和输出张量提供为 (batch, seq, feature)。默认值:False

    换句话说,您的输入是 10 个 8 维批次,每个批次的序列长度为 2。您正在做的是在批次中样本 #4 的所有输入的所有维度上加 1,这 -- 不出所料 -- 只会改变该特定样本的输出值。

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 1970-01-01
      • 2019-05-14
      • 2017-10-29
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-03-19
      • 2016-07-24
      相关资源
      最近更新 更多