如何解决在Google Colab中运行Longformer模型时使Cuda内存不足使用Bert的类似代码可以正常工作
我正在使用Longformer模型进行文本分类。我什至只取了前100行数据框。我收到内存错误。我正在使用Google Colab。
这是我的模特:
model = LongformerForMultiSequenceClassification.from_pretrained('allenai/longformer-base-4096',config=config)
# Accessing the model configuration
configuration = model.config
训练循环
for epoch in tqdm(range(1,epochs+1)):
model.train()
loss_train_total = 0
progress_bar = tqdm(DataLoader_train,desc='Epoch {:1d}'.format(epoch),leave=False,disable=False)
for batch in progress_bar:
#this will empty the gradients from the prevIoUs iterations
model.zero_grad()
#take out inputs
batch = tuple(b.to(device) for b in batch)
inputs = {'input_ids': batch[0],'attention_mask': batch[1],'labels': batch[2],}
#insert the input into the model and get the result
outputs = model(**inputs)
#calculate loss
loss = outputs[0]
loss_train_total += loss.item()
#this will calculate the gradients
loss.backward()
# for preventening gradient explosion
torch.nn.utils.clip_grad_norm_(model.parameters(),1.0)
#this will update the weights
optimizer.step()
#optimizing learning rate
scheduler.step()
progress_bar.set_postfix({'training_loss': '{:.3f}'.format(loss.item()/len(batch))})
torch.save(model.state_dict(),f'/content/Gdrive/My Drive/finetuned_longformer_epoch_{epoch}.model')
#torch.save(model.state_dict(),f'checkpoint{epoch}.pth')
tqdm.write(f'\nEpoch {epoch}')
loss_train_avg = loss_train_total/len(DataLoader_train)
tqdm.write(f'Training loss: {loss_train_avg}')
val_loss,predictions,true_vals = evaluate(DataLoader_validation)
val_f1 = f1_score_func(predictions,true_vals)
tqdm.write(f'Validation loss: {val_loss}')
tqdm.write(f'F1 score (Weighted): {val_f1}')
错误:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-32-7e534d564c0a> in <module>()
20 }
21 #insert the input into the model and get the result
---> 22 outputs = model(**inputs)
23
24 #calculate loss
12 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in dropout(input,p,training,inplace)
971 return (_VF.dropout_(input,training)
972 if inplace
--> 973 else _VF.dropout(input,training))
974
975
RuntimeError: CUDA out of memory. Tried to allocate 182.00 MiB (GPU 0; 11.17 GiB total capacity; 10.23 GiB already allocated; 59.81 MiB free; 10.69 GiB reserved in total by PyTorch)
您可以检查我的配置文件和模型结构以及“全球关注”的自定义类,或者我的完整代码在colab上:
https://colab.research.google.com/drive/19JkCht_4u6UrwcUcWNnSD2YtnsJYer0H?usp=sharing
我使用BERT运行了类似的代码,并且可以正常工作。
我是数据科学的新手。请帮忙。
解决方法
很少有检查点可以解决此错误。
在optimizer.zero_grad()
之后致电optimizer.step()
。 model.zero_grad()
从最后一步清除旧的渐变,但前提是您所有的模型参数都在同一优化器中。
- VIMP的第一步是在处理CUDA内存问题时将批处理大小减小到一个。
- 使用SGD优化器进行检查。根据pytoch论坛中的post,Adam使用的内存比SGD多。
- 您的模型太大,初始化时会消耗大量GPU内存。尝试减小模型的大小,并检查其是否解决了内存问题。
编辑: Longformer git repo在https://github.com/allenai/longformer/issues/41有类似的问题。如果您使用类似的配置,这可能会很有用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。