简体   繁体   English

在 PyTorch 中调用 forward 方法与调用 model 实例

[英]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 挂钩不会有任何效果

Detailed answer can be found in this post详细答案可以在这篇文章中找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM