RuntimeError: Expected all tensors to be on the same device, but found at least two devices

问题描述

大模型时代,使用低端 GPU 很难单卡部署模型,因为单卡的显存有限,像 V100,只有 16G,这时候就需要使用单机多卡,甚至是多机多卡进行部署。

在进行单机多卡部署时,很容易遇到一个问题:

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cuda:1!

这是因为在模型推理时,对来自于不同 GPU 上的数据进行操作。

背景知识

做大模型的都应该知道,我们一般使用 transformers 库加载模型,比如:

model = AutoModelForCausalLM.from_pretrained(
    model_path,
    trust_remote_code=True,
    device_map="auto",
)

这里的 device_map="auto" 就是为了让模型权重自动分配到不同的 GPU 上,还可以是 "balanced" 或者 "balanced_low_0" 等,但是一般使用这些还是解决不了问题,这时候需要使用另外一种输入格式:字典 Dict,即手动确定哪些层分配到哪个 GPU 上。

问题定位

我们可以打印出每一层所在的 GPU 来进行定位:

for name, p in model.named_parameters():
    print(f"{name}: {p.device}")

浏览打印信息,你应该能找到类似于这种的信息:

model.layers.10.self_attn.q_proj.weight: cuda:0

model.layers.10

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值