(已解决)ValueError: You cannot cast a bitsandbytes model in a new dtype. Make sure to load the model using from_pretrained using the desired dtype by passing the correct torch_dtype

关于bitsandbytes模型加载的坑与解决方法

最近在使用bitsandbytes模型时遇到了一些问题,记录下来,希望能帮助到遇到类似问题的小伙伴。

问题描述

错误信息

  1. ValueError: You cannot cast a bitsandbytes model in a newdtype. Make sure to load the model usingfrom_pretrainedusing the desireddtypeby passing the correcttorch_dtypeargument.

  2. 不能同时使用量化配置、bfloat16、flash_attn。写了bnb_config之后,就在from_trained中直接加载这个配置就好了,不用其他配置了,否则冲突。

具体问题

  • bitsandbytes 4bit量化模型必须在from_pretrained时就指定torch_dtype,不能后续再.to(dtype)。

    • 你的模型代码内部有.to(torch_dtype),但你加载时没传torch_dtype,导致冲突。

    • 原因:bitsandbytes量化模型不允许在模型加载后再用.to(torch_dtype)更改数据类型,只能在模型调用时(AutoModel.from_pretrained())通过torch_dtype参数指定类型。

    • 模型加载时的dtype已经确定:一旦模型通过from_pretrained加载,权重的dtype就被锁定,不能再通过.to()方法更改。

    • 模型内部的self.to(torch_dtype)会强制转换dtype:你模型文件(modeling_sa2va_chat.py)里self.to(torch_dtype)这行代码会尝试把整个模型再转dtype,这对于bitsandbytes量化模型来说是非法操作,所以报错。

解决方案

删除非法转换代码

  • 删除self.to(torch_dtype):你删掉这行代码后,模型就不会再尝试转换dtype,自然不会报错。

修改建议

  • 修改模型文件:把模型文件modeling_sa2va_chat.py里面的self.to(torch_type)注释掉就好了。

总结

bitsandbytes模型的加载和使用有一些特殊的限制,尤其是关于dtype的指定。为了避免类似的错误,建议:

  • 在加载模型时,通过from_pretrained函数明确指定torch_dtype。

  • 避免在模型加载后使用.to(dtype)进行类型转换。

  • 如果使用了bnb_config,确保在from_pretrained中直接加载该配置,避免与其他配置冲突。

希望这些记录能帮助到你,少走一些弯路。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