在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

Configuration model image

Custom class for Global attention image

训练循环

   
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()从最后一步清除旧的渐变,但前提是您所有的模型参数都在同一优化器中。

  1. VIMP的第一步是在处理CUDA内存问题时将批处理大小减小到一个。
  2. 使用SGD优化器进行检查。根据pytoch论坛中的post,Adam使用的内存比SGD多。
  3. 您的模型太大,初始化时会消耗大量GPU内存。尝试减小模型的大小,并检查其是否解决了内存问题。

编辑: Longformer git repo在https://github.com/allenai/longformer/issues/41有类似的问题。如果您使用类似的配置,这可能会很有用。 enter image description here

关于梯度检查点的一些想法。 enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...