Pytorch 中“Assertion `t >= 0 && t < n_classes` failed error ” 解决方案

一、问题描述

关键错误为:

ClassNLLCriterion_updateOutput_no_reduce_kernel: block: [0,0,0], thread: [1,0,0] Assertion `cur_target >= 0 && cur_target < n_classes` failed.

二、问题排查

1、训练使用的model是transformers.OpenAIGPTLMHeadModel,对应的参数:

  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional, defaults to None) – Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set lm_labels = input_ids Indices are selected in [-100, 0, ..., config.vocab_size] All labels set to -100 are ignored (masked), the loss is only computed for labels in [0, ..., config.vocab_size]

labels在训练时是需要传入的,并且labels中取值范围为[-100, 0,1,...,vocab_size],如果设置为-100,表示该位置是被忽略的,训练过程中计算梯度的过程中是被masked。

而我使用的代码中,在数据处理阶段,为了对齐input_ids 的长度,使用-1来补全,导致出错。

2、验证阶段,为了评估模型训练效果,使用torch.nn.CrossEntropyLoss函数计算输入 logits 和目标之间的交叉熵损失。参数:

torch.nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=- 100, reduce=None, reduction='mean', label_smoothing=0.0)

之前为了与预处理得到的label进行匹配,ignore_index被设置为-1,导致计算loss的时候报错了。

三、解决方案

  1. labels中用-100进行补全;

  1. torch.nn.CrossEntropyLoss(ignore_index=- 1)更改为torch.nn.CrossEntropyLoss();

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值