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

扩散模型Diffusers Pipeline API使用介绍

1 关于Diffusers Pipeline

1.1 简介

大部分扩散模型包含多个独立训练的子模型和组件模块组合而成,例如StableDiffusion 有:

  • 3个独立训练的子模型:Autoencoder、 Conditional Unet、CLIP text encoder
  • 调度器组件scheduler,
  • CLIPImageProcessor,
  • safety checker.

为了让开发者以最简单的方式使用最新最先进的扩散模型,diffusers开发了pipeline管理和使用这些类,使得开发者可以以端对端方式使用扩散模型。

注意:pipeline本身没有提供任何训练相关功能,如果想要实现训练,可以参考官方的训练样例

1.2 官方Pipeline

以下表格是diffusers官方实现的Pipeline,每个Pipeline有对应的论文。

PipelineSourceTasks
dance diffusionDance DiffusionUnconditional Audio Generation
ddpmDenoising Diffusion Probabilistic ModelsUnconditional Image Generation
ddimDenoising Diffusion Implicit ModelsUnconditional Image Generation
latent_diffusionHigh-Resolution Image Synthesis with Latent Diffusion ModelsText-to-Image Generation
latent_diffusion_uncondHigh-Resolution Image Synthesis with Latent Diffusion ModelsUnconditional Image Generation
pndmPseudo Numerical Methods for Diffusion Models on ManifoldsUnconditional Image Generation
score_sde_veScore-Based Generative Modeling through Stochastic Differential EquationsUnconditional Image Generation
score_sde_vpScore-Based Generative Modeling through Stochastic Differential EquationsUnconditional Image Generation
stable_diffusionStable DiffusionText-to-Image Generation
stable_diffusionStable DiffusionImage-to-Image Text-Guided Generation
stable_diffusionStable DiffusionText-Guided Image Inpainting
stochastic_karras_veElucidating the Design Space of Diffusion-Based Generative ModelsUnconditional Image Generation

2 Pipeline API接口

扩散模型包含多个独立的模型和组件,不同任务中模型独立训练,并且可以用其他模型替换。不同的Pipeline可能包含专有的函数接口,但所有Pipeline都有的共同函数如下:

  • from_pretrained(cls, pretrained_model_name_or_path, **kwargs): 参数pretrained_model_name_or_path可以是 Hugging Face Hub repository的 id, 例如: runwayml/stable-diffusion-v1-5 或本地路径:"./stable-diffusion". 为了确保所有模型和组件能被正确加载,需要提供一个 model_index.json 文件, 例如: runwayml/stable-diffusion-v1-5/model_index.json, 这个文件定义了所有要被加载的组件。其格式如下: <name>: ["<library>", "<class name>"],其中<name> 是类<class name>实例的名称。此类可以在库"<library>"中加载到。
  • save_pretrained(self, save_directory) : 参数save_directory为本地目录路径,例如: ./stable-diffusion ,所有的模型和组件会被保存。每个模型和组件创建一个对应的子目录,子目录名称为模型或组件的属性名称如./stable_diffusion/unet. 此外,还会再根目录创建 model_index.json 文件如:./stable_diffusion/model_index.json
  • to(self, torch_device: Optional[Union[str, torch.device]] = None) 参数torch_device为 stringtorch.device 类型,将所有torch.nn.Module 类型的对象转移到指定的device上,此函数与pytorch的to函数功能一致。
  • __call__函数执行推理,此函数定义了pipeline的推理逻辑,不同的Pipeline对应的推理输入差别很大,例如文生图Pipeline StableDiffusionPipeline 的输入应该是文本prompt,输出是生成的图。 而DDPMPipeline 则无需提供任何输入。因此读者需要根据实际的Pipeline功能以及查看相应的官方文档使用。

注意: 所有的Pipeline的__call__函数会自动调用torch.no_grad函数禁用梯度,因为Pipeline不是用于训练。如果你在前向推理后有保存梯度的需求,可以自定义Pipeline,参考官方示例

3 使用示例

1 扩散模型:文生图

# make sure you're logged in with `huggingface-cli login`
from diffusers import StableDiffusionPipeline, LMSDiscreteSchedulerpipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
pipe = pipe.to("cuda")prompt = "a photo of an astronaut riding a horse on mars"
image = pipe(prompt).images[0]  image.save("astronaut_rides_horse.png")

