当前位置: 首页 > news >正文

【AI 绘画】模型转换与快速生图(基于diffusers)

AI 绘画- 模型转换与快速生图(基于diffusers)

1. 本章介绍

本次主要展示一下不同框架内文生图模型转换,以及快速生成图片的方法。

SDXL文生图

2. sdxl_lightning基本原理

模型基本原理介绍如下

利用蒸馏方法获取小参数模型。首先,论文从128步直接蒸馏到32步,并使用MSE损失。在早期阶段,论文发现MSE已足够。此外,在此阶段,论文仅应用了无分类器指导(CFG),并使用了6的指导尺度,而没有使用任何负面提示。

接着,论文通过对抗性损失按照以下顺序进一步减少步数:32 → 8 → 4 → 2 → 1。在每个阶段,论文首先使用条件目标进行训练,以保持概率流动,然后使用无条件目标进行训练,以放松模式覆盖。

在每个阶段,论文首先使用LoRA并结合这两个目标进行训练,然后合并LoRA,并进一步用无条件目标训练整个UNet。论文发现微调整个UNet可以获得更好的性能,而LoRA模块可以用于其他基础模型。论文的LoRA设置与LCM-LoRA 相同,即在所有卷积和线性权重上使用64的秩,但不包括输入和输出卷积以及共享的时间嵌入线性层。论文没有在判别器上使用LoRA,并且在每个阶段都会重新初始化判别器。

3. 环境安装

diffusers是Hugging Face推出的一个diffusion库,它提供了简单方便的diffusion推理训练pipe,同时拥有一个模型和数据社区,代码可以像torchhub一样直接从指定的仓库去调用别人上传的数据集和pretrain checkpoint。除此之外,安装方便,代码结构清晰,注释齐全,二次开发会十分有效率。

# pip
pip install --upgrade diffusers[torch]
# conda
conda install -c conda-forge diffusers

4. 代码实现

主要测试代码:

4.1 sdxl_lightning文生图


from diffusers import DPMSolverMultistepScheduler,UNet2DConditionModel,StableDiffusionXLPipeline,DiffusionPipeline
import torch
from safetensors.torch import load_filedevice = "cuda"# load both base & refiner
# stabilityai/stable-diffusion-xl-base-1.0
# base = DiffusionPipeline.from_pretrained(
#     "./data/data282269/",device_map=None,torch_dtype=torch.float16, variant="fp16", use_safetensors=True
# )
# !unzip  ./data/data283423/SDXL.zip -D ./data/data283423/
# load base model
unet = UNet2DConditionModel.from_config("./data/data283423/SDXL/unet/config.json").to( device, torch.float16)
unet.load_state_dict(load_file("./data/data283423/sdxl_lightning_4step_unet.safetensors", device= device))base = StableDiffusionXLPipeline.from_pretrained("./data/data283423/SDXL/", unet=unet, torch_dtype=torch.float16, variant="fp16"
).to( device)# # scheduler
# base.scheduler = DPMSolverMultistepScheduler.from_config(
#     base.scheduler.config, timestep_spacing="trailing"
# )base.to("cuda")# Define how many steps and what % of steps to be run on each experts (80/20) here
n_steps = 4
high_noise_frac = 0.8prompt = "masterpiece, best quality,Realistic, cinematic quality,A majestic lion jumping from a big stone at night "#"A majestic lion jumping from a big stone at night"
negative_prompt = ('flaws in the eyes, flaws in the face, flaws, lowres, non-HDRi, low quality, worst quality,')
# run both experts
image = base(prompt=prompt,negative_prompt = negative_prompt,num_inference_steps=n_steps,#  denoising_end=high_noise_frac,#output_type="latent",
).images[0]image.save("./data/section-1/h5.png")

4.2 safetensors模型加载

如果想将safetensors模型加载到diffusers中,需要使用如下代码


pipeline = AutoPipelineForImage2Image.from_pretrained("stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
)

转换为


from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckptbase = download_from_original_stable_diffusion_ckpt(from_safetensors = True,checkpoint_path_or_dict = "./data/data282269/SDXL_doll.safetensors"
)

