如何获得预训练模型的拥抱脸大小?

2024-09-30 16:34:01 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图微调一个怀抱面孔的预训练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'

我已经在拥抱脸文档中搜索过了,但是我没有找到如何做。这里有人知道怎么做吗


Tags: 模型configsizemodeldevice错误torchxml
1条回答
网友
1楼 · 发布于 2024-09-30 16:34:01

如果您面临CUDA out of memory错误,问题主要不是模型,而是训练数据。您可以减少batch_size(并行使用的训练示例的数量),因此您的gpu只需要在每次迭代中处理几个示例,而不需要处理大量示例

但是,对于你的问题:

我推荐你。它是一个计算“真实”大小(也称为“深度”大小)的库。因此,一个简单的解决方案是:

import objsize
objsize.get_deep_size(model)

然而,文件说:

Excluding non-exclusive objects. That is, objects that are also referenced from somewhere else in the program. This is true for calculating the object's deep size and for traversing its descendants.

这应该不是问题,但是如果它对于您的模型仍然太小,您可以使用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

相关问题 更多 >