2 扩散模型:图生图

StableDiffusionImg2ImgPipeline 接受一个文本prompt和初始图片作为条件,指导生成新图。

import requests
from PIL import Image
from io import BytesIOfrom diffusers import StableDiffusionImg2ImgPipeline# load the pipeline
device = "cuda"
pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",torch_dtype=torch.float16,
).to(device)# let's download an initial image
url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"response = requests.get(url)
init_image = Image.open(BytesIO(response.content)).convert("RGB")
init_image = init_image.resize((768, 512))prompt = "A fantasy landscape, trending on artstation"images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).imagesimages[0].save("fantasy_landscape.png")

可以在colab中直接运行colab

3 扩充模型:In-painting

StableDiffusionInpaintPipeline 接受文本prompt和mask,用于编辑图像指定区域。

import PIL
import requests
import torch
from io import BytesIOfrom diffusers import StableDiffusionInpaintPipelinedef download_image(url):response = requests.get(url)return PIL.Image.open(BytesIO(response.content)).convert("RGB")img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"init_image = download_image(img_url).resize((512, 512))
mask_image = download_image(mask_url).resize((512, 512))pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting",torch_dtype=torch.float16,
)
pipe = pipe.to("cuda")prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]

可以在colab中直接运行 colab

相关文章:

扩散模型Diffusers Pipeline API使用介绍

1 关于Diffusers Pipeline 1.1 简介 大部分扩散模型包含多个独立训练的子模型和组件模块组合而成&#xff0c;例如StableDiffusion 有&#xff1a; 3个独立训练的子模型&#xff1a;Autoencoder、 Conditional Unet、CLIP text encoder调度器组件scheduler,CLIPImageProcesso…...

el-date-picker 组件 监听输入的内容 并按照时间格式 格式化

这个时间选择组件在输入的时候是监听不到输入的值的&#xff0c;所以我们在外层再套个div&#xff0c;然后用获取焦点事件去操作dom 页面中 <div id"inParkingData"><el-date-pickerv-model"indateRange"size"small"value-format"…...

组件通信$refs | $parent |$root

父组件传值子组件用Props 子组件传值父组件用$emit 父组件直接还可以直接取子组件的值用$refs 父组件直接从子子组件中获取值$refs 不建议使用会增加组件之间的耦合度&#xff0c;一般用于第三方插件的封装 ref如果绑定在dom节点上&#xff0c;拿到的就是原生dom节点。 ref如…...

springboot中@Async的使用

1.AsyncAnnotationBeanPostProcessor是主要逻辑类 (1)AsyncAnnotationBeanPostProcessor实现BeanFactoryAware接口 在setBeanFactory(BeanFactory beanFactory)中初始化advisorAsyncAnnotationAdvisor() (2)AsyncAnnotationBeanPostProcessor实现BeanPostProcessor接口 在p…...

学C++从CMake学起

Cmake在此引入c17编译器&#xff0c;就可以使用c17的新特性了。 c17定义了一些算法&#xff0c;都定义在了下面这个头文件里。 #include <numeric> 通过redurce函数求和 将9行的std::plus{}换成std::times{}就是相乘。...

lv8 嵌入式开发-网络编程开发 20 域名解析与http服务实现原理

目录 1 域名解析 2 如何实现万维网服务器&#xff1f; 2.1 HTTP 的操作过程 2.2 万维网服务器实现 1 域名解析 域名解析gethostbyname函数 主机结构在 <netdb.h> 中定义如下&#xff1a; struct hostent {char *h_name; /* 官方域名 */char **h_alias…...

只要路由器有WPS按钮,佳能打印机连接到Wi-Fi网络的方法就很简单

佳能打印机是很好的设备&#xff0c;可以让你从智能手机、电脑或平板电脑打印照片。它们还提供其他功能&#xff0c;如扫描文档和复制图像。 最新的型号还允许你连接到Wi-Fi&#xff0c;因此你不需要使用电线将设备连接到打印机。 Wi-Fi是通过本地网络传输数据的标准方式。它…...

Cmake输出git内容方式

实现背景 在定位问题时&#xff0c;固件无法获取当前设备中版本的详细信息&#xff0c;无法准确获取版本具体内容 输出效果 实现方式 以下是基于Cmake的语法实现 在CMake中获取git信息&#xff0c;可以通过execute_process命令运行git命令并将结果保存在一个变量中。然后可…...

