首页 > 其他分享 >stable diffusion文生图代码解读

stable diffusion文生图代码解读

时间:2024-07-25 22:27:45浏览次数:10  
标签:diffusion noise prompt 文生 pred self embeds latents stable

使用diffusers运行stable diffusion,文生图过程代码解读。
只按照下面这种最简单的运行代码,省略了一些参数的处理步骤。

from diffusers import DiffusionPipeline
pipeline = DiffusionPipeline.from_pretrained(MODEL_PATH , torch_dtype=torch.float16)
pipeline.to("cuda")
img = pipeline("An image of a squirrel in Picasso style",num_inference_steps=10).images[0]
img.save("result.jpg")

0. 定义height 和 width

如果没有输入参数,默认为unet的采样大小乘以VAE缩放率,64*8=512。

1.检查输入的参数

一些常规检查。

2. 定义参数 batch_size

根据prompt或者prompt_embeds计算batch_size,按照上面的执行代码,默认为1。如果一次输入多个prompt,那么就是prompt的数量

        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]
 
#多个prompt
#每个prompt生成的图片数量使用num_images_per_prompt控制
prompt = ["An image of a squirrel in Picasso style","Astronaut in a jungle, cold color palette"]
images = pipeline(prompt,num_images_per_prompt=1,num_inference_steps=10).images

3.对输入的prompt编码

默认使用CLIPTokenizer对输入prompt tokenize,输出为(1,77),CLIP模型默认设置最大文本长度为75,然后还有两个表示开始和结束的特殊字符’<|startoftext|>’ ‘<|endoftext|>’,最大长度就是77。
使用openai/clip-vit-large-patch14,对输入进行encoder。CLIP模型的默认embedding dim 为768,那么编码输出的prompt embedding的维度就是(1,77,768)。
如果参数没有输入negative_prompt,那么negative_prompt默认为 ‘‘’’,仍然可以tokenizer,encoder。
negative prompt embedding的维度也是(1,77,768)。
默认都是有do_classifier_free_guidance(CFG参数),为了避免计算两次,这里把negative prompt 和prompt合并在一起输入。

        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt,
            device,
            num_images_per_prompt,
            self.do_classifier_free_guidance,
            negative_prompt,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            lora_scale=lora_scale,
            clip_skip=self.clip_skip,
        )
        if self.do_classifier_free_guidance:
            prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) #(2,77,768)

4. 准备timesteps

根据使用的scheduler,计算timesteps。stable diffusion默认使用PNDMScheduler,输入的参数num_inference_steps为10步,那么timesteps的长度就为10。

        timesteps, num_inference_steps = retrieve_timesteps(
            self.scheduler, num_inference_steps, device, timesteps, sigmas
        )

5.准备latents

SD的主要计算都是在latent space进行,以加快计算速度。简单理解就是在小图计算再放大(并不准确)。
unet.config.in_channels 为4,latents的height 和width分别为输入参数height 和width 整除 VAE的缩放率,也就是 512 // 8 = 64,生成的latents的shape为 (1,4,64,64)。
latents使用了 torch.randn 生成。

        num_channels_latents = self.unet.config.in_channels
        latents = self.prepare_latents(
            batch_size * num_images_per_prompt,
            num_channels_latents,
            height,
            width,
            prompt_embeds.dtype,
            device,
            generator,
            latents,
        )
latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype, layout=layout).to(device)

6.一些其他参数处理

7.逆扩散,去除噪音

默认使用CFG,那么输入的letents也要复制一遍,和之前的prompt_embeds一起输入到UNet去预测噪声。那么得到的噪声也是两个,分别是无条件(negative_prompt) 噪声和 条件(prompt)噪声。
CFG也是在这里起作用,CFG值越大,那么prompt对预测的噪声影响越大,那么对生成的图像影响也越大。

noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)

然后再根据scheduler的算法,计算前一次的latents(去噪),生成新的latents。
循环执行10次,得到最终的latents。
最后使用VAE的解码部分,将latents还原为图片。

        with self.progress_bar(total=num_inference_steps) as progress_bar:
            for i, t in enumerate(timesteps):
                if self.interrupt:
                    continue
                # expand the latents if we are doing classifier free guidance
                latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
                latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)

                # predict the noise residual
                noise_pred = self.unet(
                    latent_model_input,
                    t,
                    encoder_hidden_states=prompt_embeds,
                    timestep_cond=timestep_cond,
                    cross_attention_kwargs=self.cross_attention_kwargs,
                    added_cond_kwargs=added_cond_kwargs,
                    return_dict=False,
                )[0]
                # perform guidance
                if self.do_classifier_free_guidance:
                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
                # compute the previous noisy sample x_t -> x_t-1
                latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
     if not output_type == "latent":
            image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[0]