4.2 safetensors模型转换

如果想将safetensors模型转化为diffusers常用格式,需要使用如下代码


"""Conversion script for the LDM checkpoints."""import argparse
import importlibimport torchfrom diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckptif __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("--checkpoint_path", default="./data/data282269/SDXL_doll.safetensors", type=str, help="Path to the checkpoint to convert." #required=True, )# !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yamlparser.add_argument("--original_config_file",default=None,type=str,help="The YAML config file corresponding to the original architecture.",)parser.add_argument("--config_files",default=None,type=str,help="The YAML config file corresponding to the architecture.",)parser.add_argument("--num_in_channels",default=None,type=int,help="The number of input channels. If `None` number of input channels will be automatically inferred.",)parser.add_argument("--scheduler_type",default="pndm",type=str,help="Type of scheduler to use. Should be one of ['pndm', 'lms', 'ddim', 'euler', 'euler-ancestral', 'dpm']",)parser.add_argument("--pipeline_type",default=None,type=str,help=("The pipeline type. One of 'FrozenOpenCLIPEmbedder', 'FrozenCLIPEmbedder', 'PaintByExample'"". If `None` pipeline will be automatically inferred."),)parser.add_argument("--image_size",default=None,type=int,help=("The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2"" Base. Use 768 for Stable Diffusion v2."),)parser.add_argument("--prediction_type",default=None,type=str,help=("The prediction type that the model was trained on. Use 'epsilon' for Stable Diffusion v1.X and Stable"" Diffusion v2 Base. Use 'v_prediction' for Stable Diffusion v2."),)parser.add_argument("--extract_ema",action="store_true",help=("Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"" or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"" higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."),)parser.add_argument("--upcast_attention",action="store_true",help=("Whether the attention computation should always be upcasted. This is necessary when running stable"" diffusion 2.1."),)parser.add_argument("--from_safetensors",default= "true",#  action="store_true",help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.",)parser.add_argument("--to_safetensors",action="store_true",help="Whether to store pipeline in safetensors format or not.",)parser.add_argument("--dump_path", default="./data/data282269/", type=str,  help="Path to the output model.")parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")parser.add_argument("--stable_unclip",type=str,default=None,required=False,help="Set if this is a stable unCLIP model. One of 'txt2img' or 'img2img'.",)parser.add_argument("--stable_unclip_prior",type=str,default=None,required=False,help="Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.",)parser.add_argument("--clip_stats_path",type=str,help="Path to the clip stats file. Only required if the stable unclip model's config specifies `model.params.noise_aug_config.params.clip_stats_path`.",required=False,)parser.add_argument("--controlnet", action="store_true", default=None, help="Set flag if this is a controlnet checkpoint.")parser.add_argument("--half", action="store_true", help="Save weights in half precision.")parser.add_argument("--vae_path",type=str,default=None,required=False,help="Set to a path, hub id to an already converted vae to not convert it again.",)parser.add_argument("--pipeline_class_name",type=str,default=None,required=False,help="Specify the pipeline class name",)args = parser.parse_args()if args.pipeline_class_name is not None:library = importlib.import_module("diffusers")class_obj = getattr(library, args.pipeline_class_name)pipeline_class = class_objelse:pipeline_class = Nonepipe = download_from_original_stable_diffusion_ckpt(checkpoint_path_or_dict=args.checkpoint_path,original_config_file=args.original_config_file,config_files=args.config_files,image_size=args.image_size,prediction_type=args.prediction_type,model_type=args.pipeline_type,extract_ema=args.extract_ema,scheduler_type=args.scheduler_type,num_in_channels=args.num_in_channels,upcast_attention=args.upcast_attention,from_safetensors=args.from_safetensors,device=args.device,stable_unclip=args.stable_unclip,stable_unclip_prior=args.stable_unclip_prior,clip_stats_path=args.clip_stats_path,controlnet=args.controlnet,vae_path=args.vae_path,pipeline_class=pipeline_class,)if args.half:pipe.to(dtype=torch.float16)if args.controlnet:# only save the controlnet modelpipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)else:pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)

5. 资源链接

https://www.liblib.art/modelinfo/8345679083144158adb64b80c58e3afd

相关文章:

【AI 绘画】模型转换与快速生图(基于diffusers)

AI 绘画- 模型转换与快速生图(基于diffusers) 1. 本章介绍 本次主要展示一下不同框架内文生图模型转换,以及快速生成图片的方法。 SDXL文生图 2. sdxl_lightning基本原理 模型基本原理介绍如下 利用蒸馏方法获取小参数模型。首先&#x…...

甄选范文“论软件设计方法及其应”软考高级论文系统架构设计师论文

论文真题 软件设计(Software Design,SD)根据软件需求规格说明书设计软件系统的整体结构、划分功能模块、确定每个模块的实现算法以及程序流程等,形成软件的具体设计方案。软件设计把许多事物和问题按不同的层次和角度进行抽象,将问题或事物进行模块化分解,以便更容易解决…...

leetcode线段树(2940. 找到 Alice 和 Bob 可以相遇的建筑)

前言 经过前期的基础训练以及部分实战练习&#xff0c;粗略掌握了各种题型的解题思路。现阶段开始专项练习。 描述 给你一个下标从 0 开始的正整数数组 heights &#xff0c;其中 heights[i] 表示第 i 栋建筑的高度。 如果一个人在建筑 i &#xff0c;且存在 i < j 的建筑…...

用于不平衡医疗数据分类的主动SMOTE

一、主动学习如何应用于不平衡数据的处理 首先&#xff0c;主动SMOTE不是像经典的SMOTE那样从训练集中随机选择一个样本作为生成合成样本的轴心点&#xff0c;而是通过不确定性和多样性采样来智能地进行样本选择&#xff0c;这是主动学习的两种技术。 在数据不平衡的情况下&…...

linux文件更新日期与系统日期比较

项目说明&#xff1a; 要获取linux系统中某目录下最新文件的修改时间并与当前系统时间进行比较&#xff0c;可以使用以下步骤&#xff1a; 使用 ls 命令获取最新文件的修改时间。 使用 date 命令获取当前时间。 计算时间差并打印结果。 实例脚本如下&#xff1a; #!/bin/…...

leetCode - - - 哈希表

目录 1.模拟行走机器人&#xff08;LeetCode 874&#xff09; 2.数组的度&#xff08;LeetCode 697&#xff09; 3.子域名访问次数&#xff08;LeetCode 811&#xff09; 4.字母异位词分组&#xff08;LeetCode 49&#xff09; 5.小结 1.常见的哈希表实现 2.遍历Map 1.模…...

NGINX自动清理180天之前的日志

需求描述 日志每天会以天为单位产生一个日志&#xff0c;不清理的话会越来越多。这里写一个Lua自定定时清理日志目录下的日志文件。 依赖安装 安装 lfs 模块 yum install luarocks yum install lua-develluarocks install luafilesystem 创建模拟旧文件 创建了一个1月的旧…...

jackson 轻松搞定接口数据脱敏

一、简介 实际的业务开发过程中&#xff0c;我们经常需要对用户的隐私数据进行脱敏处理&#xff0c;所谓脱敏处理其实就是将数据进行混淆隐藏&#xff0c;例如下图&#xff0c;将用户的手机号、地址等数据信息&#xff0c;采用*进行隐藏&#xff0c;以免泄露个人隐私信息。 如…...

Nginx 正则表达式与rewrite

目录 一、正则表达式 二、rewrite 2.1 rewrite简述 2.2 rewrite 跳转 2.3 rewrite 执行顺序 2.4 rewrite 语法格式 三、location 3.1 location 类别 3.2 location常用匹配规则 3.3 location优先级 3.4 示例说明 3.5 匹配规则总结 3.6 三个匹配规则定义 四、实战…...

tekton什么情况下在Dockerfile中需要用copy

kaniko配置如下 如果docker中的workDir跟tekton中的workDir不一致需要copy。也可以通过mv&#xff0c;cp达到类似效果...

第九届世界渲染大赛在哪里提交作品呢?

自第九届世界渲染大赛开放投稿以来&#xff0c;已经过去了10天。在这段时间里&#xff0c;众多CG爱好者已经完成了他们的动画创作。然而&#xff0c;许多参赛者对于如何提交他们的作品仍然感到困惑。接下来&#xff0c;让我们一起了解具体的投稿流程和入口&#xff0c;确保每位…...

fastjson(autoType)反序列化漏洞

1. 温少和他的fastjson 阿里巴巴的 FastJSON&#xff0c;也被称为 Alibaba FastJSON 或阿里巴巴 JSON&#xff0c;是一个高性能的 Java JSON 处理库&#xff0c;用于在 Java 应用程序中解析和生成 JSON 数据。FastJSON 以其卓越的性能和功能丰富的特点而闻名&#xff0c;并在…...

Java入门基础16:集合框架1(Collection集合体系、List、Set)

集合体系结构 Collection是单列集合的祖宗&#xff0c;它规定的方法&#xff08;功能&#xff09;是全部单列集合都会继承的。 collection集合体系 Collection的常用方法 package com.itchinajie.d1_collection;import java.util.ArrayList; import java.util.HashSet;/* * 目…...

Qt如何调用接口

在Qt中&#xff0c;你可以使用QNetworkAccessManager类来调用API。以下是一个简单的示例&#xff1a; cpp #include <QCoreApplication> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> int main(int arg…...

Android14之解决编译libaaudio.so报错问题(二百二十七)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 新书发布&#xff1a;《Android系统多媒体进阶实战》&#x1f680; 优质专栏&#xff1a; Audio工程师进阶系列…...

【专题】2024年7月人工智能AI行业报告合集汇总PDF分享(附原数据表)

原文链接:https://tecdat.cn/?p37350 随着人工智能技术的飞速发展&#xff0c;AI已经成为当今时代的重要驱动力。本报告将聚焦于人工智能AI行业的最新动态&#xff0c;涵盖客户服务、体验营销、资产管理以及国产AI大模型应用等多个领域。通过深入研究和分析&#xff0c;我们…...

干货分享|如何使用Stable Diffusion打造会说话的数字人?

数字人已不是什么新鲜名词了。在许多领域&#xff0c;尤其是媒体和娱乐领域&#xff0c;经常可以看到卡通形象的人物或逼真的虚拟主持人。在Stable Diffusion中&#xff0c;我们可以上传一段录制好的音频文件&#xff0c;然后使用SadTalker插件&#xff0c;将音频和图片相结合&…...

OrangePi AIpro学习4 —— 昇腾AI模型推理 C++版

目录 一、ATC模型转换 1.1 模型 1.2 ATC工具 1.3 实操模型转换 1.4 使用ATC工具时的一些关键注意事项 1.5 ATC模型转换命令举例 二、运行昇腾AI模型应用样仓程序 2.1 程序目录 2.2 下载模型和模型转换 2.3 下载图片和编译程序 2.4 解决报错 2.5 运行程序 三、运行…...

vue js 多组件异步请求解决方案

接口之间异步问题可以采用Promiseasyncawait 链接&#xff1a; https://blog.csdn.net/qq_39816586/article/details/103517416 使用场景&#xff1a; 1.保障用户必须完成自动登录&#xff0c;才调用后续逻辑 2.保障必须完成初始启动&#xff0c;才调用后续逻辑 3.保障先执行on…...

【Android】不同系统版本获取设备MAC地址

【Android】不同系统版本获取设备MAC地址 尝试实现 尝试 在开发过程中&#xff0c;想要获取MAC地址&#xff0c;最开始想到的就是WifiManager&#xff0c;但结果始终返回02:00:00:00:00:00&#xff0c;由于用得是wifi &#xff0c;考虑是不是因为用得网线的原因&#xff0c;但…...

20个网站备份泄漏漏洞挖掘技巧!

20个网站备份泄漏漏洞挖掘技巧&#xff01; 网站备份文件泄露&#xff0c;绝不是小问题。在网络安全攻防实战中&#xff0c;备份文件泄露一直被列为“高风险漏洞”&#xff0c;却往往被企业开发者所忽视。一次偶然的备份文件泄露&#xff0c;可能成为整个系统沦陷的起点。本文…...

Halcon仿射变换实战:手把手教你用vector_to_aniso和solve_matrix搞定图像配准(附完整代码)

Halcon仿射变换实战&#xff1a;从原理到工程落地的图像配准指南 在工业视觉检测领域&#xff0c;图像配准的精度直接影响着后续缺陷检测的准确性。去年参与的一个半导体封装项目让我深刻体会到这一点——当芯片位置存在0.5像素以上的偏移时&#xff0c;细微的焊球缺陷就会被漏…...

Windows上搭建PostgreSQL监控神器:Grafana+Prometheus+Postgres_Exporter保姆级干货教程

❓想要实时掌握 PostgreSQL 数据库的运行状态&#xff1f; &#x1f440;想知道复制延迟、锁等待这些核心指标&#xff1f; &#x1f192;这里是Moshow的「CSDN https://zhengkai.blog.csdn.net/」 &#x1f680;这篇文章带你从零开始&#xff0c;在 Windows 上搭建一套企业…...

基于微信小程序实现马拉松报名系统【附项目源码+论文说明】

基于java和微信小程序实现马拉松报名系统演示【内附项目源码LW说明】摘要 随着信息技术在管理上越来越深入而广泛的应用&#xff0c;管理信息系统的实施在技术上已逐步成熟。本文介绍了马拉松报名系统微信小程序的开发全过程。通过分析马拉松报名系统微信小程序管理的不足&…...

GNN实战:Cora、Citeseer、PubMed三大文献数据集保姆级使用指南(附代码)

GNN实战&#xff1a;Cora、Citeseer、PubMed三大文献数据集深度解析与工程实践 引言&#xff1a;为什么这三个数据集成为GNN研究的"黄金标准"&#xff1f; 在探索图神经网络&#xff08;GNN&#xff09;的浩瀚宇宙中&#xff0c;Cora、Citeseer和PubMed如同三颗璀璨的…...

swoole方案 实时监控大盘推送中心

业务服务 --写--> Kafka ---> Swoole消费 --WebSocket推--> 浏览器ECharts实时刷新Kafka 当缓冲层&#xff0c;业务打点不管推送快不快&#xff0c;Swoole 从 Kafka 拉数据&#xff0c;有新数据就推给所有看板页面。---代码<?php// composer require longlang/php…...

高效实现Windows任务栏个性化的5个极简方案:轻量级透明化工具TranslucentTB全指南

高效实现Windows任务栏个性化的5个极简方案&#xff1a;轻量级透明化工具TranslucentTB全指南 【免费下载链接】TranslucentTB A lightweight utility that makes the Windows taskbar translucent/transparent. 项目地址: https://gitcode.com/gh_mirrors/tr/TranslucentTB …...

道心网络安全学习笔记系列之好靶场的信息收集2

上节课找了一个图片的网址&#xff0c;继续挑战其它靶场&#xff0c;我们看下一题收集十个百度域名&#xff0c;这还不是顺手就来&#xff0c;但是贴吧不行&#xff0c;那还不简单&#xff0c;去访问百度网站&#xff0c;顺便输入一个搜索词&#xff0c;都不用看&#xff0c;前…...

3D打印机步进电机参数计算全攻略:从同步带到丝杆的实战配置

3D打印机步进电机参数计算全攻略&#xff1a;从同步带到丝杆的实战配置 在DIY 3D打印机的过程中&#xff0c;步进电机的参数计算往往是让初学者最头疼的环节之一。无论是同步带驱动的XY轴&#xff0c;还是丝杆控制的Z轴&#xff0c;亦或是齿轮传动的挤出机构&#xff0c;都需要…...

非隔离双向 DC/DC 变换器 buck - boost 变换器仿真探索

非隔离双向DC/DC变换器 buck-boost变换器仿真 输入侧为直流电压源&#xff0c;输出侧接蓄电池 模型采用电压外环电流内环的双闭环控制方式 可实现恒流充放电&#xff0c;且具备充放电保护装置防止过充和过放。 蓄电池充放电模式可切换 Matlab/Simulink模型在电力电子领域&#…...