llama factory 命令行推理流程
错误:RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
原因:参与运算的两个或多个变量,有的在CPU上,有的在GPU上
解决:
首先找到报错的行,看看计算时都用到哪些变量或者数据,然后在调试模式下使用.is_cuda这个属性去查看到底哪些是在GPU上,哪些是在CPU上,然后把它们统一都放在CPU,或者统一放在GPU上就可以。
1. 强制统一设备(推荐)
修改文件:modeling_qwen2_vl.py
修改内容:
python
# 原代码
delta = cache_position[0] + self.rope_deltas if cache_position is not None else 0
# 修改后
delta = (cache_position[0].to(self.rope_deltas.device) + self.rope_deltas) if cache_position is not None else 0
作用:
将 cache_position[0] 显式移动到与 self.rope_deltas 相同的设备(cuda:0)37。
2. 模型初始化修正
修改文件:模型定义部分(如 __init__ 方法)
修改内容:
python
# 原代码可能未指定设备
self.rope_deltas = torch.tensor(...) # 默认可能在CPU或错误GPU
# 修改后(添加设备指定)
self.rope_deltas = torch.tensor(...).to(device) # device需从外部传入
调用位置:
在模型实例化时传递设备参数:
python
model = QWen2VLModel(config).to(device) # device需提前定义
=