昨天我遇到了this question并且第一次注意到线性层的权重 nn.Linear
申请前需要转置matmul
.
Code应用权重:
output = input.matmul(weight.t())
这是什么原因?
为什么权重不是从一开始就在转置形状中,所以它们不需要在应用图层之前每次都转置?
最佳答案
我在这里找到了答案:
Efficient forward pass in nn.Linear #2159
这背后似乎没有真正的推理。然而,转置操作似乎并没有减慢计算速度。
根据上述问题,在期间转发 通过转置操作 (几乎)免费 在计算方面。而在反向传球期间省略转置操作 实际上会进行计算 效率较低 与当前的实现。
该问题的最后一篇文章对其进行了很好的总结:
It's historical weight layout, changing it is backward-incompatible. Unless there is some BIG benefit in terms of speed or convenience, we wont break userland.
https://github.com/pytorch/pytorch/issues/2159#issuecomment-390068272
关于matrix - PyTorch - nn.Linear 权重的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465608/