创建模型嵌入时出现 OutOfMemoryError

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

刚开始学习抱脸变形金刚。我正在尝试创建大量文本的嵌入,但我总是遇到 outOfMemoryErrors。我不确定我做错了什么。我是 python 和变形金刚的新手。下面是我的代码。

tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-xxl")
model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-xxl", device_map="auto", torch_dtype=torch.float16)

def getSentenceEmbedding(sentenceText, languageModel, modelTokenizer):
    sentence_tokens = modelTokenizer(sentenceText, return_tensors="pt")
    sentence_input_ids = sentence_tokens.input_ids.to('cuda')
    encodings = languageModel.encoder(input_ids=sentence_input_ids, attention_mask=sentence_tokens.attention_mask, return_dict=True)
    del sentence_input_ids
    del sentence_tokens
    gc.collect()
    torch.cuda.empty_cache()
    return torch.mean(encodings.last_hidden_state, dim=1)

#bookstrings 是一本书中大约 500 个段落的数组

paragEmbeddings=[]
for parag in bookstrings:
    torch.cuda.empty_cache()
    paragEmbeddings.append((getSentenceEmbedding(parag,model,tokenizer)))

outOfMemoryError:CUDA 内存不足。尝试分配 20.00 MiB(GPU 0;23.90 GiB 总容量;22.91 GiB 已分配;9.56 MiB 可用;总共保留 22.99 GiB PyTorch)如果保留内存是 >> 已分配内存,请尝试设置 max_split_size_mb 以避免碎片。请参阅内存管理和 PYTORCH_CUDA_ALLOC_CONF

的文档

我尝试在几个地方进行垃圾收集,但这似乎并不重要。一旦我开始循环并创建词嵌入,outOfMemoryError 在数组的第 25 段触发。

我想生成所有没有错误的词嵌入。我是 python 和 huggingface 的新手,所以我认为我在内存分配方面做错了。

加载模型前的内存占用

0 特斯拉 M40 24GB 341MiB / 24576MiB 1 特斯拉 M40 24GB 10MiB / 23040MiB

加载模型后的内存占用

0 特斯拉 M40 24GB 13590MiB / 24576MiB 1 特斯拉 M40 24GB 12816MiB / 23040MiB

错误后的内存占用

0 特斯拉 M40 24GB 24457MiB / 24576MiB 1 特斯拉 M40 24GB 12816MiB / 23040MiB

python word-embedding transformer-model huggingface language-model
© www.soinside.com 2019 - 2024. All rights reserved.