RuntimeError: Tensor on device cpu is not on the expected device meta!

用户在 llama.cpp 中使用 convert_hf_to_gguf.py 转换 Microsoft 的 BitNet 模型( microsoft/bitnet-b1.58-2B-4T ),运行时出现模型不支持的错误,修正注册后出现 RuntimeError: Tensor on device

RuntimeError: Tensor on device cpu is not on the expected device meta!

RuntimeError: Tensor on device cpu is not on the expected device meta!

快速结论:这个报错通常发生在 llama.cpp 的 convert_hf_to_gguf.py 转换 BitNet 模型时,根源是一个大小写拼写错误(BitnetForCausalLM vs BitNetForCausalLM)导致注册失败,继而引发转换路径上的张量设备元数据不匹配。优先排查 TEXT_MODEL_MAP@ModelBase.register 中的模型名称是否大小写一致。

问题场景

用户在 llama.cpp 中使用 convert_hf_to_gguf.py 转换 Microsoft 的 BitNet 模型(microsoft/bitnet-b1.58-2B-4T),运行时出现模型不支持的错误,修正注册后出现 RuntimeError: Tensor on device cpu is not on the expected device meta!。环境为 Linux 上的 Docker 容器,仅使用 CPU。

报错原文

RuntimeError: Tensor on device cpu is not on the expected device meta!
ERROR:hf-to-gguf:Model BitNetForCausalLM is not supported

原因分析

根本原因:Microsoft 的模型配置使用 BitNetForCausalLM(大写 N),而 llama.cpp 的转换器在 TEXT_MODEL_MAP@ModelBase.register 中注册为 BitnetForCausalLM(小写 n)。这个大小写不匹配导致模型加载时抛出 Model BitNetForCausalLM is not supported 错误。

修正注册后出现的 RuntimeError: Tensor on device cpu is not on the expected device meta! 是一个后续的、先前未测试到的 bug,发生在 dequant_bitnet 函数处理张量时,可能原因包括:

  • 张量在 CPU 上进行操作,但期望在 meta 设备上(通常用于延迟初始化或元数据加载)。
  • 转换路径中某些步骤未正确处理设备上下文,尤其是在 Docker 容器内的 CPU-only 环境中。
  • 该模型类型的转换路径在提交时未经过完整测试。

环境排查

  • 确认 Python 版本(用户环境使用 Python 3.12)。
  • 确认 PyTorch 版本(docker 内默认版本,需检查兼容性)。
  • 确认 llama.cpp 版本(用户使用 version: 9977 (6b4dc2116))。
  • 确认 convert_hf_to_gguf.pyconversion/__init__.pyTEXT_MODEL_MAP 是否包含 "BitNetForCausalLM": "bitnet" 条目。
  • 确认 conversion/bitnet.py@ModelBase.register 是否包含 "BitNetForCausalLM" 参数。
  • 确认运行环境是否仅使用 CPU(无 CUDA),可能导致某些张量操作设备不匹配。

解决步骤

  1. 修正模型名称注册:打开 conversion/__init__.py,在 TEXT_MODEL_MAP 中添加或修改为:
    "BitnetForCausalLM": "bitnet",
    "BitNetForCausalLM": "bitnet",
  2. 修正注册装饰器:打开 conversion/bitnet.py,将 @ModelBase.register("BitnetForCausalLM") 修改为:
    @ModelBase.register("BitnetForCausalLM", "BitNetForCausalLM")
  3. 解决 RuntimeError(可优先尝试):该错误是一个已知但未完全解决的后续问题。尝试在转换前设置 PyTorch 设备为 CPU:
    import torch
    torch.set_default_device('cpu')
    或者修改 conversion/base.py 中的 dequant_bitnet 函数,确保张量明确移动到 CPU:
    data = weight.unsqueeze(0).cpu().expand((4, *orig_shape)).cpu() >> shift.cpu()
  4. 替代方案:如果以上步骤无法解决,考虑使用其他工具(如 Project Zero)进行转换和推理,避免复杂的 Python 依赖设置。

验证方法

重新运行转换命令:
python3 convert_hf_to_gguf.py microsoft/bitnet-b1.58-2B-4T --remote --outtype tq2_0 --outfile /models/bitnet-tq2.gguf

观察输出日志:

  • 不应再出现 Model BitNetForCausalLM is not supported 错误。
  • 不应再出现 RuntimeError: Tensor on device cpu is not on the expected device meta!
  • 成功生成 GGUF 文件。

参考来源

ggml-org/llama.cpp #25629

GamsGo AI

AI 工具推荐

想把多个 AI 模型放在一个入口?

GamsGo AI 集成 ChatGPT、DeepSeek、Gemini、Claude、Midjourney、Veo 等常用模型,适合写作、绘图、视频和日常 AI 工作流。

了解 GamsGo AI

推广链接:通过此链接购买,我可能获得佣金,不影响你的价格。

celebrityanime
celebrityanime
文章: 14467

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注