CPU运行Stable Diffusion遇RuntimeError:期望BFloat16却得到Float
问题解决:CPU环境下Stable Diffusion的RuntimeError(BFloat16/Float类型不匹配)
错误原因分析
- autocast不适用于CPU环境:
autocast(device)是为GPU混合精度设计的,在CPU上强制启用会导致张量类型被转为bfloat16,但多数普通CPU对bfloat16支持不完善,引发模型参数与输入的类型冲突。 - 模型加载未指定兼容dtype:默认加载的模型可能包含bfloat16参数,而CPU运行时输入张量为float32,两者类型不匹配触发报错。
- 代码细节错误:
str(prompt)无法正确获取输入框内容,图像保存和展示环节存在变量名混淆问题。
修复步骤
- 移除CPU环境下的
autocast(device)上下文管理器。 - 加载模型时明确指定
torch_dtype=torch.float32,确保所有参数为CPU兼容的浮点类型。 - 修正输入获取逻辑:用
prompt.get()替代str(prompt)。 - 修复图像保存和展示的变量名错误,并保留图像引用避免Tkinter自动回收。
修改后的完整代码
import tkinter as tk import customtkinter as ctk from PIL import ImageTk, Image from auth_key import key import torch from diffusers import StableDiffusionPipeline # 创建应用 app = tk.Tk() app.geometry("532x622") app.title("Stable Diffusion App") ctk.set_appearance_mode("dark") # 输入框 prompt = ctk.CTkEntry(master=app, height=40, width=512) prompt.place(x=10, y=10) # 图像展示标签 lmain = ctk.CTkLabel(master=app, height=512, width=512) lmain.place(x=10, y=110) # 模型配置 modelid = "CompVis/stable-diffusion-v1-4" device = "cpu" try: # 明确指定float32 dtype加载模型 pipe = StableDiffusionPipeline.from_pretrained( modelid, use_auth_token=key, torch_dtype=torch.float32 ) pipe.to(device) except Exception as E: print(E) def generate(): # 移除CPU不兼容的autocast result = pipe(prompt.get()) image = result.images[0] # 保存图像 image.save('generatedimage.png') # 转换为Tkinter可用格式并保留引用 img = ImageTk.PhotoImage(image) lmain.img = img # 保留引用防止被回收 lmain.configure(image=img) # 生成按钮 trigger = ctk.CTkButton( master=app, height=40, width=120, font=("Arial", 20), text_color="white", fg_color="blue", command=generate ) trigger.configure(text="Generate") trigger.place(x=206, y=60) app.mainloop()
额外说明
- 若你的CPU支持bfloat16(如部分Intel Xeon或AMD Zen4处理器),可尝试保留
autocast并指定torch_dtype=torch.bfloat16,但普通CPU建议使用float32更稳定。 - 运行前确保依赖完整:
pip install torch diffusers transformers pillow customtkinter
内容的提问来源于stack exchange,提问作者Rahul Chauhan
相关产品推荐
相关产品推荐

