如何修复 google colab 上的 cuda 运行时错误?

Posted

技术标签:

【中文标题】如何修复 google colab 上的 cuda 运行时错误?【英文标题】:How can I fix cuda runtime error on google colab? 【发布时间】:2021-10-12 07:42:19 【问题描述】:

我正在尝试使用 BERT 和 pytorch 在 Hugging Face 页面之后执行命名实体识别示例:Token Classification with W-NUT Emerging Entities。

*** 上有a related question,但错误信息与我的情况不同。

cuda runtime error (710) : device-side assert triggered at /pytorch/aten/src/THC/generic/THCTensorMath.cu:29

我无法修复上述 cuda 运行时错误。

如何使用 运行时类型 GPU 在 google colab 上执行示例代码?

错误

trainer.train()

# Error Message
/usr/local/lib/python3.7/dist-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
    147     Variable._execution_engine.run_backward(
    148         tensors, grad_tensors_, retain_graph, create_graph, inputs,
--> 149         allow_unreachable=True, accumulate_grad=True)  # allow_unreachable flag
    150 
    151 

RuntimeError: cuda runtime error (710) : device-side assert triggered at /pytorch/aten/src/THC/generic/THCTensorMath.cu:29

代码

教程中介绍的原始数据和代码我没有更改,Token Classification with W-NUT Emerging Entities。

使用 W-NUT Emerging Entities 代码从浏览器访问令牌分类: custom_datasets.ipynb - Colaboratory

from pathlib import Path
import re

def read_wnut(file_path):
    file_path = Path(file_path)

    raw_text = file_path.read_text().strip()
    raw_docs = re.split(r'\n\t?\n', raw_text)
    token_docs = []
    tag_docs = []
    for doc in raw_docs:
        tokens = []
        tags = []
        for line in doc.split('\n'):
            token, tag = line.split('\t')
            tokens.append(token)
            tags.append(tag)
        token_docs.append(tokens)
        tag_docs.append(tags)

    return token_docs, tag_docs

texts, tags = read_wnut('wnut17train.conll')
from sklearn.model_selection import train_test_split
train_texts, val_texts, train_tags, val_tags = train_test_split(texts, tags, test_size=.2)
unique_tags = set(tag for doc in tags for tag in doc)
tag2id = tag: id for id, tag in enumerate(unique_tags)
id2tag = id: tag for tag, id in tag2id.items()
from transformers import DistilBertTokenizerFast
tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-cased')
train_encodings = tokenizer(train_texts, is_split_into_words=True, return_offsets_mapping=True, padding=True, truncation=True)
val_encodings = tokenizer(val_texts, is_split_into_words=True, return_offsets_mapping=True, padding=True, truncation=True)
import numpy as np

def encode_tags(tags, encodings):
    labels = [[tag2id[tag] for tag in doc] for doc in tags]
    encoded_labels = []
    for doc_labels, doc_offset in zip(labels, encodings.offset_mapping):
        # create an empty array of -100
        doc_enc_labels = np.ones(len(doc_offset),dtype=int) * -100
        arr_offset = np.array(doc_offset)

        # set labels whose first offset position is 0 and the second is not 0
        doc_enc_labels[(arr_offset[:,0] == 0) & (arr_offset[:,1] != 0)] = doc_labels
        encoded_labels.append(doc_enc_labels.tolist())

    return encoded_labels

train_labels = encode_tags(train_tags, train_encodings)
val_labels = encode_tags(val_tags, val_encodings)
import torch
import os

#os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
torch.backends.cudnn.enabled = False
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
# torch.backends.cudnn.enabled

if not train_on_gpu:
    print('CUDA is not available.  Training on CPU ...')
else:
    print('CUDA is available!  Training on GPU ...')

class WNUTDataset(torch.utils.data.Dataset):
    def __init__(self, encodings, labels):
        self.encodings = encodings
        self.labels = labels

    def __getitem__(self, idx):
        item = key: torch.tensor(val[idx]) for key, val in self.encodings.items()
        item['labels'] = torch.tensor(self.labels[idx])
        return item

    def __len__(self):
        return len(self.labels)