标签:diffusion,noise,prompt,文生,pred,self,embeds,latents,stable
From: https://blog.csdn.net/zhilaizhiwang/article/details/140673408

相关文章

  • 新版ChatGPT网站系统源码(GPT-4大模型支持、联网模型提问、DALL-E3文生图),AI绘画/AI视频
    目录一、人工智能SparkAi创作系统系统文档二、功能模块介绍......
  • Enhancing Diffusion Models with Reinforcement Learning
    EnhancingDiffusionModelswithReinforcementLearningSep27,2023 | UncategorizedTL;DRTodaywe'regoingtotellyouallabout DRLX -ourlibraryforDiffusionReinforcementLearning!Releasedafewweeksago,DRLXisalibraryforscalabledist......
  • 《昇思 25 天学习打卡营第 18 天 | 扩散模型(Diffusion Models) 》
    《昇思25天学习打卡营第18天|扩散模型(DiffusionModels)》活动地址:https://xihe.mindspore.cn/events/mindspore-training-camp签名:Sam9029扩散模型(DiffusionModels)扩散模型概述扩散模型(DiffusionModels),特别是去噪扩散概率模型(DDPM),在图像、音频、视频生成领......
  • AIGC-DynamiCrafter: Animating Open-domain Images with Video Diffusion Priors-ECC
    论文:https://arxiv.org/pdf/2310.12190代码:https://github.com/Doubiiu/DynamiCrafter?tab=readme-ov-fileMOTIVATIONTraditionalimageanimationtechniquesmainlyfocusonanimatingnaturalsceneswithstochasticdynamics(e.g.cloudsandfluid)ordom......
  • Stable Diffusion原理与代码实例讲解
    StableDiffusion原理与代码实例讲解1.背景介绍1.1问题的由来在深入探讨StableDiffusion之前,让我们先了解其应用背景。StableDiffusion主要出现在扩散模型领域,特别是在生成对抗网络(GAN)、变分自编码器(VAE)以及自回归模型中。这些模型通常用于生成高质量的样本,例如图像......
  • Debian12 AMD 显卡 7900XT 安装使用 stable-diffusion-webui 笔记
    简介由于AMD官方没有提供Debian12的驱动和ROCM,只好安装Ubuntu20.04的驱动和ROCM,必要软件git和python3-venv。添加i386仓库sudodpkg--add-architecturei386&&\sudoaptupgrade-y&&\aptupgrade-y下载驱动安装程序到AMD官网下载Ubuntu20.04驱动......
  • 2024最新的AI绘画工具 Stable Diffusion 整合包安装教程,SD安装分享(附整合包)
    大家好,我是灵魂画师向阳自从AI绘画开始进入大众视野之后,AI绘画工具StableDiffusion技术以其创新的人工智能能力而著称,它拥有根据用户输入的文字描述来创造细致且富有表现力的图像的独特本领。SD不仅能够生成图像,还能执行图像修复、扩展以及在文本指导下的图像变换等多样......
  • AI绘画Stable Diffusion ,3种方法精确控制人物姿势,总有一种适合你
    前言在AI绘画软件stablediffusion中,控制人物姿势的方法有很多,最简单的方法是在提示词中加入动作提示词,比如Sit,walk,run(坐、走、跑)等,但如果想要精确控制人物姿势就比较难了,首先想要用语言精确描述一个姿势比较困难,另外stablediffusion生图姿势图就像抽盲盒一样具体有......
  • Stable Diffusion【进阶篇】:真人漫改之图生图实现
    所谓真人漫改,就是把一张真人的图片生成一张新的二次元的图片,在StableDiffusion中,有很多方式实现,其中通过图生图的方式是最常用的方式,大概1-3分钟就可以完成。本文我们系统的讲解一下。下面我们来详细看一下图生图实现真人漫改的具体实现方式。【第一步】:图生图图片上......
  • stable diffusion教程:固定同套衣服,一秒快速换脸
    哈喽今天教大家用sd,做封面上的圣斗士女郎。文章使用的AI工具SD整合包、各种模型插件、提示词、AI人工智能学习资料都已经打包好放在网盘中了,无需自行查找,有需要的小伙伴下方扫码自行获取。昨天一位网友私信我,让我用这张圣斗士铠甲,画几个美女壁纸。特别强调铠甲不能变。......