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

广东有实力的汽车救援公司

引言在广东&#xff0c;汽车保有量庞大&#xff0c;汽车救援服务的需求也日益增长。当车辆出现故障或遭遇意外情况时&#xff0c;及时有效的救援至关重要。一、行业现状与需求 广东地区的交通网络发达&#xff0c;汽车使用频繁。据行业报告显示&#xff0c;每天都有大量的车辆需…...

基于北方苍鹰优化算法优化BP神经网络(NGO - BP)的多变量时间序列预测Matlab实现

基于北方苍鹰优化算法优化BP神经网络(NGO-BP)的多变量时间序列预测NGO-BP多变量时间序列 matlab代码注&#xff1a;要求Matlab2018B及以上版本在数据驱动的时代&#xff0c;多变量时间序列预测是众多领域如金融、气象、工业生产等的关键任务。BP神经网络是常用的预测模型&#…...

能用脚本就别用Agent。

今天早上发了那篇文章以后&#xff0c;有很多朋友跟我讨论。发现大家问得最多的一个问题是&#xff0c;你天天说Agent和Skills是未来&#xff0c;那你自己平时干活是不是什么都丢给Agent&#xff1f;我说实话&#xff0c;还真不是。正好借这个机会我再补充一下&#xff0c;因为…...

场景新叙事|小红书发布男装春上新场景趋势

春日渐暖&#xff0c;衣橱焕新。在小红书&#xff0c;男装消费决策的锚点从过去单一的审美偏好&#xff0c;逐渐向涵盖工作、休闲、运动及社交等维度的多元生活全景偏移。男性用户在选购穿搭服饰时&#xff0c;不仅是在挑选一件好看的衣服&#xff0c;更是在寻找一套能完美嵌入…...

2026年热门降AI率工具推荐!一键消除AI痕迹+稳过检测

2026年热门降AI率工具推荐&#xff01;一键消除AI痕迹稳过检测 又到论文集中提交、自媒体内容批量产出的时间段&#xff0c;不少同学和创作者都在为一件事头疼&#xff1a;AI生成痕迹太重&#xff0c;内容被平台判定为低质量&#xff0c;要么论文打回修改&#xff0c;要么自媒体…...

如何构建流畅的Android音频播放体验:UAMP与ExoPlayer集成实战指南

如何构建流畅的Android音频播放体验&#xff1a;UAMP与ExoPlayer集成实战指南 【免费下载链接】uamp A sample audio app for Android 项目地址: https://gitcode.com/gh_mirrors/ua/uamp UAMP&#xff08;Android Universal Music Player&#xff09;是一个功能全面的音…...

如何实现daedalOS浏览器桌面环境中的精准文件类型检测

如何实现daedalOS浏览器桌面环境中的精准文件类型检测 【免费下载链接】daedalOS Desktop environment in the browser 项目地址: https://gitcode.com/gh_mirrors/da/daedalOS daedalOS作为一款创新的浏览器桌面环境&#xff0c;其核心功能之一就是能够准确识别各种文件…...

终极指南:Fay数字人框架API限流策略——保护系统稳定与防止滥用的完整方案

终极指南&#xff1a;Fay数字人框架API限流策略——保护系统稳定与防止滥用的完整方案 【免费下载链接】Fay Fay is an open-source digital human framework integrating language models and digital characters. It offers retail, assistant, and agent versions for diver…...

使用VScode开发Java项目,在一个maven工程中,出现src源代码的java文件无法进行自动编译、自动纠错功能的解决方法

也就是VScode编译器代码不进行自动纠察&#xff0c;胡乱写一通代码&#xff0c;代码下面不出现波浪线&#xff1f;&#xff01;出现原因&#xff1a;其实就是在maven工程中jdk未识别到&#xff01;无法编译java工程&#xff01;解决方法&#xff1a;完善pom.xml即可&#xff0c…...

卫星载荷论文阅读笔记

1.《China Seismo-Electromagnetic Satellite search coil magnetometer data and initial results》&#xff08;中国地震机理电磁监测卫星搜索磁强计数据及初步结果&#xff09; 这篇文章主要介绍了“张衡一号”&#xff08;CSES&#xff09;卫星上搭载的**搜索磁强计&#x…...