如何获取Hugging Face预训练模型的大小?

问题描述 投票:0回答:3

在尝试微调 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文档中搜索过,但我没有找到如何做。这里有人知道怎么做吗?

python deep-learning nlp pytorch huggingface-transformers
3个回答
2
投票

这里的尺寸有点模棱两可所以这两个答案都是

1。模型的大小(参数数量)。

使用

.num_parameters()
功能,例如

from transformers import MarianMTModel
model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")

model.num_parameters()

[出]:

74410496

2。模型的大小(在 GPU RAM 中)。

首先安装这个:

pip install -U nvidia-ml-py3

然后在代码中:

from pynvml import *
from transformers import MarianMTModel

def print_gpu_utilization():
    nvmlInit()
    handle = nvmlDeviceGetHandleByIndex(0)
    info = nvmlDeviceGetMemoryInfo(handle)
    print(f"GPU memory occupied: {info.used//1024**2} MB.")

model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
model.to('cuda')

print_gpu_utilization()

[出]:

GPU memory occupied: 884 MB.

1
投票

如果你面临

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

但是,对于你的问题:

我会推荐你objsize。它是一个计算“实际”大小(也称为“深度”大小)的库。所以一个简单的解决方案是:

import objsize
objsize.get_deep_size(model)

但是,文档说:

不包括非排他性对象。也就是说,也从程序中的其他地方引用的对象。这适用于计算对象的深度大小和遍历其后代。

这不应该是个问题,但是如果它对于您的模型来说仍然太小,您可以使用 Pympler,这是另一个通过递归计算“深度”大小的库。

另一种方法是自己实现一个

get_deep_size()
功能,例如来自这篇文章:

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

0
投票

预训练权重的大小可以在模型网站的文件下通过检查例如找到。

pytorch_model.bin
。对于 Bert,这给出了 ~440MB https://huggingface.co/bert-base-uncased/tree/main

请注意,最终出现在 GPU 上的模型可能比这更小或更大。

© www.soinside.com 2019 - 2024. All rights reserved.