当前位置: 首页 > 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;但…...

[特殊字符] 智能合约中的数据是如何在区块链中保持一致的?

&#x1f9e0; 智能合约中的数据是如何在区块链中保持一致的&#xff1f; 为什么所有区块链节点都能得出相同结果&#xff1f;合约调用这么复杂&#xff0c;状态真能保持一致吗&#xff1f;本篇带你从底层视角理解“状态一致性”的真相。 一、智能合约的数据存储在哪里&#xf…...

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…...

【Python】 -- 趣味代码 - 小恐龙游戏

文章目录 文章目录 00 小恐龙游戏程序设计框架代码结构和功能游戏流程总结01 小恐龙游戏程序设计02 百度网盘地址00 小恐龙游戏程序设计框架 这段代码是一个基于 Pygame 的简易跑酷游戏的完整实现,玩家控制一个角色(龙)躲避障碍物(仙人掌和乌鸦)。以下是代码的详细介绍:…...

安宝特方案丨XRSOP人员作业标准化管理平台:AR智慧点检验收套件

在选煤厂、化工厂、钢铁厂等过程生产型企业&#xff0c;其生产设备的运行效率和非计划停机对工业制造效益有较大影响。 随着企业自动化和智能化建设的推进&#xff0c;需提前预防假检、错检、漏检&#xff0c;推动智慧生产运维系统数据的流动和现场赋能应用。同时&#xff0c;…...

基于uniapp+WebSocket实现聊天对话、消息监听、消息推送、聊天室等功能,多端兼容

基于 ​UniApp + WebSocket​实现多端兼容的实时通讯系统,涵盖WebSocket连接建立、消息收发机制、多端兼容性配置、消息实时监听等功能,适配​微信小程序、H5、Android、iOS等终端 目录 技术选型分析WebSocket协议优势UniApp跨平台特性WebSocket 基础实现连接管理消息收发连接…...

Cilium动手实验室: 精通之旅---20.Isovalent Enterprise for Cilium: Zero Trust Visibility

Cilium动手实验室: 精通之旅---20.Isovalent Enterprise for Cilium: Zero Trust Visibility 1. 实验室环境1.1 实验室环境1.2 小测试 2. The Endor System2.1 部署应用2.2 检查现有策略 3. Cilium 策略实体3.1 创建 allow-all 网络策略3.2 在 Hubble CLI 中验证网络策略源3.3 …...

Module Federation 和 Native Federation 的比较

前言 Module Federation 是 Webpack 5 引入的微前端架构方案&#xff0c;允许不同独立构建的应用在运行时动态共享模块。 Native Federation 是 Angular 官方基于 Module Federation 理念实现的专为 Angular 优化的微前端方案。 概念解析 Module Federation (模块联邦) Modul…...

BCS 2025|百度副总裁陈洋:智能体在安全领域的应用实践

6月5日&#xff0c;2025全球数字经济大会数字安全主论坛暨北京网络安全大会在国家会议中心隆重开幕。百度副总裁陈洋受邀出席&#xff0c;并作《智能体在安全领域的应用实践》主题演讲&#xff0c;分享了在智能体在安全领域的突破性实践。他指出&#xff0c;百度通过将安全能力…...

实现弹窗随键盘上移居中

实现弹窗随键盘上移的核心思路 在Android中&#xff0c;可以通过监听键盘的显示和隐藏事件&#xff0c;动态调整弹窗的位置。关键点在于获取键盘高度&#xff0c;并计算剩余屏幕空间以重新定位弹窗。 // 在Activity或Fragment中设置键盘监听 val rootView findViewById<V…...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...