Safetensors checkpoint loading fails with a torch.device map_location

未关闭 适合新手
#15,459 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
78/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python, pytorch

调研方向

从 src/diffusers/models/model_loading_utils.py 开始。这里的 load_state_dict 会处理 safetensors 检查点。将其对 map_location 的处理方式与 .bin 路径进行比较。使用 issue 中只有一个张量的复现示例确认故障,并检查相关的模型加载测试。传入 map_location=torch.device("cpu") 时能够加载有效检查点,即为完成。

由索引模型根据 Issue 内容生成。

描述

Describe the bug

I get an OSError when I pass torch.device("cpu") to load_state_dict for a valid safetensors checkpoint. The helper accepts torch.device in its type annotation, and the same argument works for .bin checkpoints. I have a small fix for the safetensors call and would like to submit it.

Reproduction
from pathlib import Path
from tempfile import TemporaryDirectory

import torch
from safetensors.torch import save_file

from diffusers.models.model_loading_utils import load_state_dict

with TemporaryDirectory() as directory:
    path = Path(directory) / "model.safetensors"
    save_file({"weight": torch.ones(1)}, path)
    load_state_dict(path, map_location=torch.device("cpu"))
Context

I found this while reading checkpoint loading in model_loading_utils.py, then reproduced it with the one-tensor checkpoint above.

Logs
SafetensorError: device device(type='cpu') is invalid
OSError: Unable to load weights from checkpoint file
System Info

Diffusers 0.44.0.dev0 at 08d5de3, Linux x86_64, Python 3.14.5, PyTorch 2.15.0+cpu, safetensors 0.8.0. CPU only, single process.

主要语言
Python
星标
35k
派生
7.5k
平均合并
3 天 2 小时
30 天内合并 PR
58

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

huggingface/diffusers 的其他 Issue

查看 huggingface/diffusers 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。