微调Wav2Vec2 XLSR卡纳达语模型时遇TypeError报错求助
问题排查:Wav2Vec2微调时TypeError: list indices must be integers or slices, not tuple
问题概述
使用自有数据集微调Wav2Vec2 XLSR卡纳达语模型,设置padding=True后仍报错,更新代码后触发TypeError,报错指向模型调用行:
logits = model(inputs["input_values"], attention_mask=inputs["attention_mask"]).logits
相关代码与报错栈
完整代码片段
import torch import torchaudio from datasets import load_dataset from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor # Load the test dataset test_dataset = dataset['test'] processor = Wav2Vec2Processor.from_pretrained("/content/container_0/ckpts/checkpoint-1000") model = Wav2Vec2ForCTC.from_pretrained("/content/container_0/ckpts/checkpoint-1000") resampler = torchaudio.transforms.Resample(48000, 16_000) # Preprocessing the datasets. # We need to read the audio files as arrays def speech_file_to_array_fn(batch): speech_array, sampling_rate = torchaudio.load(batch["path"]) batch["speech"] = resampler(speech_array).squeeze().numpy() return batch test_dataset = test_dataset.map(speech_file_to_array_fn) max_length = 50 def prepare_inputs(batch): input_values = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True).input_values # Pad the inputs to the maximum length input_values = torch.nn.functional.pad(input_values, (0, max_length - input_values.shape[-1]), value=0) attention_mask = torch.ones(input_values.shape) return {"input_values": input_values[0][:max_length], "attention_mask": attention_mask[0][:max_length]} def prepare_inputs(batch): input_values = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True).input_values # Pad the inputs to the maximum length input_values = torch.nn.functional.pad(input_values, (0, max_length - input_values.shape[-1]), value=0) attention_mask = torch.ones(input_values.shape) return {"input_values": input_values[0], "attention_mask": attention_mask[0]} inputs = test_dataset.map(prepare_inputs, batched=True, batch_size=len(test_dataset)) with torch.no_grad(): logits = model(inputs["input_values"], attention_mask=inputs["attention_mask"]).logits predicted_ids = torch.argmax(logits, dim=-1) print("Prediction:", processor.batch_decode(predicted_ids)) print("Reference:", test_dataset["text"][:2])
报错栈
TypeError Traceback (most recent call last) in <cell line: 42>() 41 42 with torch.no_grad(): ---> 43 logits = model(inputs["input_values"], attention_mask=inputs["attention_mask"]).logits 44 45 predicted_ids = torch.argmax(logits, dim=-1) 5 frames /usr/local/lib/python3.9/dist-packages/transformers/models/wav2vec2/modeling_wav2vec2.py in forward(self, input_values) 431 432 def forward(self, input_values): ---> 433 hidden_states = input_values[:, None] 434 435 # make sure hidden_states require grad for gradient_checkpointing TypeError: list indices must be integers or slices, not tuple
问题原因
- 输入类型不匹配:
test_dataset.map处理后,inputs["input_values"]和inputs["attention_mask"]是Python列表而非PyTorch张量,模型内部执行input_values[:, None]张量切片操作时,列表不支持元组形式的索引,触发报错。 - 预处理逻辑错误:当
batched=True时,processor返回的input_values已经是[batch_size, seq_len]的批量张量,代码中通过input_values[0]只保留了批量中的第一条数据,导致最终inputs存储的是单条数据的列表,而非完整批量张量。
解决方法
步骤1:修正prepare_inputs函数
去掉input_values[0]和attention_mask[0]的索引操作,直接返回批量张量;同时处理原序列长度超过max_length的情况:
def prepare_inputs(batch): input_values = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True).input_values # 处理长度:不足max_length则padding,超过则截断 pad_length = max(max_length - input_values.shape[-1], 0) input_values = torch.nn.functional.pad(input_values, (0, pad_length), value=0)[:, :max_length] attention_mask = torch.ones(input_values.shape) # 直接返回批量张量,不要取[0] return {"input_values": input_values, "attention_mask": attention_mask}
步骤2:将列表转为张量后传入模型
map方法会自动将张量转为列表存储,因此在调用模型前需要手动转回张量:
with torch.no_grad(): # 把列表转成PyTorch张量 input_values = torch.tensor(inputs["input_values"]) attention_mask = torch.tensor(inputs["attention_mask"]) # 传入模型 logits = model(input_values, attention_mask=attention_mask).logits
验证修改
执行修改后的代码,模型将接收正确形状的张量输入,即可正常生成logits并完成预测。
内容的提问来源于stack exchange,提问作者Aniruddh H S
相关产品推荐
相关产品推荐

