在尝试微调 Hugging Face 预训练的 XML Roberta 模型时,我不断收到 CUDA out of memory
错误。所以,我首先想知道的是预训练模型的大小。
model = XLMRobertaForCausalLM.from_pretrained('xlm-roberta-base', config=config)
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
model.to(device)
我试图用
获得模型的大小sys.getsizeof(model)
而且,不出所料,我得到了错误的结果。结果我得到56,这是python对象的大小。
但是,我尝试了 model. element_size()
,但出现错误
ModuleAttributeError: 'XLMRobertaForCausalLM' object has no attribute 'element_size'
我在 Hugging Face 文档中搜索过,但我还没有找到如何去做。这里有人知道怎么做吗?
答案 0 :(得分:1)
如果您面临 CUDA out of memory
错误,则问题主要不是模型,而是训练数据。您可以减少 batch_size
(并行使用的训练示例的数量),因此您的 GPU 每次迭代只需处理几个示例,而不是大量示例。
但是,对于您的问题:
我会推荐你objsize。它是一个计算“真实”尺寸(也称为“深度”尺寸)的库。所以一个简单的解决方案是:
import objsize
objsize.get_deep_size(model)
但是,文档说:
<块引用>排除非独占对象。也就是说,也从程序中的其他地方引用的对象。这对于计算对象的深度大小和遍历其后代是正确的。
这应该不是问题,但如果您的模型尺寸仍然太小,您可以使用 Pympler,这是另一个通过递归计算“深度”尺寸的库。
另一种方法是自己实现一个 get_deep_size()
函数,例如来自this article:
import sys
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size