【问题标题】:BERT NER: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory firstBERT NER:无法将 CUDA 张量转换为 numpy。首先使用 Tensor.cpu() 将张量复制到主机内存
【发布时间】:2021-03-09 22:03:03
【问题描述】:

我想在 colab 上训练我的 BERT NER 模型。但是出现以下错误

代码:

tr_logits = tr_logits.detach().cpu().numpy()
tr_label_ids = torch.masked_select(b_labels, (preds_mask == 1))
tr_batch_preds = np.argmax(tr_logits[preds_mask.squeeze()], axis=1)
tr_batch_labels = tr_label_ids.to(device).numpy()
tr_preds.extend(tr_batch_preds)
tr_labels.extend(tr_batch_labels)

错误:

Using TensorFlow backend.
Saved standardized data to ./data/en/combined/train_combined.txt.
Saved standardized data to ./data/en/combined/dev_combined.txt.
Saved standardized data to ./data/en/combined/test_combined.txt.
Constructed SentenceGetter with 25650 examples.
Constructed SentenceGetter with 8934 examples.
Loaded training and validation data into DataLoaders.
Initialized model and moved it to cuda.
Initialized optimizer and set hyperparameters.
Epoch:   0% 0/5 [00:00<?, ?it/s]Starting training loop.
Epoch:   0% 0/5 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "/content/FYP_Presentation/python/main.py", line 102, in <module>
    valid_dataloader,
  File "/content/FYP_Presentation/python/utils/main_utils.py", line 431, in train_and_save_model
    tr_batch_preds = torch.max(tr_logits[preds_mask.squeeze()], axis=1)
  File "/usr/local/lib/python3.6/dist-packages/torch/tensor.py", line 412, in __array__
    return self.numpy()
TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

我该如何解决这个问题?

【问题讨论】:

  • 我认为问题在于 preds_mask 在 GPU 上,而 tr_logits 不在。尝试将 preds_mask 也移动到 cpu。

标签: nlp pytorch bert-language-model named-entity-recognition


【解决方案1】:

在代码的第一行中,tr_logits = tr_logits.detach().cpu().numpy() 已经将tr_logits 转换为一个 numpy 数组。在引发错误的行中:

tr_batch_preds = torch.max(tr_logits[preds_mask.squeeze()], axis=1)

程序要做的第一件事是评估tr_logits[preds_mask.squeeze()]。既然tr_logits 是numpy 数组,那么它的索引preds_mask 也必须是numpy 数组。因此程序调用preds_mask.numpy() 将其更改为一个numpy 数组。但是,它在 GPU 上,因此出现错误。

我建议在一个程序中一直使用 numpy 数组或 pytorch 张量,而不是交替使用。

【讨论】:

    猜你喜欢
    • 2019-05-22
    • 2020-07-28
    • 2021-06-19
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多