用diffusers库从单文件safetensor加载sdxl模型(离线)
可用环境:
diffusers==0.33.1 torch==2.1.2
diffusers==0.32.2 torch==2.3.1
准备工作
首先要准备两样东西:1. 模型权重 2. 配置文件
sdxl模型权重6.46G:animeIllustDiffusion_v08.safetensors
sdxl模型配置(文件夹形式):
生成图片:
from diffusers import StableDiffusionXLPipeline
import torch
from PIL import Image# 加载模型
config_path = "./sdxl" ## sdxl的配置文件夹,里面包含一些json文件
model_path = "./animeIllustDiffusion_v08.safetensors" ## 单一模型文件pipe = StableDiffusionXLPipeline.from_single_file(model_path, # dtype=torch.bfloat16, ## 指定精度(一般不用考虑,单一模型文件只对应一种精度)config=config_path, ## 指定配置文件local_files_only=True) ## 只从本地加载pipe = pipe.to("cuda") # 节约显存,但是速度会慢
pipe.enable_vae_slicing()
pipe.enable_vae_tiling()
pipe.enable_sequential_cpu_offload()# 提示词
prompt = "pixel,pixel art,pixelart,xiangsu,xiang su,full body"# 设置生成参数
num_inference_steps = 28 # 推理步数,可根据需要调整
guidance_scale = 7 # 引导比例,控制生成图像与提示的匹配程度
generator = torch.manual_seed(0) # 随机性(不必要)
clip_skip = 1 # 字面意思,经常会在各大AI绘画模型下见到这个参数# 执行生成
with torch.no_grad():image = pipe(prompt = prompt,num_inference_steps = num_inference_steps,guidance_scale = guidance_scale,clip_skip = clip_skip,generator = generator).images[0]# 保存结果
image.save("output_image.png")
其它
6.46G的单文件,已经包含所有所需的权重了!
如果执行代码时发现它仍试图从HF上下载东西,那么就是有问题了!
此时,检查一下diffusers版本是不是太老了