gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:16:04 26 4
gpt4 key购买 nike

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

a related question在 stackoverflow 上,但错误消息与我的情况不同。

cuda 运行时错误 (710):设备端断言在/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 新兴实体代码从浏览器访问 token 分类: 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

最佳答案

也许问题出在这一行:

torch.backends.cudnn.enabled = False

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

关于python - 如何修复 google colab 上的 cuda 运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68698065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com