Pytorch CUDA在训练时出现OutOfMemory错误

2024-04-25 19:23:55 发布

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

我想在AWS Sagemaker中训练一个PyTorch天才模特。 执行此操作时,会出现以下错误:

RuntimeError: CUDA out of memory. Tried to allocate 84.00 MiB (GPU 0; 11.17 GiB total capacity; 9.29 GiB already allocated; 7.31 MiB free; 10.80 GiB reserved in total by PyTorch)

对于培训,我使用了sagemaker.pytorch.estimator.pytorch类

我尝试了不同的实例类型变体,从ml.m5、g4dn到p3(即使是96GB的内存)。 在ml.m5中,使用cpumemoryisue获取错误;在g4dn中,使用gpumemoryisue获取错误;在P3中,使用gpumemoryisue主要是因为Pytorch只使用了8*12GB中的一个12GB的GPU

无法在任何地方完成此培训,即使在本地,也尝试使用CPU机器,但出现以下错误:

RuntimeError: [enforce fail at ..\c10\core\CPUAllocator.cpp:72] data. DefaultCPUAllocator: not enough memory: you tried to allocate 67108864 bytes. Buy new RAM!

模型培训脚本:

    corpus = ClassificationCorpus(data_folder, test_file='../data/exports/val.csv', train_file='../data/exports/train.csv')
                                          
    print("finished loading corpus")

    word_embeddings = [WordEmbeddings('glove'), FlairEmbeddings('news-forward-fast'), FlairEmbeddings('news-backward-fast')]

    document_embeddings = DocumentLSTMEmbeddings(word_embeddings, hidden_size=512, reproject_words=True, reproject_words_dimension=256)

    classifier = TextClassifier(document_embeddings, label_dictionary=corpus.make_label_dictionary(), multi_label=False)

    trainer = ModelTrainer(classifier, corpus, optimizer=Adam)

    trainer.train('../model_files', max_epochs=12,learning_rate=0.0001, train_with_dev=False, embeddings_storage_mode="none")

附言:我能够在本地GPU机器上使用4GB GTX 1650 DDR5内存使用更小的数据集来训练相同的体系结构,而且速度非常快


Tags: todatagpu错误traincorpuspytorchlabel
2条回答

好的,经过两天的持续调试,我们找到了根本原因。 我所理解的是Flair对句子长度没有任何限制,从字数的意义上讲,它是以最长的句子作为最大值。 因此,这就引起了问题,因为在我的例子中,有150万行的内容很少,这太多了,无法将嵌入到内存中,即使是16GB的GPU。 就这样,它被打破了

要解决这个问题:对于包含这么长单词的内容,您可以从这些内容的任何部分(左/右/中间的任何位置)提取n个单词(在我的例子中为10K),然后对其余部分进行主干,或者如果比较数量非常少,则直接忽略这些记录进行培训

在这之后,我希望你能在训练中取得进步,就像我的情况一样

附言:如果你遵循这个思路并且面临类似的问题,请随时回复,这样我就可以探索并帮助你解决这个问题

此错误是因为GPU内存不足。你可以试试看

  1. 减少训练数据的大小

  2. 减少模型的大小,即隐藏层的数量或深度

  3. 您还可以尝试减少批量大小

相关问题 更多 >