解决:RuntimeError: CUDA out of memory. Tried to allocate 2.00 MiB

有文章说:减小batch_size 解决。但是减小到4还是解决不了。

上一篇文章CSDN:说with torch.no_grad(),就是不生成计算图。计算结果没有差异。

但是!!!对于计算机资源的占用却有差异!不生成计算图,GPU就会小很大的负担

如图,bath_size = 4,依然报错

在for i,(data,labels)  in enumerate(data)前加上这句代码:顺利执行。同时,batch_size取到128也照样可以运行。

所以出现此错误,不是单纯减小batch_size()这么简单。

参考:【E-02】内存不足RuntimeError: CUDA out of memory. Tried to allocate 16.00 MiB (GPU 0; 2.00 GiB total capacity; 1.34 GiB already allocated; 14.76 MiB free; 1.38 GiB reserved in total by PyTorch) - 忆凡人生 - 博客园

----------------------------更新--------------------------

经过一段时间的学习,现在遇到了预训练模型与微调。对with torch.no_grad()有了新的认识。

将与训练模型用于下游任务有如下几个中点:

1.构建token

2.修改模型

3.fine-turning模型

比如,我们利用bert-base-chinese做分类任务,

首先加载预训练模型

from transformers import AutoModel
model = AutoModel.from_pretrained('ckiplab/bert-base-chinese')

然后修改模型,加入用于不同下游任务的输出层

class Model(torch.nn.Module):
		def __init__(self):
				super().__init__()
                self.pretrained = AutoModel.from_pretrained('ckiplab/bert-base-chinese')
				self.fc = torch.nn.Linear(768,2)      # 为模型添加新的结构 输出层  2分类任务


		def forward(self, input_ids, labels):
				with torch.no_grad():                        # 原来的与训练模型不用更新参数
						out = self.pretrained(ipythonput_ids)               # 原始预训练模型输出结果
				out = self.fc(out.last_hidden_state[:,0])    # 放入下游具体任务的输出层中
				out = out.softmax(dim = 1)                   # 并进行softmax操作   
				reture out                                   # 才是最终的二分类输出结果

model = Model() 

在这里通过with torch.no_grad():在更新梯度的时候,就可以避开原来预训练好的模型。也就是说冻结元模型参数

或者通过如下操作也可以实现

class Model(torch.nn.Module):
		def __init__(self):
				super().__init__()
                self.pretrained = AutoModel.from_pretrained('ckiplab/bert-base-chinese')
				self.fc = torch.nn.Linear(768,2)      # 为模型添加新的结构 输出层  2分类任务


		def forward(self, input_ids, labels):
				for param in self.pretrained.parameters():    # 冻结元模型参数
	                param.requires_grad_(False)  
				out = self.pretrained(ipythonput_ids)               # 原始预训练模型输出结果
				out = self.fc(out.last_hidden_state[:,0])    # 放入下游具体任务的输出层中
				out = out.softmax(dim = 1)                   # 并进行softmax操作   
				reture out                                   # 才是最终的二分类输出结果

model = Model() 


而对于with torch.no_grad()  和   param.requires_grad_(False)  的区别,可以参考:什么时候该用with torch.no_grad()?什么时候该用.requires_grad ==False?_Y. F. Zhang的博客-CSDN博客

但我还没搞懂他们的区别。

  • 15
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
这个错误是由于CUDA内存不足导致的。根据引用\[1\]和引用\[2\]的信息,你的GPU总容量为4.00 GiB或10.76 GiB,但已经分配了2.34 GiB或1.82 GiB的内存,剩余的内存不足以分配14.00 MiB的内存。这可能是由于你的模型或数据的规模过大,导致内存不足。你可以尝试减小batch size或者使用更小的模型来减少内存的使用。另外,你还可以尝试设置max_split_size_mb参数来避免内存碎片化。关于内存管理和PYTORCH_CUDA_ALLOC_CONF的更多信息,请参考PyTorch的文档。 此外,根据引用\[3\]的信息,你还可以通过手动杀死占用GPU内存的进程来释放内存。你可以使用kill命令加上进程的PID来终止该进程,例如kill -9 31272。 综上所述,你可以通过减小batch size、使用更小的模型、设置max_split_size_mb参数或手动杀死占用内存的进程来解决CUDA内存不足的问题。 #### 引用[.reference_title] - *1* [已解决yolov5报错RuntimeError: CUDA out of memory. Tried to allocate 14.00 MiB](https://blog.csdn.net/Code_and516/article/details/129798540)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [解决RuntimeError: CUDA out of memory. Tried to allocate 14.00 MiB](https://blog.csdn.net/qq_43733107/article/details/126876755)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值