Diffusers documentation
ControlNet
ControlNet
ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 Adding Conditional Control to Text-to-Image Diffusion Models 中提出。
使用 ControlNet 模型,您可以提供一张额外的控制图像,以调节并控制 Stable Diffusion 的生成过程。例如,如果您提供一张深度图,ControlNet 模型将生成一张保留深度图中空间信息的图像。这是一种更灵活、更精确地控制图像生成过程的方式。
该论文的摘要如下:
我们提出了 ControlNet,一种用于为大型预训练文本到图像扩散模型添加空间条件控制的神经网络架构。ControlNet 锁定生产就绪的大型扩散模型,并复用其使用数十亿张图像预训练得到的深层且鲁棒的编码层作为强大的骨干网络,以学习多样化的条件控制。该神经架构通过“零卷积”(零初始化的卷积层)进行连接,这些层使参数从零开始逐步增长,并确保在微调过程中不会产生有害噪声。我们使用 Stable Diffusion 测试了多种条件控制,例如边缘、深度、分割、人体姿态等,支持使用单一或多个条件,以及有或无提示词的情况。我们展示了 ControlNet 的训练在小规模(<50k)和大规模(>1m)数据集上均具有鲁棒性。大量结果表明,ControlNet 有助于将图像扩散模型的应用扩展到更广泛的领域。
此流水线由 ishan24 贡献。❤️ 原始代码库可在 NVlabs/Sana 中找到,你可以在 Efficient-Large-Model 的 Hub 主页上找到官方的 ControlNet 检查点。
SanaControlNetPipeline
class diffusers.SanaControlNetPipeline
< source >( tokenizer: GemmaTokenizertext_encoder: Gemma2PreTrainedModelvae: AutoencoderDCtransformer: SanaTransformer2DModelcontrolnet: SanaControlNetModelscheduler: DPMSolverMultistepScheduler )
使用 Sana 进行文本到图像生成的 Pipeline。
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str = ''num_inference_steps: int = 20timesteps: list = Nonesigmas: list = Noneguidance_scale: float = 4.5control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0num_images_per_prompt: int | None = 1height: int = 1024width: int = 1024eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueclean_caption: bool = Falseuse_resolution_binning: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 300complex_human_instruction: list = ["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: '] ) → SanaPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - num_inference_steps (
int, 可选,默认为 20) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - timesteps (
list[int], 可选) — 用于支持timesteps参数的调度器去噪过程的自定义时间步,该参数位于其set_timesteps方法中。如果未定义,则使用传入num_inference_steps时的默认行为。必须按降序排列。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 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]]): 用于为unet的生成过程提供引导的 ControlNet 输入条件。如果类型指定为torch.Tensor,则会原样传递给 ControlNet。也可以接受PIL.Image.Image作为图像。输出图像的默认尺寸与image的尺寸相同。如果传入了高度和/或宽度,image将相应地调整大小。如果在init中指定了多个 ControlNet,则必须以列表形式传入图像,以便列表中的每个元素都能被正确批处理,作为单个 ControlNet 的输入。 - controlnet_conditioning_scale (
float或list[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 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。 - generator (
torch.Generator或list[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, 可选) — 为负向文本嵌入预生成的注意力掩码。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput而不是普通元组。 - attention_kwargs —
一个 kwargs 字典,如果指定,将传递给
AttentionProcessor,该处理器在 diffusers.models.attention_processor 中定义,并位于self.processor下。 - clean_caption (
bool,可选,默认为True) — 是否在创建嵌入之前清理字幕。需要安装beautifulsoup4和ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。 - use_resolution_binning (
bool,默认为True) — 如果设置为True,请求的高度和宽度会先通过ASPECT_RATIO_1024_BIN映射到最接近的分辨率。生成的潜变量解码为图像后,会被重新调整回请求的分辨率。适用于生成非正方形图像。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传递。您只能包含流水线类._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为300)— 与prompt配合使用的最大序列长度。 - complex_human_instruction (
list[str], 可选) — 用于复杂人类注意力的指令: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55。
返回值
SanaPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 SanaPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成图像的列表
调用生成 pipeline 时调用的函数。
示例:
>>> 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")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenegative_prompt: str = ''num_images_per_prompt: int = 1device: typing.Optional[torch.device] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneclean_caption: bool = Falsemax_sequence_length: int = 300complex_human_instruction: list[str] | None = Nonelora_scale: float | None = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时会被忽略)。对于 PixArt-Alpha,此值应为 ""。 - do_classifier_free_guidance (
bool,可选,默认为True) — 是否使用 classifier free guidance - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词应生成的图像数量 - device — (
torch.device,可选): 用于放置生成的嵌入向量的 torch 设备 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。对于 Sana,它应该是空字符串 "" 的嵌入。 - clean_caption (
bool,默认为False) — 如果为True,该函数将在编码之前对提供的 caption 进行预处理和清理。 - max_sequence_length (
int,默认为 300) — 用于提示词的最大序列长度。 - complex_human_instruction (
list[str],默认为complex_human_instruction) — 如果complex_human_instruction不为空,该函数将使用复杂的 Human 指令作为提示词。
将提示词编码为文本编码器的隐藏状态。
SanaPipelineOutput
class diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
Sana 管道的输出类。