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 等,2023] 在控制基于 Stable Diffusion 的图像生成过程中的大小和架构设计。我们表明,一个参数量仅为基础模型 1% 的新架构可以实现最先进的结果,在 FID 分数方面显著优于 ControlNet。因此,我们将其命名为 ControlNet-XS。我们提供了控制 StableDiffusion-XL [Podell 等,2023](模型 B,48M 参数)和 StableDiffusion 2.1 [Rombach 等,2022](模型 B,14M 参数)的代码,所有这些代码均在 OpenRail 许可证下发布。
该模型由 UmerHA 贡献。❤️
StableDiffusionControlNetXSPipeline
class diffusers.StableDiffusionControlNetXSPipeline
< 来源 >( 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 进行文本到图像生成的流水线。
该模型继承自 DiffusionPipeline。请查看超类文档,了解为所有流水线实现的通用方法(下载、保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- loaders.FromSingleFileMixin.from_single_file() 用于加载
.ckpt
文件
__call__
< 来源 >( 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
的尺寸相同。如果传递了 height 和/或 width,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) — 较高的引导比例值鼓励模型生成与文本prompt
紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1
时,启用引导比例。 - negative_prompt (
str
或List[str]
, 可选) — 引导图像生成中不包含内容的提示词或提示词列表。如果未定义,则需要传递negative_prompt_embeds
。当不使用引导时 (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
, 可选) — 从高斯分布中采样的预生成噪声潜在表示,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,则使用提供的随机generator
采样生成潜在张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则从negative_prompt
输入参数生成negative_prompt_embeds
。 - output_type (
str
, 可选,默认为"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选,默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。 - cross_attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则作为参数传递给self.processor
中定义的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可选, 默认为 1.0) — ControlNet 的输出乘以controlnet_conditioning_scale
后添加到原始unet
中的残差。如果在init
中指定了多个 ControlNet,您可以将相应的比例设置为列表。 - control_guidance_start (
float
或List[float]
, 可选, 默认为 0.0) — ControlNet 开始应用的步数占总步数的百分比。 - control_guidance_end (
float
或List[float]
, 可选, 默认为 1.0) — ControlNet 停止应用的步数占总步数的百分比。 - clip_skip (
int
, 可选) — CLIP 计算提示嵌入时要跳过的层数。值为 1 表示使用倒数第二层的输出计算提示嵌入。 - 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
,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不安全内容”(nsfw) 的 bool
列表。
用于生成的管道的调用函数。
示例
>>> # !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]
, 可选) — 要编码的提示词 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个提示词应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用分类器自由指导 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递negative_prompt_embeds
。在使用非指导模式时(即guidance_scale
小于1
时),此参数会被忽略。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将根据prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,负面提示词嵌入将根据negative_prompt
输入参数生成。 - lora_scale (
float
, 可选) — 一个 LoRA 比例,如果加载了 LoRA 层,将应用于文本编码器的所有 LoRA 层。 - clip_skip (
int
, 可选) — CLIP 计算提示嵌入时要跳过的层数。值为 1 表示使用倒数第二层的输出计算提示嵌入。
将提示编码为文本编码器隐藏状态。
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 管道的输出类。