实现多余内容变成省略号

实现效果 代码 <p class"item-content">{{ item.content }}</p>样式 .item-content {white-space: nowrap;/* 禁止换行 */overflow: hidden;/* 隐藏溢出部分 */text-overflow: ellipsis;/* 使用省略号表示溢出部分 */ }...

WAL 模式(PostgreSQL 14 Internals翻译版)

性能 当服务器正常运行时&#xff0c;WAL文件不断被写入磁盘。但是&#xff0c;这些写操作是顺序的:几乎没有随机访问&#xff0c;因此即使是HDD也可以处理这个任务。由于这种类型的加载与典型的数据文件访问非常不同&#xff0c;因此有必要为WAL文件设置一个单独的物理存储&a…...

2023年信息科学与工程学院学生科协第二次软件培训

2023年信息科学与工程学院学生科协第二次软件培训 文章目录 2023年信息科学与工程学院学生科协第二次软件培训一维数组数组的概念定义格式一维数组的访问例题&#xff1a;练习题&#xff1a; 数组元素数量一维数组的初始化 二维数组定义格式二维数组的访问二维数组的存储结构二…...

渗透测试tomcat错误信息泄露解决办法

解决方法&#xff1a; 1、使用tomcat8.5.16&#xff0c;会重定向非法url到登录url 2、配置server.xml&#xff0c;加上 <Valve className"org.apache.catalina.valves.ErrorReportValve" showReport"false" showServerInfo"false" />配置…...

notes_NLP

RNN > LSTM, GRU model特点RNNLSTMinputforgetputput&#xff1b;GRUresetupdate&#xff1b;参数比LSTM少&#xff0c;计算效率更高&#xff1b; 循环神经网络&#xff08;RNN/LSTM/GRU&#xff09; 人人都能看懂的GRU transformer > self-attention 根据Query和Key计…...

内存分段、分页

大家好&#xff0c;我叫徐锦桐&#xff0c;个人博客地址为www.xujintong.com。平时记录一下学习计算机过程中获取的知识&#xff0c;还有日常折腾的经验&#xff0c;欢迎大家访问。 前言 每个进程都有一套自己的虚拟地址&#xff0c;尽管进程可能有相同的虚拟地址&#xff0c;…...

Python-pptx教程之一从零开始生成PPT文件

简介 python-pptx是一个用于创建、读取和更新PowerPoint&#xff08;.pptx&#xff09;文件的python库。 典型的用途是根据动态内容&#xff08;如数据库查询、分析数据等&#xff09;&#xff0c;将这些内容自动化生成PowerPoint演示文稿&#xff0c;将数据可视化&#xff0c…...

k8s 使用ingress-nginx访问集群内部应用

k8s搭建和部署应用完成后&#xff0c;可以通过NodePort&#xff0c;Loadbalancer&#xff0c;Ingress方式将应用端口暴露到集群外部&#xff0c;提供外部访问。 缺点&#xff1a; NodePort占用端口&#xff0c;大量暴露端口非常不安全&#xff0c;并且有端口数量限制【不推荐】…...

企业数据泄露怎么办?

随着数字化时代的到来&#xff0c;威胁企业数据安全的因素越来越多。一旦机密数据泄露&#xff0c;不仅会对企业造成巨大的经济损失&#xff0c;还会对企业的声誉和客户信任度造成严重影响。发生数据泄露情况时&#xff0c;企业该怎样应对&#xff1f; 1.确认数据泄露 确认是…...

GoLong的学习之路(一)语法之变量与常量

目录 GoLang变量批量声明变量的初始化类型推导短变量声明匿名变量 常量iota&#xff08;特殊&#xff09;&#xff08;需要重点记忆&#xff09; GoLang go的诞生为了解决在21世纪多核和网络化环境越来越复杂的变成问题而发明的Go语言。 go语言是从Ken Thomepson发明的B语言和…...

Go-Python-Java-C-LeetCode高分解法-第十一周合集

前言 本题解Go语言部分基于 LeetCode-Go 其他部分基于本人实践学习 个人题解GitHub连接&#xff1a;LeetCode-Go-Python-Java-C 欢迎订阅CSDN专栏&#xff0c;每日一题&#xff0c;和博主一起进步 LeetCode专栏 我搜集到了50道精选题&#xff0c;适合速成概览大部分常用算法 突…...

