Diffusers 文档

ControlNet

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

ControlNet

LoRA

ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 《为文本到图像扩散模型添加条件控制》 中提出。

通过 ControlNet 模型,您可以提供一个额外的控制图像来调整和控制 Stable Diffusion 的生成。例如,如果您提供一个深度图,ControlNet 模型会生成一个保留深度图空间信息的图像。这是一种更灵活、更准确的控制图像生成过程的方式。

论文摘要如下:

我们提出了 ControlNet,一种神经网络架构,用于为大型预训练的文本到图像扩散模型添加空间条件控制。ControlNet 锁定即用型大型扩散模型,并重用其通过数十亿图像预训练的深度且强大的编码层作为强大的主干,以学习各种条件控制。该神经网络架构通过“零卷积”(零初始化卷积层)连接,这些层从零开始逐步增长参数,并确保不会有害的噪声影响微调。我们使用 Stable Diffusion 测试了各种条件控制,例如边缘、深度、分割、人体姿态等,可以使用单个或多个条件,带或不带提示词。我们表明 ControlNet 的训练在小型(<50k)和大型(>1m)数据集上都具有鲁棒性。广泛的结果表明 ControlNet 可能促进更广泛的应用,以控制图像扩散模型。

此流水线由 ishan24 贡献。❤️ 原始代码库可以在 NVlabs/Sana 找到,您可以在 Efficient-Large-Model 的 Hub 配置文件中找到官方 ControlNet 检查点。

SanaControlNetPipeline

class diffusers.SanaControlNetPipeline

< >

( tokenizer: typing.Union[transformers.models.gemma.tokenization_gemma.GemmaTokenizer, transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast] text_encoder: Gemma2PreTrainedModel vae: AutoencoderDC transformer: SanaTransformer2DModel controlnet: SanaControlNetModel scheduler: DPMSolverMultistepScheduler )

