torch.as_tensor转换input_ids时报dim1长度不匹配错误如何解决?
报错原因
报错核心原因是逐句编码时的padding参数仅做了单句内部对齐,没有将批次内所有样本的序列长度对齐到统一值,导致input_ids嵌套列表中每个子列表的长度不一致,而PyTorch张量要求同一维度的所有元素长度必须相同,因此转换时触发长度不匹配错误。
你代码中调用encode_plus时设置的padding=True在单句编码场景下是无效的——单句padding只能对齐到当前句子本身的长度,相当于没有生效。你给出的样例input_ids中四个子列表长度分别为12、15、32、17,长度完全不同,自然无法转换为张量。
另外你的代码还存在一处变量名不匹配的问题:调用Flaubert模型后返回值赋值给了hidden_state,但后续提取CLS特征时用的是未定义的outputs变量,修复完长度问题后需要同步修改。
可行修复方案
- 方案1:使用批量编码接口(最优推荐)
直接调用tokenizer的批量编码方法,不需要逐句循环,一步得到对齐后的张量,速度远高于逐句编码:
encoded_batch = flaubert_tokenizer( texte, add_special_tokens=True, truncation=True, padding='longest', # 对齐到批次内最长序列的长度,也可填'max_length'对齐到模型最大长度 max_length=512, # 可根据需求调整,不超过Flaubert默认最大长度512即可 return_attention_mask=True, return_tensors='pt' # 直接返回PyTorch张量,无需手动转换 ) input_ids = encoded_batch['input_ids'] attention_masks = encoded_batch['attention_mask']
- 方案2:逐句编码时指定统一对齐长度
如果必须保留逐句编码的逻辑,修改padding参数为max_length并指定统一的长度阈值:
input_ids = [] attention_masks = [] for sent in texte: encoded_sent = flaubert_tokenizer.encode_plus( sent, add_special_tokens=True, truncation=True, padding='max_length', # 对齐到指定的max_length max_length=133, # 可以填你需要的统一长度,比如报错中提到的133,或者512 return_attention_mask=True ) input_ids.append(encoded_sent.get('input_ids')) attention_masks.append(encoded_sent.get('attention_mask')) input_ids = torch.as_tensor(input_ids) attention_masks = torch.as_tensor(attention_masks)
- 方案3:手动补全不同长度的序列
如果需要自定义padding逻辑,可以手动统计批次最大长度,对短序列补padding位:
# 统计批次内最大序列长度 max_len = max([len(s) for s in input_ids]) pad_id = flaubert_tokenizer.pad_token_id # Flaubert默认padding id为1 # 补全所有序列到max_len长度 for i in range(len(input_ids)): pad_len = max_len - len(input_ids[i]) input_ids[i] += [pad_id] * pad_len attention_masks[i] += [0] * pad_len # attention mask的padding位填0 input_ids = torch.as_tensor(input_ids) attention_masks = torch.as_tensor(attention_masks)
内容的提问来源于stack exchange,提问作者emma
相关产品推荐
相关产品推荐

