一、问题描述
关键错误为:
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的时候报错了。
三、解决方案
labels中用-100进行补全;
torch.nn.CrossEntropyLoss(ignore_index=- 1)更改为torch.nn.CrossEntropyLoss();