2301_80844976 2024-07-10 14:19 采纳率: 0%
浏览 3

RuntimeError

跑代码的时候,这段代码遇见了报错:

 def train_emb(self, images, captions, lengths, image_lengths=None, warmup_alpha=None):
        """One training step given images and captions."""
        self.Eiters += 1
        self.logger.update('Eit', self.Eiters)
        self.logger.update('lr', self.optimizer.param_groups[0]['lr'])

        captions_all = captions.reshape(captions.size(0) * captions.size(1), captions.size(2))
        caption_lens = lengths.reshape(-1)

        # compute the embeddings    #(256, 1024)
        img_emb, cap_emb = self.forward_emb(images, captions_all, caption_lens, image_lengths=image_lengths)

        # measure accuracy and record loss
        self.optimizer.zero_grad()
        loss = self.forward_loss(img_emb, cap_emb)

        if warmup_alpha is not None:
            loss = loss * warmup_alpha

        # compute gradient and update
        loss.backward(retain_graph=True)

        # Adversarial Training
        img_real = img_emb.detach() # img_real(256,1024)
        cap_real = cap_emb.detach() # cap_real(256,1024)

        # Generate fake embeddings
        img_fake = self.img_gen(cap_emb).detach()   # cap_emb(256,1024), img_fake(256,2048)
        cap_fake = self.txt_gen(img_emb).detach()   #img_emb(256,1024),  cap_fake(256,1024)

        # Train discriminators
        img_real.requires_grad = True
        img_fake.requires_grad = True
        cap_real.requires_grad = True
        cap_fake.requires_grad = True

        disc_img_real = self.img_disc(img_real)  # img_real(256,1024) disc_img_real()
        disc_img_fake = self.img_disc(img_fake)  #img_fake(256,1024)  disc_img_fake()

        disc_cap_real = self.txt_disc(cap_real)  #cap_real(256,1024) dis_cap_real()
        disc_cap_fake = self.txt_disc(cap_fake)  #cap_fake(256,1024) dis_cap_fake()

        disc_loss_img = self.gan_criterion(disc_img_real, True) + self.gan_criterion(disc_img_fake, False)
        disc_loss_cap = self.gan_criterion(disc_cap_real, True) + self.gan_criterion(disc_cap_fake, False)
        total_disc_loss = disc_loss_img + disc_loss_cap

        total_disc_loss.backward(retain_graph=True)

        clip_grad_norm_(self.params, self.grad_clip)
        self.optimizer.step()

        # Train generators
        #self.gen_optim.zero_grad()
        img_fake.requires_grad = False
        cap_fake.requires_grad = False

        self.optimizer.zero_grad()  # Clear gradients for generator training

        gen_img = self.img_gen(cap_emb) #gen_img(256,1024)
        gen_cap = self.txt_gen(img_emb)#gen_cap(256,1024)

        disc_img_fake_for_gen = self.img_disc(gen_img) #disc_img_fake_for_gen(256,1)
        disc_cap_fake_for_gen = self.txt_disc(gen_cap) #disc_cap_fake_for_gen(256,1)

        gen_loss_img = self.gan_criterion(disc_img_fake_for_gen, True)
        gen_loss_cap = self.gan_criterion(disc_cap_fake_for_gen, True)
        total_gen_loss = gen_loss_img + gen_loss_cap

        total_gen_loss.backward()

        clip_grad_norm_(self.params, self.grad_clip)
        self.optimizer.step()

debug调试发现报错在

total_gen_loss.backward()

报错内容是:

Traceback (most recent call last):
  File "train.py", line 274, in <module>
    main()
  File "train.py", line 99, in main
    train(opt, train_loader, model, epoch, val_loader)
  File "train.py", line 155, in train
    model.train_emb(images, captions, lengths, image_lengths=img_lengths)
  File "/home/s1/ESA-main4/ESA_BERT/lib/vse.py", line 290, in train_emb
    total_gen_loss.backward()
  File "/home/s1/anaconda3/envs/s1_new/lib/python3.8/site-packages/torch/_tensor.py", line 525, in backward
    torch.autograd.backward(
  File "/home/s1/anaconda3/envs/s1_new/lib/python3.8/site-packages/torch/autograd/__init__.py", line 267, in backward
    _engine_run_backward(
  File "/home/s1/anaconda3/envs/s1_new/lib/python3.8/site-packages/torch/autograd/graph.py", line 744, in _engine_run_backward
    return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
RuntimeError: Output 0 of TBackward0 is a view and its base or another view of its base has been modified inplace. This view is the output of a function that returns multiple views. Such functions do not allow the output views to be modified inplace. You should replace the inplace operation by an out-of-place one.

请问怎么解决这个报错啊?

  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2024-07-10 14:20
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    遇到这个 RuntimeError 错误,通常是因为 PyTorch 在执行反向传播时,发现某个张量被原地修改了,而这个张量是一个视图(view),它的基张量或其基张量的其他视图也被修改了。在 PyTorch 中,如果一个张量是另一个张量的视图,那么它们共享相同的内存空间,原地修改会导致问题。

    根据你提供的错误信息,问题可能出在以下几处:

    1. 原地操作:错误信息提示存在原地操作,你需要检查代码中是否有使用原地操作符,如 +=-= 等,这些操作可能会修改张量,导致视图问题。

    2. 张量视图:错误信息中提到“Output 0 of TBackward0 is a view”,这意味着在某个操作中返回了张量的视图。你需要检查 self.forward_emb, self.img_gen, 和 self.txt_gen 这三个函数,确保它们不会返回视图。

    3. detach()clone():在进行原地操作之前,使用 .detach().clone() 来避免这个问题。.detach() 会创建一个新的张量,它与计算图分离,不会影响梯度计算;.clone() 则会创建张量的副本。

    4. 梯度裁剪clip_grad_norm_ 函数调用可能也与此问题有关,需要确保它不会对原张量造成影响。

    为了解决这个问题,你可以尝试以下步骤:

    • 审查函数实现:检查 self.forward_emb, self.img_gen, 和 self.txt_gen 这三个函数的实现,确保它们不返回依赖于输入张量的视图。
    • 避免原地操作:如果发现原地操作,考虑替换为非原地操作,或者在操作前使用 .detach().clone()
    • 梯度裁剪:检查 clip_grad_norm_ 函数的实现,确保它不会影响张量的视图。

    最后,如果你需要进一步的帮助,可以提供更多的代码细节,或者具体的函数实现,这样我可以提供更具体的建议。

    目前,我没有找到特定的参考链接,但是这些步骤是根据 PyTorch 的文档和社区经验总结的常见解决方案。如果你需要更详细的解释或示例,可以查看 PyTorch 的官方文档,特别是关于自动微分和梯度计算的部分。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 7月10日

悬赏问题

  • ¥15 c++ gmssl sm2验签demo
  • ¥15 关于模的完全剩余系(关键词-数学方法)
  • ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
  • ¥30 模拟电路 logisim
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?