You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将CivitAI的.ckpt模型加载到PyTorch中进行推理?

解决CivitAI .ckpt模型加载到PyTorch并推理的问题

CivitAI上的Stable Diffusion类.ckpt模型本质是基于原版CompVis Stable Diffusion架构保存的权重文件,AUTOMATIC1111通过匹配对应基础模型架构直接加载,要实现同样的逻辑,核心是匹配基础模型版本并调整权重字典的键名以适配推理框架(比如diffusers)。以下是具体实现步骤:

关键前提

CivitAI模型都基于特定版本的Stable Diffusion(比如Deliberate基于SD 1.5),必须加载对应版本的基础模型架构,否则会因结构不匹配加载失败。

完整实现代码(基于diffusers框架)

1. 安装依赖

pip install diffusers transformers torch accelerate

2. 加载并适配模型

import torch
from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler

# 加载对应版本的基础Pipeline:Deliberate基于SD 1.5,所以用runwayml/stable-diffusion-v1-5
pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)

# 读取CivitAI的ckpt文件
ckpt_path = '/Users/XXXX/XXXX/model.ckpt'
checkpoint = torch.load(ckpt_path, map_location="cpu")

# 转换ckpt的权重键名,适配diffusers的Pipeline结构
def remap_ckpt_keys(ckpt_state_dict):
    adjusted_dict = {}
    for key, value in ckpt_state_dict.items():
        # 移除前缀"model."
        if key.startswith("model."):
            key = key[6:]
        # 映射CompVis架构的键到diffusers对应键
        if key.startswith("diffusion_model."):
            key = key.replace("diffusion_model.", "unet.")
        elif key.startswith("cond_stage_model.transformer."):
            key = key.replace("cond_stage_model.transformer.", "text_encoder.")
        elif key.startswith("first_stage_model."):
            key = key.replace("first_stage_model.", "vae.")
        adjusted_dict[key] = value
    return adjusted_dict

# 处理权重字典
adjusted_state_dict = remap_ckpt_keys(checkpoint['state_dict'])
# 加载权重,strict=False允许忽略部分无关键
pipe.load_state_dict(adjusted_state_dict, strict=False)
pipe.to("cuda" if torch.cuda.is_available() else "cpu")
pipe.eval()

# 生成图像
prompt = "a photo of a cat wearing a vintage hat"
with torch.no_grad():
    result = pipe(prompt)
result.images[0].save("generated_image.png")

核心问题解释

你之前的代码失败主要有两个原因:

  • 基础模型版本不匹配:用了SD 2.1的Pipeline加载基于SD 1.5的Deliberate模型,两者架构差异大,无法兼容。
  • 权重键名不匹配:CivitAI的ckpt采用CompVis原版SD的键名规则(比如diffusion_model.xxx对应Unet),而diffusers的Pipeline使用unet.xxx这类键名,必须转换后才能加载。

替代方案(完全复刻AUTOMATIC1111逻辑)

如果想直接用AUTOMATIC1111的底层代码逻辑加载,可以使用其项目内的模型加载模块:

import torch
from modules.sd_models import load_model

# 直接加载ckpt(需配置AUTOMATIC1111的运行环境)
model = load_model(ckpt_path)
model.eval()

# 复用AUTOMATIC1111的推理代码执行生成
# ...

内容的提问来源于stack exchange,提问作者Vandan Chopra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:35:29