[英]Calling the forward method in PyTorch vs. calling the model instance
A lot of the PyTorch tutorials I've been viewing do something like this.我一直在查看的许多 PyTorch 教程都是这样做的。
Define model:定义 model:
class Network(nn.Module):
def __init__():
super().__init__()
self.conv1 = ..
...
def forward(x)
...
...
Once the Network has been instantiated ( net = Network()
), the people in the tutorials write net(input_data)
instead of net.forward(input_data)
.一旦网络被实例化(
net = Network()
),教程中的人写net(input_data)
而不是net.forward(input_data)
。 I tried net.forward()
and it gives the same results as net()
.我尝试
net.forward()
,它给出了与net()
相同的结果。
Why is this a common practice, and also why does this work?为什么这是一种常见的做法,以及为什么会这样?
You should avoid calling Module.forward
.您应该避免调用
Module.forward
。 The difference is that all the hooks are dispatched in the __call__
function see this , so if you call .forward
and have hooks in your model, the hooks won't have any effect.不同之处在于所有的钩子都是在
__call__
function中调度的,所以如果你调用.forward
并在你的 model 中有钩子,钩子不会有任何效果。
Inshort when you call Module.forward
, pytorch hooks wont have any effect简而言之,当您调用
Module.forward
时, pytorch 挂钩不会有任何效果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.