运行Qwen3-VL-4B-Instruct推理时,如何修复张量设备不一致错误?
解决Qwen3-VL-4B-Instruct模型推理时的设备不匹配错误
这个错误的核心原因是:processor生成的输入张量默认留在CPU,但模型已通过device_map="auto"加载到CUDA设备,两者设备不一致触发了index_select的设备检查报错。
修复步骤
在生成inputs后,添加一行代码将所有输入张量迁移到模型所在设备:
inputs = inputs.to(model.device)
修改后的完整代码
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor # default: Load the model on the available device(s) model = Qwen3VLForConditionalGeneration.from_pretrained( "Qwen/Qwen3-VL-4B-Instruct", dtype="auto", device_map="auto" ) # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios. # model = Qwen3VLForConditionalGeneration.from_pretrained( # "Qwen/Qwen3-VL-4B-Instruct", # dtype=torch.bfloat16, # attn_implementation="flash_attention_2", # device_map="auto", # ) processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-4B-Instruct") messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg", }, {"type": "text", "text": "Describe this image."}, ], } ] # Preparation for inference inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) # 将输入张量移到模型所在设备 inputs = inputs.to(model.device) # Inference: Generation of the output generated_ids = model.generate(**inputs, max_new_tokens=128) generated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) ] output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False ) print(output_text)
额外验证点
- 可通过
print(model.device)确认模型所在设备,确保输入张量迁移到对应设备 - 多GPU环境下,
device_map="auto"会将模型分片到不同GPU,但model.device指向主CUDA设备,此方法依然有效
内容的提问来源于stack exchange,提问作者Franck Dernoncourt




