码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 扩散模型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, 这个文件定义了所有要被加载的组件。其格式如下: : ["", ""],其中 是类实例的名称。此类可以在库""中加载到。
    • 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为 string 或 torch.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, LMSDiscreteScheduler
    
    pipe = 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")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2 扩散模型:图生图

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

    import requests
    from PIL import Image
    from io import BytesIO
    
    from 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).images
    
    images[0].save("fantasy_landscape.png")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    可以在colab中直接运行colab

    3 扩充模型:In-painting

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

    import PIL
    import requests
    import torch
    from io import BytesIO
    
    from diffusers import StableDiffusionInpaintPipeline
    
    def 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]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    可以在colab中直接运行 colab

  • 相关阅读:
    智能配电系统解决方案
    游戏安全03:缓冲区溢出攻击简单解释
    全网最全谷粒商城记录_09、环境-配置docker阿里云镜像加速
    服务器硬件基础知识
    python多进程编程
    误删记录/表/库怎么办?该如何防范误删?
    STL算法
    pyppeteer框架基本语法备忘录
    牛客网反转链表
    React81_React.memo
  • 原文地址:https://blog.csdn.net/huachao1001/article/details/133988875
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号