1.报错内容

ValueError: Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'truncation=True' to have batched tensors with the same length.

2.相关代码

def tokenize(example):
    label=example['label']
    text=example['text']
    # example是一个字典,包含两个键text和label,对应的值都是List[str]
    input_len=len(tokenizer(
        text,
        truncation=True,
        max_length=cutoff_len,
        padding=False,
        return_tensors=None,
    )['input_ids'])
    result = tokenizer(
        text+label,
        truncation=True,
        max_length=cutoff_len,
        padding='max_length',
        return_tensors=None,
    )
    result['labels'] = result['input_ids'].copy()
    text_len=len(result['input_ids'])
    result['labels'] = [-100] * input_len + result['labels'][input_len:]
    return result
train_dataset=train_dataset.map(tokenize)
#要注意 这里train_dataset并不是我们想象中的3列,而是五列:#text,label,input_ids,labels,attention_mask
data_collator = transformers.DataCollatorForSeq2Seq(
    tokenizer=tokenizer,
    pad_to_multiple_of=8,
    return_tensors="pt",
    padding=False
)
trainer=Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    data_collator=data_collator,
    # eval_dataset=eval_dataset,
    compute_metrics=compute_metrics
)

3.解决方案

data_collator要对dataset中的所有列做填充,对于input_ids, attention_mask, labels 模型知道如何pad(因为他们是列表或者张量),但是对于text和label来说,他们是字符串,模型不知道该怎么填充

我们需要移去这两列,使用如下代码:

train_dataset=train_dataset.remove_columns(['label','text'])

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