You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LLaVA模型RuntimeError:CUDA设备不匹配问题求助

解决LLaVA-v1.5-13b张量跨设备RuntimeError问题
  • 排查ask_image函数内所有张量的设备一致性

    • 先打印关键张量的设备信息,定位残留cuda:0的张量:
      print("Image features device:", image_features.device)
      print("Prompt tensor device:", prompt_tensor.device)
      
    • 重点检查图像特征提取环节,CLIP编码器可能仍绑定在cuda:0,即便主模型已转至cuda:1,需同步转移编码器设备:
      image_encoder = image_encoder.to("cuda:1")
      
  • 强制统一所有输入张量到目标设备

    • 不要仅转移模型,需将图像特征、提示词张量、attention mask等所有输入显式转至cuda:1,在ask_image函数内添加:
      image_features = image_features.to("cuda:1")
      prompt_tensor = prompt_tensor.to("cuda:1")
      if attention_mask is not None:
          attention_mask = attention_mask.to("cuda:1")
      
    • 改用device_map参数指定模型全组件设备,替代单纯的.to(device),避免多模态组件分散在不同设备:
      model = AutoModelForCausalLM.from_pretrained(
          "liuhaotian/LLaVA-v1.5-13b",
          device_map="cuda:1",
          torch_dtype=torch.float16
      )
      
  • 从预处理阶段锁定设备

    • 图像加载后转张量时直接指定cuda:1,避免后续再转移出现设备不一致:
      from torchvision import transforms
      preprocess = transforms.Compose([
          transforms.Resize((224,224)),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
      ])
      image_tensor = preprocess(image).unsqueeze(0).to("cuda:1")
      
  • 全局设置默认CUDA设备

    • 在脚本开头强制将默认设备设为cuda:1,避免部分库自动使用cuda:0:
      import torch
      torch.cuda.set_device("cuda:1")
      

内容的提问来源于stack exchange,提问作者Md. Rifat Ullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 14:07:10