在尝试微调 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文档中搜索过,但我没有找到如何做。这里有人知道怎么做吗?
这里的尺寸有点模棱两可所以这两个答案都是
使用
.num_parameters()
功能,例如
from transformers import MarianMTModel
model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
model.num_parameters()
[出]:
74410496
首先安装这个:
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.
如果你面临
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
预训练权重的大小可以在模型网站的文件下通过检查例如找到。
pytorch_model.bin
。对于 Bert,这给出了 ~440MB https://huggingface.co/bert-base-uncased/tree/main
请注意,最终出现在 GPU 上的模型可能比这更小或更大。