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.self_attn.k_proj.weight: cuda:0

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

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

model.layers.10.mlp.up_proj.weight: cuda:0

model.layers.10.mlp.down_proj.weight: cuda:1

model.layers.10.input_layernorm.weight: cuda:1

model.layers.10.post_attention_layernorm.weight: cuda:1

 这里的 layers.10 就是第 11 层 transformer 层,里面包含 Attention 层和 MLP 层。

在每一个 transformer 层中,是包含跳跃连接的,如果输入层和输出层不在同一个 GPU 上,那么在做跳跃连接的 add 操作或者 * 操作时,就是报错,这就是问题所在。

解决办法

手动设置每个层的 GPU 分布:

# 对模型的每一层权重都指定部署的 GPU_ID
device_map = {
    ...
    "model.layers.10": "cuda:0",
    "model.layers.11": "cuda:1",
    ...
}
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    trust_remote_code=True,
    device_map=device_map,
)

举一反三

在 VL 大模型中,存在 LLM、VLM、aligner 等多种模型或权重,他们之间是存在相关计算的,如果报错同样的问题,那么可以把每个模型的输入层和输出层全部放在同一块 GPU 上,把其他层放在另外的 GPU 上,这样就可以保证他们之间的相关计算在同一台 GPU 上执行了。

### 解决 PyTorch 多GPU训练中 'Expected all tensors to be on the same device' 错误 当在多GPU环境中运行PyTorch程序时,如果遇到`RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:7 and cuda:0!`这样的错误提示,表明存在张量分布在不同的CUDA设备上。为了确保所有操作都能顺利进行,必须使参与计算的所有张量位于同一设备之上。 #### 确认并统一张量所在设备 可以通过`.to(device)`方法将指定的张量移动到特定的设备上去。对于模型及其参数还有输入数据都需要这样做: ```python import torch # 定义目标设备 target_device = torch.device('cuda:0') # 或者其他编号的GPU model.to(target_device) for param in model.parameters(): param.requires_grad_(True).to(target_device) input_tensor = input_tensor.to(target_device) ``` 此外,在定义优化器之前也需要保证模型已经在正确的设备上了[^4]。 #### 使用 `DataParallel` 实现简单并行化 为了让多个GPU能够共同分担工作负载,可以考虑采用`torch.nn.DataParallel`类封装网络结构,这会自动分配批次的数据给各个可用的GPU处理: ```python if torch.cuda.device_count() > 1: print(f"Using {torch.cuda.device_count()} GPUs!") model = torch.nn.DataParallel(model) model.to(target_device) ``` 需要注意的是,虽然`DataParallel`能简化跨多卡训练的过程,但在某些情况下可能会带来性能损失或是不便之处;此时推荐探索更先进的分布式训练方案如`DistributedDataParallel`[^2]。 #### 设置默认Tensor类型为CUDA Tensor 为了避免意外创建CPU上的tensor对象,可以在脚本开头设置全局默认tensor类型为CUDA tensor: ```python torch.set_default_tensor_type(torch.cuda.FloatTensor) ``` 不过这种方法并非总是适用,因为并不是所有的运算都支持这种类型的tensor作为输入[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值