【diffusers】(一) diffusers库介绍 & 框架代码解析

1.简介

说到现在最常用的stable diffusion代码,那肯定莫过于stable-diffusion-webui了,它的快捷安装、可视化界面、extension模块等等功能都拓展了使用人群。

虽然在大多数情况下webui都有很好的适用性,但是在某些特殊需求或者应用场景下,我们需要对模型部分结构进行修改(比如把condition模块从文字换成图像,甚至是点云、图表、图结构等数据形式),这时修改模型的同时也需要修改前端可视化代码,时间成本上会较高(主要是我也不会Gradio)。

那可不可以在源码上进行修改呢?我去看了一遍Compvis的1.x版本代码和Stability AI的2.x版本代码,整体的布局和层次都稍微有点混乱(主要是底层部分,以及可替换模块的结构统一性),没有训练验证代码,最关键的是注释太!少!了!

因此,在这个【diffusers】专栏的几篇文章里,我主要给大家介绍一下这个好用的diffusers库,后续会包括整体的框架结构、其中关键的模块、训练及验证的pipe、以及进行自定义修改。


2.diffusers

diffusers是Hugging Face推出的一个diffusion库,它提供了简单方便的diffusion推理训练pipe,同时拥有一个模型和数据社区,代码可以像torchhub一样直接从指定的仓库去调用别人上传的数据集和pretrain checkpoint。除此之外,安装方便,代码结构清晰,注释齐全,二次开发会十分有效率。


3.安装

傻瓜式安装,使用pip或者conda即可。

# pip
pip install --upgrade diffusers[torch]
# conda
conda install -c conda-forge diffusers

4.使用

diffusers使用pipeline类封装各个模块,以及安排其中的调用顺序和输出。

我们来举个例子,以下代码调用StableDiffusionPipeline,from_pretrained是指从特定仓库加载别人预训练好的模型。其中model_id可以是本地的路径,如果本地没找到对应的文件,则会自动去Hugging Face的Community中去自动下载。

from diffusers import StableDiffusionPipeline

model_id = "runwayml/stable-diffusion-v1-5"
stable_diffusion_txt2img = StableDiffusionPipeline.from_pretrained(model_id)

需要注意的是,下载需要科学上网。如果科学上网之后还是下载有问题,可以在model_id前面加上https://huggingface.co/,然后进入对应网站,找到HTTPS或SSH直接用git clone去下载。比如在上述代码里,网址就是https://huggingface.co/runwayml/stable-diffusion-v1-5,然后点击下图里的clone repository用git下载。下载好后记得把文件夹放在对应的路径上。

如果我们不想用别人的模板,或者我想在模板基础上进行修改,应该怎么办呢?

这里我们可以先定义其中的模块,包括Unet、VAE、CLIP、scheduler等,进行编辑和修改后再输入到pipe中去。

from diffusers import StableDiffusionPipeline, DDPMScheduler

model_id = "runwayml/stable-diffusion-v1-5"

scheduler = DDPMScheduler.from_pretrained(model_id)
stable_diffusion_txt2img = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler)

ok,不同的inpainting、txt2img、img2img的pipeline,以及里面不同种类的Unet、VAE、scheduler的替换和自定义我们会在以后单独介绍,现在我们先来看看代码怎么进行推理。

from diffusers import StableDiffusionPipeline
model_id = "runwayml/stable-diffusion-v1-5"
stable_diffusion_txt2img = StableDiffusionPipeline.from_pretrained(model_id)
prompt = "A boy wearing white suspenders and playing basketball"
image = stable_diffusion_txt2img (prompt).images[0]
image.save('generated_image.png')

简单来说,我们只需要把文字prompt输入进去,然后就会按照StableDiffusionPipeline中设置好的流程来进行推理。


5.推理

我们看下StableDiffusionPipeline源码里的具体推理流程,便于更好理解SD,也便于后续进行修改和自定义。

        # 0. 定义unet中的高宽,这里要考虑经过vae后的缩小系数
        height = height or self.unet.config.sample_size * self.vae_scale_factor
        width = width or self.unet.config.sample_size * self.vae_scale_factor


        # 1. 检查输入是否合规
        self.check_inputs(
            prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
        )

        # 2. 定义调用的batch,device以及classifier-free的监督系数
        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]

        device = self._execution_device
        do_classifier_free_guidance = guidance_scale > 1.0

        # 3. 将输入的文字prompt进行encoding
        text_encoder_lora_scale = (
            cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
        )
        prompt_embeds = self._encode_prompt(
            prompt,
            device,
            num_images_per_prompt,
            do_classifier_free_guidance,
            negative_prompt,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            lora_scale=text_encoder_lora_scale,
        )

        # 4. 准备scheduler中的时间步数
        self.scheduler.set_timesteps(num_inference_steps, device=device)
        timesteps = self.scheduler.timesteps

        # 5. 生成对应尺寸的初始噪声图latent
        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,
        )

        # 6. 额外的去噪参数
        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)

        # 7. 循环多个步长进行去噪
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        with self.progress_bar(total=num_inference_steps) as progress_bar:
            for i, t in enumerate(timesteps):
                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
                latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
                noise_pred = self.unet(
                    latent_model_input,
                    t,
                    encoder_hidden_states=prompt_embeds,
                    cross_attention_kwargs=cross_attention_kwargs,
                    return_dict=False,
                )[0]

                if do_classifier_free_guidance:
                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

                if do_classifier_free_guidance and guidance_rescale > 0.0:
                    noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)

                latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]

                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                    progress_bar.update()
                    if callback is not None and i % callback_steps == 0:
                        callback(i, t, latents)

        if not output_type == "latent":
            image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
            image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
        else:
            image = latents
            has_nsfw_concept = None

        if has_nsfw_concept is None:
            do_denormalize = [True] * image.shape[0]
        else:
            do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]

        image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)

        if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
            self.final_offload_hook.offload()

        if not return_dict:
            return (image, has_nsfw_concept)

        return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)

其实也能看出来是怎样一个大概的流程,如果我们后续需要改输入模块,那么直接在pipeline的对应部分重写就可以,十分方便。

后续文章会介绍每个模块的原理特点以及应用场景、如何进行训练和finetune、自定义。


业务合作/学习交流+v:lizhiTechnology

 如果想要了解更多diffusers相关知识,可以参考我的专栏和其他相关文章:

diffusers_Lcm_Tech的博客-CSDN博客

【diffusers】(一) diffusers库介绍 & 框架代码解析-CSDN博客

【diffusers】(二) scheduler介绍 & 代码解析_ddpmscheduler-CSDN博客

【diffusers】(三) pipeline原理及自定义训练推理-CSDN博客

如果想要了解更多深度学习相关知识,可以参考我的其他文章:

深度学习_Lcm_Tech的博客-CSDN博客

【优化器】(一) SGD原理 & pytorch代码解析_sgd优化器-CSDN博客

【损失函数】(一) L1Loss原理 & pytorch代码解析_l1 loss-CSDN博客

【图像生成】(一) DNN 原理 & pytorch代码实例_pytorch dnn代码-CSDN博客

  • 16
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值