Diffusers 文档
ControlNet-XS
并获取增强的文档体验
开始使用
ControlNet-XS
ControlNet-XS 由 Denis Zavadski 和 Carsten Rother 在 ControlNet-XS 中提出。它基于以下观察:原始 ControlNet 中的控制模型可以做得更小,并且仍然产生良好的结果。
与原始 ControlNet 模型一样,您可以提供额外的控制图像来调节和控制 Stable Diffusion 的生成。例如,如果您提供深度图,ControlNet 模型将生成一张保留深度图空间信息的图像。这是一种更灵活、更准确的控制图像生成过程的方式。
ControlNet-XS 生成的图像质量与常规 ControlNet 相当,但速度快 20-25%(请参阅 StableDiffusion-XL 的基准测试),并且内存使用量减少约 45%。
以下是来自 项目页面 的概述
随着计算能力的提升,当前的模型架构似乎遵循简单地放大所有组件的趋势,而没有验证这样做的必要性。在这个项目中,我们研究了 ControlNet [Zhang et al., 2023] 的尺寸和架构设计,以在使用基于稳定扩散的模型时控制图像生成过程。我们表明,一种参数量仅为基础模型 1% 的新架构实现了最先进的结果,在 FID 分数方面明显优于 ControlNet。因此,我们称之为 ControlNet-XS。我们提供了用于控制 StableDiffusion-XL [Podell et al., 2023] (模型 B,48M 参数) 和 StableDiffusion 2.1 [Rombach et al. 2022] (模型 B,14M 参数) 的代码,所有代码均在 openrail 许可下发布。
此模型由 UmerHA 贡献。 ❤️
StableDiffusionControlNetXSPipeline
class diffusers.StableDiffusionControlNetXSPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.controlnets.controlnet_xs.UNetControlNetXSModel] controlnet: ControlNetXSAdapter scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式,以及从潜在表示形式解码为图像。
- text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用于标记文本的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 一个 UNet2DConditionModel,用于创建 UNetControlNetXSModel 以对编码后的图像潜在空间进行去噪。
- controlnet (
ControlNetXSAdapter
) — 一个ControlNetXSAdapter
,与unet
结合使用以对编码后的图像潜在空间进行去噪。 - scheduler (SchedulerMixin) — 一个调度器,与
unet
结合使用以对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于估计生成的图像是否可能被认为是冒犯性或有害的。有关模型潜在危害的更多详细信息,请参阅 模型卡。 - feature_extractor (CLIPImageProcessor) — 一个
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用带有 ControlNet-XS 指导的 Stable Diffusion 进行文本到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。
该 pipeline 还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- loaders.FromSingleFileMixin.from_single_file() 用于加载
.ckpt
文件
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 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 negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 control_guidance_start: float = 0.0 control_guidance_end: float = 1.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] ) → StableDiffusionPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则需要传递prompt_embeds
。 - 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
的尺寸。如果传递了高度和/或宽度,则会相应地调整image
的大小。如果在init
中指定了多个 ControlNet,则必须将图像作为列表传递,以便可以正确批处理列表中的每个元素,以输入到单个 ControlNet。 - height (
int
, 可选, 默认为self.unet.config.sample_size * self.vae_scale_factor
) — 生成图像的像素高度。 - width (
int
, 可选, 默认为self.unet.config.sample_size * self.vae_scale_factor
) — 生成图像的像素宽度。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲更慢的推理速度。 - guidance_scale (
float
, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会牺牲较低的图像质量。当guidance_scale > 1
时,guidance scale 生效。 - negative_prompt (
str
或List[str]
, 可选) — 用于引导图像生成中不应包含的内容的提示或提示列表。如果未定义,则需要传递negative_prompt_embeds
代替。当不使用 guidance 时(guidance_scale < 1
),将被忽略。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的图像数量。 - eta (
float
, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成过程具有确定性的torch.Generator
。 - latents (
torch.Tensor
, 可选) — 预生成的、从高斯分布中采样的噪声潜变量,用作图像生成的输入。可用于使用不同的 prompt 微调相同的生成结果。如果未提供,则会使用提供的随机generator
采样生成潜变量张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从negative_prompt
输入参数生成negative_prompt_embeds
。 - output_type (
str
, 可选,默认为"pil"
) — 生成图像的输出格式。从PIL.Image
或np.array
中选择。 - return_dict (
bool
, 可选,默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通的元组。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可选,默认为 1.0) — ControlNet 的输出在添加到原始unet
中的残差之前,会乘以controlnet_conditioning_scale
。如果在init
中指定了多个 ControlNet,则可以将相应的比例设置为列表。 - control_guidance_start (
float
或List[float]
, 可选,默认为 0.0) — ControlNet 开始应用的占总步数的百分比。 - control_guidance_end (
float
或List[float]
, 可选,默认为 1.0) — ControlNet 停止应用的占总步数的百分比。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预最终层的输出将用于计算 prompt 嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可选) — 在推理期间的每个去噪步骤结束时调用的函数或PipelineCallback
或MultiPipelineCallbacks
的子类。 具有以下参数: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
属性中列出的变量。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
用于生成的管道调用函数。
示例
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetXSPipeline, ControlNetXSAdapter
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> import cv2
>>> from PIL import Image
>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"
>>> # download an image
>>> image = load_image(
... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )
>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5
>>> controlnet = ControlNetXSAdapter.from_pretrained(
... "UmerHA/Testing-ConrolNetXS-SD2.1-canny", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionControlNetXSPipeline.from_pretrained(
... "stabilityai/stable-diffusion-2-1-base", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)
>>> # generate image
>>> image = pipe(
... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
... ).images[0]
encode_prompt
< 源代码 >( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的 prompt - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器引导 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
。当不使用引导时(即,如果guidance_scale
小于1
时)将被忽略。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 比例。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预最终层的输出将用于计算 prompt 嵌入。
将 prompt 编码为文本编码器隐藏状态。
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< 源代码 >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion 管道的输出类。