Enable MPS backend for bitsandbytes quantization

用户在 Apple MPS 后端(Apple Silicon 芯片)上运行 diffusers 中的 bitsandbytes 量化功能时,尝试加载量化模型(如 FLUX.2-dev 的 4-bit 版本),diffusers 拒绝使用量化,因为当前的 GPU 检测逻辑不支持 MPS。

Enable MPS backend for bitsandbytes quantization

Enable MPS backend for bitsandbytes quantization

快速结论:此问题出现在 macOS Apple Silicon 硬件上使用 diffusers 进行 bitsandbytes 量化时,会触发 “No GPU found” 错误。

问题场景

用户在 Apple MPS 后端(Apple Silicon 芯片)上运行 diffusers 中的 bitsandbytes 量化功能时,尝试加载量化模型(如 FLUX.2-dev 的 4-bit 版本),diffusers 拒绝使用量化,因为当前的 GPU 检测逻辑不支持 MPS。

报错原文

No GPU found. A GPU is needed for quantization.

原因分析

diffusers 中 src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py 第 64-65 行的 GPU 检测条件仅检查了 torch.cuda.is_available()torch.xpu.is_available(),没有检查 torch.mps.is_available()。虽然 bitsandbytes 已在 PR #1818 和 #1875 中添加了基本的 MPS 后端支持,但 diffusers 的量化器入口检查仍然阻止了其在 Apple 硬件上运行。

环境排查

  • 确认操作系统是否为 macOS 且硬件为 Apple Silicon(M1/M2/M3/M4 系列)
  • 确认 torch.backends.mps.is_available() 返回 True
  • 确认已安装支持 MPS 后端的 bitsandbytes 版本(建议≥0.45.0)
  • 确认 diffusers 版本(问题在 0.30.0 及以上版本可能仍存在,直到 PR #13915 合入)

解决步骤

  1. 替换 bnb_quantizer.py 中的 GPU 检测逻辑:找到文件 src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py,将第 64-65 行的 GPU 检测条件替换为:
    if not (torch.cuda.is_available() or torch.xpu.is_available() or torch.mps.is_available()):
        raise RuntimeError("No GPU found. A GPU is needed for quantization.")
  2. 可选:如果遇到 device_map 相关错误,还需要在 update_device_map 方法中添加 MPS 设备映射支持:
    def update_device_map(self, device_map):
        if device_map is None:
            if torch.xpu.is_available():
                current_device = f"xpu:{torch.xpu.current_device()}"
            elif torch.mps.is_available():
                current_device = "mps"
            else:
                # 原有逻辑
                ...
  3. 等待官方 PR 合并:相关修复已在 PR #13915 中提交,合入后可通过升级 diffusers 获得原生支持。

验证方法

修改后,尝试在 Apple Silicon Mac 上运行 from_pretrained 加载一个量化模型(例如 black-forest-labs/FLUX.2-dev 的 4-bit 版本),应不再触发 “No GPU found” 报错,且可以正常使用 MPS 后端进行推理。

参考来源

huggingface/diffusers #13361

GamsGo AI

AI 工具推荐

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

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

了解 GamsGo AI

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

celebrityanime
celebrityanime
文章: 9822

发表回复

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