封装axios的两种方式

作为前端工程师&#xff0c;经常需要对axios进行封装以满足复用的目的。在不同的前端项目中使用相同的axios封装有利于保持一致性&#xff0c;有利于数据之间的传递和处理。本文提供两种对axios进行封装的思路。 1. 将请求方式作为调用参数传递进来 首先导入了axios, AxiosIn…...

在rocky linux 9.5上在线安装 docker

前面是指南&#xff0c;后面是日志 sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io -y docker version sudo systemctl start docker sudo systemctl status docker …...

基于Uniapp开发HarmonyOS 5.0旅游应用技术实践

一、技术选型背景 1.跨平台优势 Uniapp采用Vue.js框架&#xff0c;支持"一次开发&#xff0c;多端部署"&#xff0c;可同步生成HarmonyOS、iOS、Android等多平台应用。 2.鸿蒙特性融合 HarmonyOS 5.0的分布式能力与原子化服务&#xff0c;为旅游应用带来&#xf…...

dedecms 织梦自定义表单留言增加ajax验证码功能

增加ajax功能模块&#xff0c;用户不点击提交按钮&#xff0c;只要输入框失去焦点&#xff0c;就会提前提示验证码是否正确。 一&#xff0c;模板上增加验证码 <input name"vdcode"id"vdcode" placeholder"请输入验证码" type"text&quo…...

Java + Spring Boot + Mybatis 实现批量插入

在 Java 中使用 Spring Boot 和 MyBatis 实现批量插入可以通过以下步骤完成。这里提供两种常用方法&#xff1a;使用 MyBatis 的 <foreach> 标签和批处理模式&#xff08;ExecutorType.BATCH&#xff09;。 方法一&#xff1a;使用 XML 的 <foreach> 标签&#xff…...

Java求职者面试指南:Spring、Spring Boot、Spring MVC与MyBatis技术解析

Java求职者面试指南&#xff1a;Spring、Spring Boot、Spring MVC与MyBatis技术解析 一、第一轮基础概念问题 1. Spring框架的核心容器是什么&#xff1f;它的作用是什么&#xff1f; Spring框架的核心容器是IoC&#xff08;控制反转&#xff09;容器。它的主要作用是管理对…...

Elastic 获得 AWS 教育 ISV 合作伙伴资质,进一步增强教育解决方案产品组合

作者&#xff1a;来自 Elastic Udayasimha Theepireddy (Uday), Brian Bergholm, Marianna Jonsdottir 通过搜索 AI 和云创新推动教育领域的数字化转型。 我们非常高兴地宣布&#xff0c;Elastic 已获得 AWS 教育 ISV 合作伙伴资质。这一重要认证表明&#xff0c;Elastic 作为 …...

【Veristand】Veristand环境安装教程-Linux RT / Windows

首先声明&#xff0c;此教程是针对Simulink编译模型并导入Veristand中编写的&#xff0c;同时需要注意的是老用户编译可能用的是Veristand Model Framework&#xff0c;那个是历史版本&#xff0c;且NI不会再维护&#xff0c;新版本编译支持为VeriStand Model Generation Suppo…...

第八部分:阶段项目 6:构建 React 前端应用

现在&#xff0c;是时候将你学到的 React 基础知识付诸实践&#xff0c;构建一个简单的前端应用来模拟与后端 API 的交互了。在这个阶段&#xff0c;你可以先使用模拟数据&#xff0c;或者如果你的后端 API&#xff08;阶段项目 5&#xff09;已经搭建好&#xff0c;可以直接连…...

2025 后端自学UNIAPP【项目实战:旅游项目】7、景点详情页面【完结】

1、获取景点详情的请求【my_api.js】 // 引入公共的请求封装 import http from ./my_http.js// 登录接口&#xff08;适配服务端返回 Token&#xff09; export const login async (code, avatar) > {const res await http(/login/getWXSessionKey, {code,avatar}); };//…...

CentOS 7.9安装Nginx1.24.0时报 checking for LuaJIT 2.x ... not found

Nginx1.24编译时&#xff0c;报LuaJIT2.x错误&#xff0c; configuring additional modules adding module in /www/server/nginx/src/ngx_devel_kit ngx_devel_kit was configured adding module in /www/server/nginx/src/lua_nginx_module checking for LuaJIT 2.x ... not…...