使用 Sana 进行文本到图像生成的流水线。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: str = '' num_inference_steps: int = 20 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 4.5 control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 num_images_per_prompt: typing.Optional[int] = 1 height: int = 1024 width: int = 1024 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True clean_caption: bool = False use_resolution_binning: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 300 complex_human_instruction: typing.List[str] = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '] ) SanaPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,则必须传入 prompt_embeds
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1 时),此参数将被忽略。
  • num_inference_steps (int, 可选, 默认为 20) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • timesteps (List[int], 可选) — 自定义时间步长,用于支持 timesteps 参数的调度器的去噪过程。如果未定义,将使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (List[float], 可选) — 自定义 sigmas,用于支持 sigmas 参数的调度器的去噪过程。如果未定义,将使用传入 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 4.5) — 如 Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale 定义为 Imagen Paper 方程 2 中的 w。通过设置 guidance_scale > 1 启用引导比例。更高的引导比例鼓励生成与文本 prompt 紧密相关的图像,通常以牺牲图像质量为代价。
  • control_image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): ControlNet 输入条件,用于为 unet 提供生成引导。如果类型指定为 torch.Tensor,则直接传递给 ControlNet。PIL.Image.Image 也可以作为图像接受。输出图像的尺寸默认为 image 的尺寸。如果传入 height 和/或 width,则 image 会相应地调整大小。如果在 init 中指定了多个 ControlNet,则图像必须作为列表传入,以便列表的每个元素都可以正确地批量输入到单个 ControlNet。
  • controlnet_conditioning_scale (floatList[float], 可选, 默认为 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前,将乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,则可以以列表形式设置相应的比例。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • height (int, 可选, 默认为 self.unet.config.sample_size) — 生成图像的高度(像素)。
  • width (int, 可选, 默认为 self.unet.config.sample_size) — 生成图像的宽度(像素)。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文 https://huggingface.co/papers/2010.02502 中的参数 eta (η)。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,将使用提供的随机 generator 采样生成一个潜在张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • prompt_attention_mask (torch.Tensor, 可选) — 文本嵌入的预生成注意力掩码。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。对于 PixArt-Sigma,此负面提示应为 ""。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_prompt_attention_mask (torch.Tensor, optional) — 为负文本嵌入预先生成的注意力掩码。
  • output_type (str, optional, 默认为 "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, 默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • attention_kwargs — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中定义的 self.processor 下的 AttentionProcessor
  • clean_caption (bool, optional, 默认为 True) — 在创建嵌入之前是否清理标题。需要安装 beautifulsoup4ftfy。如果未安装依赖项,则将从原始提示创建嵌入。
  • use_resolution_binning (bool 默认为 True) — 如果设置为 True,则请求的高度和宽度首先使用 ASPECT_RATIO_1024_BIN 映射到最接近的分辨率。生成的潜在图解码为图像后,它们将调整回请求的分辨率。适用于生成非方形图像。
  • callback_on_step_end (Callable, optional) — 在推理过程中,在每个去噪步骤结束时调用的函数。该函数以以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)callback_kwargs 将包含 callback_on_step_end_tensor_inputs 指定的所有张量列表。
  • callback_on_step_end_tensor_inputs (List, optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含管道类 ._callback_tensor_inputs 属性中列出的变量。
  • max_sequence_length (int 默认为 300) — 用于 prompt 的最大序列长度。
  • complex_human_instruction (List[str], optional) — 复杂人工指令:https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55

返回

SanaPipelineOutputtuple

如果 return_dictTrue,则返回 SanaPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import SanaControlNetPipeline
>>> from diffusers.utils import load_image

>>> pipe = SanaControlNetPipeline.from_pretrained(
...     "ishan24/Sana_600M_1024px_ControlNetPlus_diffusers",
...     variant="fp16",
...     torch_dtype={"default": torch.bfloat16, "controlnet": torch.float16, "transformer": torch.float16},
...     device_map="balanced",
... )
>>> cond_image = load_image(
...     "https://huggingface.co/ishan24/Sana_600M_1024px_ControlNet_diffusers/resolve/main/hed_example.png"
... )
>>> prompt = 'a cat with a neon sign that says "Sana"'
>>> image = pipe(
...     prompt,
...     control_image=cond_image,
... ).images[0]
>>> image.save("output.png")

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing,此方法将返回一步计算解码。

disable_vae_tiling

< >

( )

禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling,此方法将恢复一步计算解码。

enable_vae_slicing

< >

( )

启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分片,分步计算解码。这有助于节省一些内存并允许更大的批次大小。

enable_vae_tiling

< >

( )

启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成瓦片,分多步计算编码和解码。这对于节省大量内存和处理更大的图像非常有用。

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True negative_prompt: str = '' num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None clean_caption: bool = False max_sequence_length: int = 300 complex_human_instruction: typing.Optional[typing.List[str]] = None lora_scale: typing.Optional[float] = None )

参数

  • prompt (strList[str], optional) — 要编码的提示
  • negative_prompt (strList[str], optional) — 不用于引导图像生成的提示。如果未定义,则必须传递 negative_prompt_embeds。在不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。对于 PixArt-Alpha,这应为空字符串。
  • do_classifier_free_guidance (bool, optional, 默认为 True) — 是否使用无分类器引导
  • num_images_per_prompt (int, optional, 默认为 1) — 每个提示应生成的图像数量
  • device — (torch.device, optional): 放置结果嵌入的 torch 设备
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负文本嵌入。对于 Sana,它应该是 "" 字符串的嵌入。
  • clean_caption (bool, 默认为 False) — 如果为 True,函数将在编码前预处理和清理提供的标题。
  • max_sequence_length (int, 默认为 300) — 用于提示的最大序列长度。
  • complex_human_instruction (list[str], 默认为 complex_human_instruction) — 如果 complex_human_instruction 不为空,函数将使用复杂的人工指令作为提示。

将提示编码为文本编码器隐藏状态。

SanaPipelineOutput

class diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] )

参数

  • images (List[PIL.Image.Image]np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表或形状为 (batch_size, height, width, num_channels) 的 numpy 数组。PIL 图像或 numpy 数组表示扩散管道的去噪图像。

Sana 管道的输出类。

< > 在 GitHub 上更新