【item() detach()用法】神经网络训练显存越来越大的原因之一

1 显存变大的原因

PyTorch采用动态图机制,通过tensor(以前是variable)来构建图,tensor里面包含的梯度信息用于反向传播求导。但不是所有变量都应该包含梯度(毕竟东西多,占“面积”就多),否则就会造成网络越跑,所占显存越大的情况,那怎么办呢?

2 loss.item()和loss.detach()解决问题

先看一段代码,

    for batch_idx, (inputs, targets) in enumerate(trainloader):
        inputs, targets = inputs.to(device), targets.to(device)
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = loss_func(outputs, targets)
        loss.backward()
        optimizer.step()
        
        print('loss:',loss)
        print('loss.item():',loss.item())
        print('loss.detach():',loss.detach())
        train_loss += loss.item()			# <----关键
        ...

输出:

loss: tensor(2.3391, device='cuda:0', grad_fn=<NllLossBackward>)
loss.item(): 2.3391051292419434
loss.detach(): tensor(2.3391, device='cuda:0')

很明显,loss.backward()在上面已经进行过了,下面去计算train_loss的时候就不要再带有梯度信息才合适。故有两种解决方案:

  • 使用loss.detach()来获取不需要梯度回传的部分。
    detach()通过重新声明一个变量,指向原变量的存放位置,但是requires_grad变为False。
  • 使用loss.item()直接获得对应的python数据类型。
    建议: 把除了loss.backward()之外的loss调用都改成loss.item()

3 感谢链接

https://www.zhihu.com/question/67209417/answer/344752405
  • 8
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
神经网络训练过程中,通常需要进行以下五个步骤:准备数据、定义模型、定义损失函数、定义优化器、开始训练。下面是一份使用PyTorch实现style transfer的代码,其中与这五个步骤相对应的代码部分已经用注释标出。 ```python import torch import torch.nn as nn import torchvision.transforms as transforms import torchvision.models as models from PIL import Image # 准备数据 transform = transforms.Compose([ transforms.Resize(512), # 调整图像大小 transforms.ToTensor(), # 将图像转换为Tensor transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # 标准化图像 ]) # 定义模型 class VGG(nn.Module): def __init__(self): super(VGG, self).__init__() self.features = models.vgg19(pretrained=True).features[:35] # 选择VGG19模型的前35层作为特征提取器 def forward(self, x): return self.features(x) # 定义损失函数 class StyleLoss(nn.Module): def __init__(self, target_feature): super(StyleLoss, self).__init__() self.target = self.gram_matrix(target_feature).detach() def forward(self, input): G = self.gram_matrix(input) self.loss = nn.functional.mse_loss(G, self.target) return input def gram_matrix(self, input): a, b, c, d = input.size() features = input.view(a * b, c * d) G = torch.mm(features, features.t()) return G.div(a * b * c * d) # 定义优化器 def get_input_optimizer(input_img): optimizer = torch.optim.Adam([input_img.requires_grad_()]) return optimizer # 开始训练 def run_style_transfer(content_img, style_img, num_steps=300, style_weight=1000000, content_weight=1): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 转换图像并将其放到设备上 content = transform(Image.open(content_img)).unsqueeze(0).to(device) style = transform(Image.open(style_img)).unsqueeze(0).to(device) input_img = content.clone().to(device).requires_grad_() # 定义模型和损失函数 model = VGG().to(device).eval() content_loss = nn.functional.mse_loss style_loss = StyleLoss(model(style).to(device)) # 定义优化器 optimizer = get_input_optimizer(input_img) # 迭代训练 for i in range(num_steps): input_img.data.clamp_(0, 1) optimizer.zero_grad() content_feature = model(content).detach() style_feature = model(input_img) content_loss = content_weight * content_loss(style_feature, content_feature) style_loss = 0 for ft, w in zip(style_feature, style_weight): style_loss += w * style_loss(ft, style_loss) loss = content_loss + style_loss loss.backward() optimizer.step() return input_img ``` 其中, - 准备数据:使用transforms定义了一组图像预处理方法,包括调整图像大小、将图像转换为Tensor、标准化图像。 - 定义模型:定义了一个VGG类,选择VGG19模型的前35层作为特征提取器。 - 定义损失函数:定义了一个StyleLoss类,用于计算风格损失。 - 定义优化器:定义了一个get_input_optimizer函数,用于获取一个Adam优化器。 - 开始训练:使用run_style_transfer函数开始训练,其中包括将图像转换到设备上、定义模型和损失函数、定义优化器、迭代训练过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值