train_encodings.pop("offset_mapping") # we don't want to pass this to the model
val_encodings.pop("offset_mapping")
train_dataset = WNUTDataset(train_encodings, train_labels)
val_dataset = WNUTDataset(val_encodings, val_labels)
from transformers import DistilBertForTokenClassification
model = DistilBertForTokenClassification.from_pretrained('distilbert-base-cased', num_labels=len(unique_tags))
from transformers import DistilBertForSequenceClassification, Trainer, TrainingArguments, DistilBertForTokenClassification
from sklearn.metrics import precision_recall_fscore_support
import tensorflow as tf

def compute_metrics(pred):
    labels = pred.label_ids
    preds = pred.predictions.argmax(-1)
    precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='binary')
    acc = accuracy_score(labels, preds)
    return 
        'accuracy': acc,
        'f1': f1,
        'precision': precision,
        'recall': recall
    

training_args = TrainingArguments(
    output_dir='./results',          # output directory
    num_train_epochs=3,              # total number of training epochs
    per_device_train_batch_size=16,  # batch size per device during training
    per_device_eval_batch_size=64,   # batch size for evaluation
    warmup_steps=500,                # number of warmup steps for learning rate scheduler
    weight_decay=0.01,               # strength of weight decay
    logging_dir='./logs',            # directory for storing logs
    logging_steps=10,
)

model = DistilBertForTokenClassification.from_pretrained("distilbert-base-uncased")

trainer = Trainer(
    model=model,                         # the instantiated ???? Transformers model to be trained
    args=training_args,                  # training arguments, defined above
    train_dataset=train_dataset,         # training dataset
    eval_dataset=val_dataset,             # evaluation dataset
    compute_metrics=compute_metrics
)

trainer.train()

我做了什么

我检查了 cuda 和 GPU 相关设置。

#os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
torch.backends.cudnn.enabled = False
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
# torch.backends.cudnn.enabled

if not train_on_gpu:
    print('CUDA is not available.  Training on CPU ...')
else:
    print('CUDA is available!  Training on GPU ...')

#output
CUDA is available!  Training on GPU ...

training_args.device

#output
device(type='cuda', index=0)

回复答案

当我注释掉该部分时,

#os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
#torch.backends.cudnn.enabled = False

当我没有重置运行时,错误消息变成了下面。

/usr/local/lib/python3.7/dist-packages/torch/autograd/__init__.py in _make_grads(outputs, grads)
     49                 if out.numel() != 1:
     50                     raise RuntimeError("grad can be implicitly created only for scalar outputs")
---> 51                 new_grads.append(torch.ones_like(out, memory_format=torch.preserve_format))
     52             else:
     53                 new_grads.append(None)

RuntimeError: CUDA error: device-side assert triggered
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.

如果我重置运行时,消息是一样的。

RuntimeError: cuda runtime error (710) : device-side assert triggered at /pytorch/aten/src/THC/generic/THCTensorMath.cu:29

【问题讨论】:

【参考方案1】:

也许问题出在这一行:

torch.backends.cudnn.enabled = False

您可以评论或删除它,然后重试。

【讨论】:

感谢您的回答。添加了结果和可用的相同代码 custom_datasets.ipynb - Colaboratory,可从浏览器获得。 custom_datasets.ipynb - Colaboratory(colab.research.google.com/github/huggingface/notebooks/blob/…)

以上是关于如何修复 google colab 上的 cuda 运行时错误?的主要内容,如果未能解决你的问题,请参考以下文章

如何修复 Colab 上的“错误:pytorch3d 构建***失败”错误?

如何在 Google Colab GPU 中安装 CUDA

在 Google Colab 上从 CUDA 11.2 降级到 11.1 或 10.2(找不到包问题)

不使用多处理但在使用 PyTorch DataLoader 时在 google colab 上出现 CUDA 错误

将Colab上的CUDA版本降级到9

Google Colab Fine Tuning BERT Base Cased with Transformers and PyTorch 中出现间歇性“RuntimeError: CUDA out