【问题标题】:Pytorch model training without using forwardPytorch模型训练不使用forward
【发布时间】:2021-07-01 00:42:52
【问题描述】:

我正在训练 CLIP 模型。 这是模型的源代码https://github.com/openai/CLIP/blob/main/clip/model.py

基本上 CLIP 对象是这样构造的:

class CLIP(nn.module):
   ...
   def encode_image(self, image):
     return self.visual(image.type(self.dtype))

   def encode_text(self, text):
    x = ... 
    ...
    return x

   def forward(self, image, text):
     image_features = self.encode_image(image)
     text_features = self.encode_text(text)
     ...
     return logits_per_image, logits_per_text

除了图像和文本对之外的转发方法,因为我想将 CLIP 重新用于其他任务(文本-文本对),我没有使用 CLIP 的转发,但我正在使用 CLIP 中定义的其他方法。我的训练代码如下所示:

for k in range(epoch):
  for batch in dataloader :
    x,y = batch
    y1 = model.encode_text(x[first_text_part])
    y2 = model.encode_text(x[second_text_part])
    <calculate loss, backward, step, etc>

问题是,在 1 个 epoch 之后,即使损失不是 nan,所有梯度都变成 nan。
我怀疑 PyTorch 只能通过 forward 方法传播梯度。
一些消息来源说 forward 没有那么特别 (https://discuss.pytorch.org/t/must-use-forward-function-in-nn-module/50943/3),但其他消息来源说使用 torch 进行编码必须使用 forward (https://stackoverflow.com/a/58660175/12082666)。

问题是,我们可以不使用前向方法来训练 Pytorch 网络吗?

【问题讨论】:

    标签: python deep-learning pytorch


    【解决方案1】:

    pytorch 中的 forward() 并不是什么新鲜事。它只是在调用时附加您的网络图。反向传播不太依赖 forward(),因为梯度是通过图传播的。

    唯一不同的是,在pytorch源码中,forward类似于call()方法,所有的钩子都注册在nn.Module中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-03
      • 2019-11-06
      • 2019-09-11
      • 2018-02-20
      • 2017-08-19
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多