【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的博客-优快云博客

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

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

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

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

深度学习_Lcm_Tech的博客-优快云博客

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

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

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

本文章已经生成可运行项目
### Diffusers 的使用指南 Diffusers个用于生成图像、音频等最先进预训练扩散模型的,它既支持推理解决方案,也支持训练自己的扩散模型。与 ComfyUI 和 webUI 等 UI 类应用不同,Diffusers 实际上是个更底层的,可以支持更好的建立自己的工作流而不仅仅是应用[^1]。 #### 安装方法 安装 Diffusers 非常简单,可以通过以下命令进行安装: - **PyTorch 版本**: ```bash pip install --upgrade diffusers[torch] ``` - **Flax 版本**: ```bash pip install --upgrade diffusers[flax] ``` 如果您只需要基本的安装,可以使用以下命令: ```bash pip install --upgrade diffusers ``` 此外,为了更好地管理和优化您的工作流,您还可以安装些额外的依赖项,例如 `accelerate`、`datasets`、`transformers` 等: ```bash pip install -qq -U diffusers datasets transformers accelerate ftfy pyarrow==9.0.0 ``` #### 自定义模型缓存路径 在加载模型之前,您可以设置自定义的模型缓存路径,以便更好地管理您的模型文件: ```python from diffusers import StableDiffusionPipeline import os # 设置环境变量(在加载模型前) os.environ["HF_HOME"] = "/path/to/your/custom/cache" # 然后正常加载模型 pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") ``` #### 扩散模型的使用 使用 Diffusers 加载和运行扩散模型非常直观。以下是个简单的示例,展示如何使用 Stable Diffusion 模型生成图像: ```python from diffusers import StableDiffusionPipeline import torch # 加载预训练模型 model_id = "runwayml/stable-diffusion-v1-5" pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16) pipe = pipe.to("cuda") # 使用 GPU 进行加速 # 生成图像 prompt = "A beautiful butterfly with vibrant colors" image = pipe(prompt).images[0] # 保存图像 image.save("butterfly.png") ``` 在这个示例中,首先加载了预训练的 Stable Diffusion 模型,并将其移动到 GPU 上以提高性能。然后,通过提供个描述性的提示词,生成了张图像并保存为文件。 #### 最佳实践建议 - **环境准备**:确保您的环境中已经安装了必要的依赖项,如 `torch` 或 `jax`,以及 `diffusers`。 - **模型选择**:根据您的需求选择合适的模型版本,例如 `stable-diffusion-v1-5` 或其他变体。 - **硬件加速**:尽可能使用 GPU 来加速模型推理过程,这可以通过将模型移动到 `"cuda"` 设备来实现。 - **自定义缓存路径**:通过设置 `HF_HOME` 环境变量,您可以指定模型文件的存储位置,从而更好地管理磁盘空间。 通过这些步骤,您可以轻松地安装和使用 Diffusers ,并利用其强大的功能来进行图像生成和其他任务。
评论 18
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值