Diffusers 文档
ControlNet
并获取增强的文档体验
开始使用
ControlNet
ControlNet 是由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 Adding Conditional Control to Text-to-Image Diffusion Models 中提出的。
通过 ControlNet 模型,您可以提供额外的控制图像来调节和控制 Stable Diffusion 的生成。例如,如果您提供深度图,ControlNet 模型将生成保留深度图空间信息的图像。这是一种更灵活、更准确的控制图像生成过程的方式。
论文摘要如下:
我们提出了 ControlNet,一种神经网络架构,用于为大型预训练文本到图像扩散模型添加空间条件控制。ControlNet 锁定了生产就绪的大型扩散模型,并重用其使用数十亿图像进行预训练的深度和鲁棒的编码层,作为学习各种条件控制的强大骨干。该神经网络架构与“零卷积”(zero-initialized convolution layers)相连,这些卷积层从零开始逐步增加参数,并确保没有有害噪声会影响微调。我们使用 Stable Diffusion 测试了各种条件控制,例如,边缘、深度、分割、人体姿势等,使用单条件或多条件,有或没有提示。结果表明,ControlNet 的训练对于小型(<50k)和大型(>1m)数据集都是稳健的。广泛的结果表明,ControlNet 可以促进更广泛的应用来控制图像扩散模型。
此模型由 takuma104 贡献。 ❤️
原始代码库可以在 lllyasviel/ControlNet 找到,您可以在 lllyasviel’s Hub 个人资料上找到官方 ControlNet 检查点。
请务必查看 Schedulers 指南,了解如何探索 scheduler 速度和质量之间的权衡,并查看 跨 pipelines 重用组件 部分,了解如何有效地将相同组件加载到多个 pipelines 中。
StableDiffusionControlNetPipeline
class diffusers.StableDiffusionControlNetPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
- text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 一个
CLIPTokenizer
,用于文本分词。 - unet (UNet2DConditionModel) — 一个
UNet2DConditionModel
,用于对编码后的图像潜在空间进行去噪。 - controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪过程中为unet
提供额外的条件信息。如果将多个 ControlNet 设置为列表,则每个 ControlNet 的输出将相加,以创建一个组合的额外条件信息。 - scheduler (SchedulerMixin) — 一个调度器,与
unet
结合使用,以对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler, LMSDiscreteScheduler, 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为是冒犯性或有害的。请参阅 模型卡 以了解有关模型潜在危害的更多详细信息。 - feature_extractor (CLIPImageProcessor) — 一个
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用 Stable Diffusion 和 ControlNet 指导的文本到图像生成管道。
此模型继承自 DiffusionPipeline。查看超类文档以获取为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- from_single_file() 用于加载
.ckpt
文件 - load_ip_adapter() 用于加载 IP 适配器
__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 timesteps: typing.List[int] = None sigmas: typing.List[float] = None 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[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 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[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'] **kwargs ) → 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。当prompt
是列表时,如果为单个 ControlNet 传递了图像列表,则每个图像将与prompt
列表中的每个提示配对。这也适用于多个 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) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲更慢的推理速度。 - timesteps (
List[int]
, 可选) — 自定义时间步长,用于支持在其set_timesteps
方法中使用timesteps
参数的调度器进行去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。必须按降序排列。 - sigmas (
List[float]
, 可选) — 自定义 sigmas,用于支持在其set_timesteps
方法中使用sigmas
参数的调度器进行去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。 - 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
, 可选) — 预生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于通过不同的提示词调整相同的生成。如果未提供,则会通过使用提供的随机generator
进行采样来生成潜在变量张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则会从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则会从negative_prompt
输入参数生成negative_prompt_embeds
。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为(batch_size, num_images, emb_dim)
的张量。如果do_classifier_free_guidance
设置为True
,则应包含负图像嵌入。如果未提供,则嵌入将从ip_adapter_image
输入参数计算得出。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。 - callback (
Callable
, 可选) — 在推理期间每callback_steps
步调用的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选, 默认为 1) — 调用callback
函数的频率。如果未指定,则在每个步骤都调用回调。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可选, 默认为 1.0) — ControlNet 的输出在添加到原始unet
中的残差之前,会乘以controlnet_conditioning_scale
。如果在init
中指定了多个 ControlNet,则可以将相应的比例设置为列表。 - guess_mode (
bool
, 可选, 默认为False
) — 即使您删除所有提示,ControlNet 编码器也会尝试识别输入图像的内容。建议使用介于 3.0 和 5.0 之间的guidance_scale
值。 - 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
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
用于生成管道的调用函数。
示例
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> import cv2
>>> from PIL import Image
>>> # download an image
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> image = np.array(image)
>>> # get canny image
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)
>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> # remove following line if xformers is not installed
>>> pipe.enable_xformers_memory_efficient_attention()
>>> pipe.enable_model_cpu_offload()
>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
... "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
... ).images[0]
enable_attention_slicing
< 源代码 >( slice_size: typing.Union[int, str, NoneType] = 'auto' )
启用切片注意力计算。启用此选项后,注意力模块会将输入张量分割成切片,以分几个步骤计算注意力。对于多个注意力头,计算将按顺序对每个头执行。这对于节省一些内存以换取少量速度下降非常有用。
⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 的 scaled_dot_product_attention
(SDPA),请不要启用注意力切片。这些注意力计算已经非常节省内存,因此您不需要启用此功能。如果您在 SDPA 或 xFormers 上启用注意力切片,则可能会导致严重的减速!
示例
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5",
... torch_dtype=torch.float16,
... use_safetensors=True,
... )
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
禁用切片注意力计算。如果之前调用了 enable_attention_slicing
,则注意力将在一步中计算。
启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分割成切片,以分几个步骤计算解码。这有助于节省一些内存并允许更大的批量大小。
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将恢复为一步计算解码。
enable_xformers_memory_efficient_attention
< 源代码 >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, 可选) — 覆盖默认的None
运算符,用作 xFormers 的memory_efficient_attention()
函数的op
参数。
启用来自 xFormers 的内存高效注意力。启用此选项后,您应该会观察到较低的 GPU 内存使用率和推理期间的潜在加速。不保证训练期间的加速。
⚠️ 当内存高效注意力和切片注意力都启用时,内存高效注意力优先。
示例
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
load_textual_inversion
< 源代码 >( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[typing.List[str], str, NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None **kwargs )
参数
- pretrained_model_name_or_path (
str
或os.PathLike
或List[str or os.PathLike]
或Dict
或List[Dict]
) — 可以是以下之一或它们的列表:- 一个字符串,预训练模型的模型 ID(例如
sd-concepts-library/low-poly-hd-logos-icons
),托管在 Hub 上。 - 一个目录的路径(例如
./my_text_inversion_directory/
),包含文本反演权重。 - 一个文件的路径(例如
./my_text_inversions.pt
),包含文本反演权重。 - 一个 torch 状态字典。
- 一个字符串,预训练模型的模型 ID(例如
- token (
str
或List[str]
, 可选) — 覆盖用于文本反演权重的 token。如果pretrained_model_name_or_path
是一个列表,则token
也必须是等长的列表。 - text_encoder (CLIPTextModel, 可选) — 冻结的文本编码器 (clip-vit-large-patch14)。如果未指定,函数将采用 self.tokenizer。
- tokenizer (CLIPTokenizer, 可选) — 用于标记文本的
CLIPTokenizer
。如果未指定,函数将采用 self.tokenizer。 - weight_name (
str
, 可选) — 自定义权重文件的名称。当以下情况时应使用此项:- 保存的文本反演文件是 🤗 Diffusers 格式,但以特定的权重名称(例如
text_inv.bin
)保存。 - 保存的文本反演文件是 Automatic1111 格式。
- 保存的文本反演文件是 🤗 Diffusers 格式,但以特定的权重名称(例如
- cache_dir (
Union[str, os.PathLike]
, 可选) — 下载的预训练模型配置的缓存目录路径(如果未使用标准缓存)。 - force_download (
bool
, 可选, 默认为False
) — 是否强制(重新)下载模型权重和配置文件,覆盖缓存版本(如果存在)。 - proxies (
Dict[str, str]
, 可选) — 要按协议或端点使用的代理服务器字典,例如,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理用于每个请求。 - local_files_only (
bool
, 可选, 默认为False
) — 是否仅加载本地模型权重和配置文件。如果设置为True
,则不会从 Hub 下载模型。 - token (
str
或bool
, 可选) — 用作远程文件的 HTTP Bearer 授权的令牌。 如果为True
,则使用从diffusers-cli login
生成的令牌(存储在~/.huggingface
中)。 - revision (
str
, 可选, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID 或 Git 允许的任何标识符。 - subfolder (
str
, 可选, 默认为""
) — Hub 上或本地的较大模型存储库中模型文件的子文件夹位置。 - mirror (
str
, 可选) — 镜像源,用于解决在中国下载模型时的可访问性问题。我们不保证来源的及时性或安全性,您应参考镜像站点以获取更多信息。
将 Textual Inversion 嵌入加载到 StableDiffusionPipeline 的文本编码器中(支持 🤗 Diffusers 和 Automatic1111 格式)。
示例
加载 🤗 Diffusers 格式的 Textual Inversion 嵌入向量
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("sd-concepts-library/cat-toy")
prompt = "A <cat-toy> backpack"
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")
要加载 Automatic1111 格式的 Textual Inversion 嵌入向量,请确保首先下载向量(例如从 civitAI),然后本地加载向量
本地
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")
encode_prompt
< source >( 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
) — 是否使用无分类器 guidance - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
。当不使用 guidance 时忽略(即,如果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 编码为文本编码器隐藏状态。
get_guidance_scale_embedding
< source >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
StableDiffusionControlNetImg2ImgPipeline
class diffusers.StableDiffusionControlNetImg2ImgPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )
参数
- vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式以及从潜在表示形式解码图像。
- text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用于对文本进行标记化的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用于对编码后的图像潜在空间进行去噪的
UNet2DConditionModel
。 - controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪过程中为unet
提供额外的条件控制。 如果您将多个 ControlNet 设置为列表,则每个 ControlNet 的输出将相加在一起,以创建一个组合的额外条件控制。 - scheduler (SchedulerMixin) — 调度器,与
unet
结合使用,以对编码后的图像潜在空间进行去噪。 可以是 DDIMScheduler、 LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于估计生成的图像是否可能被认为是冒犯性或有害的。 有关模型潜在危害的更多详细信息,请参阅模型卡。 - feature_extractor (CLIPImageProcessor) — 一个
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用 Stable Diffusion 和 ControlNet 指导的图像到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档以获取为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- from_single_file() 用于加载
.ckpt
文件 - load_ip_adapter() 用于加载 IP 适配器
__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 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 height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.8 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[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]] = 0.8 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[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'] **kwargs ) → StableDiffusionPipelineOutput or tuple
参数
- prompt (
str
或List[str]
, optional) — 用于引导图像生成的提示或提示列表。 如果未定义,则需要传递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]]
): 用作图像生成过程起点的初始图像。 也可以接受图像潜在空间作为image
,如果直接传递潜在空间,则不会再次编码。 - 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。 - height (
int
, optional, 默认为self.unet.config.sample_size * self.vae_scale_factor
) — 生成图像的高度像素值。 - width (
int
, optional, 默认为self.unet.config.sample_size * self.vae_scale_factor
) — 生成图像的宽度像素值。 - strength (
float
, optional, 默认为 0.8) — 指示转换参考image
的程度。 必须介于 0 和 1 之间。image
用作起点,strength
越高,添加的噪点越多。 去噪步骤的数量取决于最初添加的噪点量。 当strength
为 1 时,添加的噪点最大,去噪过程将运行完整数量的迭代次数,该次数在num_inference_steps
中指定。 值为 1 实际上会忽略image
。 - num_inference_steps (
int
, optional, 默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。 - guidance_scale (
float
, optional, 默认为 7.5) — 较高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会降低图像质量。 当guidance_scale > 1
时,将启用 Guidance scale。 - 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
。 - ip_adapter_image — (
PipelineImageInput
, 可选):与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是形状为(batch_size, num_images, emb_dim)
的张量。如果do_classifier_free_guidance
设置为True
,则应包含负图像嵌入。如果未提供,则会从ip_adapter_image
输入参数计算嵌入。 - 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,则可以将相应的比例设置为列表。 - guess_mode (
bool
, 可选, 默认为False
) — 即使您删除了所有提示,ControlNet 编码器也会尝试识别输入图像的内容。建议guidance_scale
值在 3.0 到 5.0 之间。 - 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
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
用于生成管道的调用函数。
示例
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, UniPCMultistepScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> import cv2
>>> from PIL import Image
>>> # download an image
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> np_image = np.array(image)
>>> # get canny image
>>> np_image = cv2.Canny(np_image, 100, 200)
>>> np_image = np_image[:, :, None]
>>> np_image = np.concatenate([np_image, np_image, np_image], axis=2)
>>> canny_image = Image.fromarray(np_image)
>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()
>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
... "futuristic-looking woman",
... num_inference_steps=20,
... generator=generator,
... image=image,
... control_image=canny_image,
... ).images[0]
enable_attention_slicing
< source >( slice_size: typing.Union[int, str, NoneType] = 'auto' )
启用切片注意力计算。启用此选项后,注意力模块会将输入张量分割成切片,以分几个步骤计算注意力。对于多个注意力头,计算将按顺序对每个头执行。这对于节省一些内存以换取少量速度下降非常有用。
⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 的 scaled_dot_product_attention
(SDPA),请不要启用注意力切片。这些注意力计算已经非常节省内存,因此您不需要启用此功能。如果您在 SDPA 或 xFormers 上启用注意力切片,则可能会导致严重的减速!
示例
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5",
... torch_dtype=torch.float16,
... use_safetensors=True,
... )
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
禁用切片注意力计算。如果之前调用了 enable_attention_slicing
,则注意力将在一步中计算。
启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分割成切片,以分几个步骤计算解码。这有助于节省一些内存并允许更大的批量大小。
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将恢复为一步计算解码。
enable_xformers_memory_efficient_attention
< source >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, 可选) — 覆盖默认的None
运算符,用作 xFormers 的memory_efficient_attention()
函数的op
参数。
启用来自 xFormers 的内存高效注意力。启用此选项后,您应该会观察到较低的 GPU 内存使用率和推理期间的潜在加速。不保证训练期间的加速。
⚠️ 当内存高效注意力和切片注意力都启用时,内存高效注意力优先。
示例
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
禁用来自 xFormers 的内存高效注意力。
load_textual_inversion
< source >( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[typing.List[str], str, NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None **kwargs )
参数
- pretrained_model_name_or_path (
str
或os.PathLike
或List[str or os.PathLike]
或Dict
或List[Dict]
) — 可以是以下之一或它们的列表:- 字符串,Hub 上托管的预训练模型的模型 ID(例如
sd-concepts-library/low-poly-hd-logos-icons
)。 - 目录的路径(例如
./my_text_inversion_directory/
),其中包含文本反演权重。 - 文件的路径(例如
./my_text_inversions.pt
),其中包含文本反演权重。 - torch 状态字典。
- 字符串,Hub 上托管的预训练模型的模型 ID(例如
- token (
str
或List[str]
, 可选) — 覆盖用于文本反演权重的 token。如果pretrained_model_name_or_path
是一个列表,则token
也必须是相同长度的列表。 - text_encoder (CLIPTextModel, 可选) — 冻结的文本编码器 (clip-vit-large-patch14)。如果未指定,函数将使用 self.tokenizer。
- tokenizer (CLIPTokenizer, 可选) — 用于标记文本的
CLIPTokenizer
。如果未指定,函数将使用 self.tokenizer。 - weight_name (
str
, 可选) — 自定义权重文件的名称。应在以下情况下使用:- 保存的文本反演文件是 🤗 Diffusers 格式,但以特定的权重名称(例如
text_inv.bin
)保存。 - 保存的文本反演文件是 Automatic1111 格式。
- 保存的文本反演文件是 🤗 Diffusers 格式,但以特定的权重名称(例如
- cache_dir (
Union[str, os.PathLike]
, 可选) — 下载的预训练模型配置缓存目录的路径(如果未使用标准缓存)。 - force_download (
bool
, 可选, 默认为False
) — 是否强制(重新)下载模型权重和配置文件,覆盖缓存的版本(如果存在)。 - proxies (
Dict[str, str]
, 可选) — 按协议或端点使用的代理服务器字典,例如,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理用于每个请求。 - local_files_only (
bool
, 可选, 默认为False
) — 是否仅加载本地模型权重和配置文件。如果设置为True
,则不会从 Hub 下载模型。 - token (
str
或bool
, 可选) — 用作远程文件 HTTP Bearer 授权的 token。如果为True
,则使用从diffusers-cli login
生成的 token(存储在~/.huggingface
中)。 - revision (
str
, 可选, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID 或 Git 允许的任何标识符。 - subfolder (
str
, 可选, 默认为""
) — Hub 或本地的较大模型库中模型文件的子文件夹位置。 - mirror (
str
, 可选) — 镜像源,用于解决在中国下载模型时的可访问性问题。我们不保证来源的及时性或安全性,您应参考镜像站点以获取更多信息。
将 Textual Inversion 嵌入加载到 StableDiffusionPipeline 的文本编码器中(支持 🤗 Diffusers 和 Automatic1111 格式)。
示例
加载 🤗 Diffusers 格式的 Textual Inversion 嵌入向量
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("sd-concepts-library/cat-toy")
prompt = "A <cat-toy> backpack"
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")
要加载 Automatic1111 格式的 Textual Inversion 嵌入向量,请确保首先下载向量(例如从 civitAI),然后本地加载向量
本地
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")
encode_prompt
< source >( 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
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从prompt
输入参数生成文本 embeddings。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 缩放比例。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示预最终层的输出将用于计算 prompt embeddings。
将 prompt 编码为文本编码器隐藏状态。
StableDiffusionControlNetInpaintPipeline
class diffusers.StableDiffusionControlNetInpaintPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )
参数
- vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
- text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用于标记文本的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用于去噪编码图像 latent 的
UNet2DConditionModel
。 - controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪过程中为unet
提供额外的条件控制。如果将多个 ControlNet 设置为列表,则每个 ControlNet 的输出会相加在一起,以创建一个组合的额外条件控制。 - scheduler (SchedulerMixin) — 与
unet
结合使用的调度器,用于对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler、 LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为具有攻击性或有害。有关模型潜在危害的更多详细信息,请参阅模型卡。 - feature_extractor (CLIPImageProcessor) — 一个
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用带有 ControlNet 指导的 Stable Diffusion 进行图像修复的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档以获取为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- from_single_file() 用于加载
.ckpt
文件 - load_ip_adapter() 用于加载 IP 适配器
此 pipeline 可用于专门为图像修复微调的检查点 (runwayml/stable-diffusion-inpainting) 以及默认的文本到图像 Stable Diffusion 检查点 (runwayml/stable-diffusion-v1-5)。对于在这些检查点上微调的 ControlNet,例如 lllyasviel/control_v11p_sd15_inpaint,默认的文本到图像 Stable Diffusion 检查点可能是更优选择。
__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 mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None 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 height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 1.0 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[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]] = 0.5 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[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'] **kwargs ) → 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]
):Image
、NumPy 数组或张量,表示要用作起点的图像批次。对于 NumPy 数组和 PyTorch 张量,期望值范围在[0, 1]
之间。如果是张量或张量列表,则期望形状应为(B, C, H, W)
或(C, H, W)
。 如果是 NumPy 数组或数组列表,则期望形状应为(B, H, W, C)
或(H, W, C)
。 它也可以接受图像潜在表示作为image
,但如果直接传递潜在表示,则不会再次编码。 - mask_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
, —List[PIL.Image.Image]
, 或List[np.ndarray]
):Image
、NumPy 数组或张量,表示要遮罩image
的图像批次。蒙版中的白色像素会被重新绘制,而黑色像素会被保留。如果mask_image
是 PIL 图像,则在使用前会将其转换为单通道(亮度)。如果它是 NumPy 数组或 PyTorch 张量,则应包含一个颜色通道 (L) 而不是 3 个,因此 PyTorch 张量的期望形状为(B, 1, H, W)
、(B, H, W)
、(1, H, W)
、(H, W)
。对于 NumPy 数组,它将是(B, H, W, 1)
、(B, H, W)
、(H, W, 1)
或(H, W)
。 - control_image (
torch.Tensor
,PIL.Image.Image
,List[torch.Tensor]
,List[PIL.Image.Image]
, —List[List[torch.Tensor]]
, 或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
) — 生成图像的宽度像素。 - padding_mask_crop (
int
, 可选, 默认为None
) — 要应用于图像和蒙版的裁剪边距大小。如果为None
,则不对图像和 mask_image 应用裁剪。如果padding_mask_crop
不为None
,它将首先找到一个矩形区域,该区域与图像的长宽比相同,并包含所有蒙版区域,然后根据padding_mask_crop
扩展该区域。然后将根据扩展区域裁剪图像和 mask_image,然后再调整为原始图像大小以进行修复。当蒙版区域很小而图像很大并且包含与修复无关的信息(例如背景)时,这非常有用。 - strength (
float
, 可选, 默认为 1.0) — 指示转换参考image
的程度。必须介于 0 和 1 之间。image
用作起点,强度strength
越高,添加的噪声就越多。去噪步数取决于最初添加的噪声量。当strength
为 1 时,添加的噪声最大,并且去噪过程运行完整的迭代次数,即num_inference_steps
中指定的次数。值为 1 实际上会忽略image
。 - 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) — 每个 prompt 生成的图像数量。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成具有确定性的torch.Generator
。 - latents (
torch.Tensor
, optional) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成结果。如果未提供,则会通过使用提供的随机generator
进行采样来生成潜变量张量。 - prompt_embeds (
torch.Tensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从negative_prompt
输入参数生成negative_prompt_embeds
。 - ip_adapter_image — (
PipelineImageInput
, optional): 与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, optional) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为(batch_size, num_images, emb_dim)
的张量。如果do_classifier_free_guidance
设置为True
,则应包含负面图像嵌入。如果未提供,则从ip_adapter_image
输入参数计算嵌入。 - output_type (
str
, optional, defaults to"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。 - cross_attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。 - controlnet_conditioning_scale (
float
orList[float]
, optional, defaults to 0.5) — ControlNet 的输出在添加到原始unet
中的残差之前,会乘以controlnet_conditioning_scale
。 如果在init
中指定了多个 ControlNet,则可以将相应的比例设置为列表。 - guess_mode (
bool
, optional, defaults toFalse
) — ControlNet 编码器尝试识别输入图像的内容,即使您删除了所有提示。建议guidance_scale
值介于 3.0 和 5.0 之间。 - control_guidance_start (
float
orList[float]
, optional, defaults to 0.0) — ControlNet 开始应用的步骤总数的百分比。 - control_guidance_end (
float
orList[float]
, optional, defaults to 1.0) — ControlNet 停止应用的步骤总数的百分比。 - clip_skip (
int
, optional) — 从 CLIP 中跳过的层数,用于计算提示嵌入。值为 1 表示将使用预最终层的输出计算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, optional) — 一个函数或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
, optional) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您将只能包含管道类的._callback_tensor_inputs
属性中列出的变量。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
用于生成管道的调用函数。
示例
>>> # !pip install transformers accelerate
>>> from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> init_image = load_image(
... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))
>>> generator = torch.Generator(device="cpu").manual_seed(1)
>>> mask_image = load_image(
... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))
>>> def make_canny_condition(image):
... image = np.array(image)
... image = cv2.Canny(image, 100, 200)
... image = image[:, :, None]
... image = np.concatenate([image, image, image], axis=2)
... image = Image.fromarray(image)
... return image
>>> control_image = make_canny_condition(init_image)
>>> controlnet = ControlNetModel.from_pretrained(
... "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()
>>> # generate image
>>> image = pipe(
... "a handsome man with ray-ban sunglasses",
... num_inference_steps=20,
... generator=generator,
... eta=1.0,
... image=init_image,
... mask_image=mask_image,
... control_image=control_image,
... ).images[0]
enable_attention_slicing
< source >( slice_size: typing.Union[int, str, NoneType] = 'auto' )
启用切片注意力计算。启用此选项后,注意力模块会将输入张量分割成切片,以分几个步骤计算注意力。对于多个注意力头,计算将按顺序对每个头执行。这对于节省一些内存以换取少量速度下降非常有用。
⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 的 scaled_dot_product_attention
(SDPA),请不要启用注意力切片。这些注意力计算已经非常节省内存,因此您不需要启用此功能。如果您在 SDPA 或 xFormers 上启用注意力切片,则可能会导致严重的减速!
示例
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5",
... torch_dtype=torch.float16,
... use_safetensors=True,
... )
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
禁用切片注意力计算。如果之前调用了 enable_attention_slicing
,则注意力将在一步中计算。
启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分割成切片,以分几个步骤计算解码。这有助于节省一些内存并允许更大的批量大小。
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将恢复为一步计算解码。
enable_xformers_memory_efficient_attention
< source >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, optional) — 覆盖默认的None
运算符,用作 xFormers 的memory_efficient_attention()
函数的op
参数。
启用来自 xFormers 的内存高效注意力。启用此选项后,您应该会观察到较低的 GPU 内存使用率和推理期间的潜在加速。不保证训练期间的加速。
⚠️ 当内存高效注意力和切片注意力都启用时,内存高效注意力优先。
示例
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
禁用来自 xFormers 的内存高效注意力。
load_textual_inversion
< source >( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[typing.List[str], str, NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None **kwargs )
参数
- pretrained_model_name_or_path (
str
oros.PathLike
orList[str or os.PathLike]
orDict
orList[Dict]
) — 可以是以下之一或它们的列表:- 一个字符串,即托管在 Hub 上的预训练模型的模型 ID(例如
sd-concepts-library/low-poly-hd-logos-icons
)。 - 一个目录的路径(例如
./my_text_inversion_directory/
),其中包含文本反演权重。 - 一个文件的路径(例如
./my_text_inversions.pt
),其中包含文本反演权重。 - 一个 torch 状态字典。
- 一个字符串,即托管在 Hub 上的预训练模型的模型 ID(例如
- token (
str
或List[str]
, 可选) — 覆盖用于文本反演权重的 token。如果pretrained_model_name_or_path
是一个列表,则token
也必须是等长的列表。 - text_encoder (CLIPTextModel, 可选) — 冻结的文本编码器 (clip-vit-large-patch14)。如果未指定,函数将使用
self.tokenizer
。 - tokenizer (CLIPTokenizer, 可选) — 用于文本分词的
CLIPTokenizer
。如果未指定,函数将使用self.tokenizer
。 - weight_name (
str
, 可选) — 自定义权重文件的名称。在以下情况下应使用此参数:- 保存的文本反演文件为 🤗 Diffusers 格式,但以特定的权重名称(如
text_inv.bin
)保存。 - 保存的文本反演文件为 Automatic1111 格式。
- 保存的文本反演文件为 🤗 Diffusers 格式,但以特定的权重名称(如
- cache_dir (
Union[str, os.PathLike]
, 可选) — 下载的预训练模型配置的缓存目录路径(如果未使用标准缓存)。 - force_download (
bool
, 可选, 默认为False
) — 是否强制(重新)下载模型权重和配置文件,覆盖已缓存的版本(如果存在)。 - proxies (
Dict[str, str]
, 可选) — 代理服务器字典,用于按协议或端点使用,例如,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理服务器用于每个请求。 - local_files_only (
bool
, 可选, 默认为False
) — 是否仅加载本地模型权重和配置文件。如果设置为True
,则不会从 Hub 下载模型。 - token (
str
或 bool, 可选) — 用作远程文件 HTTP Bearer 授权的 token。如果为True
,则使用从diffusers-cli login
生成的 token (存储在~/.huggingface
中)。 - revision (
str
, 可选, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID 或 Git 允许的任何标识符。 - subfolder (
str
, 可选, 默认为""
) — 模型文件在 Hub 或本地较大模型库中的子文件夹位置。 - mirror (
str
, 可选) — 镜像源,用于解决在中国下载模型时的访问性问题。我们不保证来源的及时性或安全性,您应参考镜像站点以获取更多信息。
将 Textual Inversion 嵌入加载到 StableDiffusionPipeline 的文本编码器中(支持 🤗 Diffusers 和 Automatic1111 格式)。
示例
加载 🤗 Diffusers 格式的 Textual Inversion 嵌入向量
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("sd-concepts-library/cat-toy")
prompt = "A <cat-toy> backpack"
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")
要加载 Automatic1111 格式的 Textual Inversion 嵌入向量,请确保首先下载向量(例如从 civitAI),然后本地加载向量
本地
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")
encode_prompt
< source >( 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
, 可选) — 在计算 prompt 嵌入时,要从 CLIP 跳过的层数。值为1
表示预最终层的输出将用于计算 prompt 嵌入。
将 prompt 编码为文本编码器隐藏状态。
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion 管道的输出类。
FlaxStableDiffusionControlNetPipeline
class diffusers.FlaxStableDiffusionControlNetPipeline
< source >( vae: FlaxAutoencoderKL text_encoder: FlaxCLIPTextModel tokenizer: CLIPTokenizer unet: FlaxUNet2DConditionModel controlnet: FlaxControlNetModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_flax.FlaxDDIMScheduler, diffusers.schedulers.scheduling_pndm_flax.FlaxPNDMScheduler, diffusers.schedulers.scheduling_lms_discrete_flax.FlaxLMSDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep_flax.FlaxDPMSolverMultistepScheduler] safety_checker: FlaxStableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor dtype: dtype = <class 'jax.numpy.float32'> )
参数
- vae (FlaxAutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自动编码器 (VAE) 模型。
- text_encoder (FlaxCLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用于标记文本的
CLIPTokenizer
。 - unet (FlaxUNet2DConditionModel) — 用于对编码后的图像潜在空间进行去噪的
FlaxUNet2DConditionModel
。 - controlnet (FlaxControlNetModel) — 在去噪过程中为
unet
提供额外的条件控制。 - scheduler (SchedulerMixin) — 与
unet
结合使用的调度器,用于对编码后的图像潜在空间进行去噪。可以是FlaxDDIMScheduler
、FlaxLMSDiscreteScheduler
、FlaxPNDMScheduler
或FlaxDPMSolverMultistepScheduler
之一。 - safety_checker (
FlaxStableDiffusionSafetyChecker
) — 用于估计生成的图像是否可能被认为具有攻击性或有害的分类模块。有关模型潜在危害的更多详细信息,请参阅模型卡。 - feature_extractor (CLIPImageProcessor) — 用于从生成的图像中提取特征的
CLIPImageProcessor
;用作safety_checker
的输入。
基于 Flax 的 pipeline,用于使用带有 ControlNet 指导的 Stable Diffusion 进行文本到图像的生成。
此模型继承自 FlaxDiffusionPipeline。查看超类文档,了解为所有 pipelines 实现的通用方法(下载、保存、在特定设备上运行等)。
__call__
< source >( prompt_ids: Array image: Array params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array num_inference_steps: int = 50 guidance_scale: typing.Union[float, jax.Array] = 7.5 latents: Array = None neg_prompt_ids: Array = None controlnet_conditioning_scale: typing.Union[float, jax.Array] = 1.0 return_dict: bool = True jit: bool = False ) → FlaxStableDiffusionPipelineOutput 或 tuple
参数
- prompt_ids (
jnp.ndarray
) — 用于引导图像生成的提示。 - image (
jnp.ndarray
) — 表示 ControlNet 输入条件的数组,为生成过程中的unet
提供指导。 - params (
Dict
或FrozenDict
) — 包含模型参数/权重的字典。 - prng_seed (
jax.Array
) — 包含随机数生成器密钥的数组。 - num_inference_steps (
int
, 可选,默认为 50) — 去噪步骤的数量。更多去噪步骤通常会以较慢的推理速度为代价,带来更高质量的图像。 - guidance_scale (
float
, 可选,默认为 7.5) — 较高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会降低图像质量。当guidance_scale > 1
时,guidance scale 生效。 - latents (
jnp.ndarray
, 可选) — 从高斯分布中采样的预生成噪声潜在空间,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则会通过使用提供的随机generator
进行采样来生成潜在空间数组。 - controlnet_conditioning_scale (
float
或jnp.ndarray
, 可选,默认为 1.0) — ControlNet 的输出在添加到原始unet
中的残差之前,会乘以controlnet_conditioning_scale
。 - return_dict (
bool
, 可选,默认为True
) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通元组。 - jit (
bool
, 默认为False
) — 是否运行生成和安全评分函数的pmap
版本。此参数的存在是因为
__call__
尚不能进行端到端 pmap。它将在未来的版本中删除。
返回
如果 return_dict
为 True
,则返回 FlaxStableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是指示相应的生成图像是否包含“不适合工作场所”(nsfw)内容的 bool
列表。
用于生成管道的调用函数。
示例
>>> import jax
>>> import numpy as np
>>> import jax.numpy as jnp
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> from diffusers.utils import load_image, make_image_grid
>>> from PIL import Image
>>> from diffusers import FlaxStableDiffusionControlNetPipeline, FlaxControlNetModel
>>> def create_key(seed=0):
... return jax.random.PRNGKey(seed)
>>> rng = create_key(0)
>>> # get canny image
>>> canny_image = load_image(
... "https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/blog_post_cell_10_output_0.jpeg"
... )
>>> prompts = "best quality, extremely detailed"
>>> negative_prompts = "monochrome, lowres, bad anatomy, worst quality, low quality"
>>> # load control net and stable diffusion v1-5
>>> controlnet, controlnet_params = FlaxControlNetModel.from_pretrained(
... "lllyasviel/sd-controlnet-canny", from_pt=True, dtype=jnp.float32
... )
>>> pipe, params = FlaxStableDiffusionControlNetPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, revision="flax", dtype=jnp.float32
... )
>>> params["controlnet"] = controlnet_params
>>> num_samples = jax.device_count()
>>> rng = jax.random.split(rng, jax.device_count())
>>> prompt_ids = pipe.prepare_text_inputs([prompts] * num_samples)
>>> negative_prompt_ids = pipe.prepare_text_inputs([negative_prompts] * num_samples)
>>> processed_image = pipe.prepare_image_inputs([canny_image] * num_samples)
>>> p_params = replicate(params)
>>> prompt_ids = shard(prompt_ids)
>>> negative_prompt_ids = shard(negative_prompt_ids)
>>> processed_image = shard(processed_image)
>>> output = pipe(
... prompt_ids=prompt_ids,
... image=processed_image,
... params=p_params,
... prng_seed=rng,
... num_inference_steps=50,
... neg_prompt_ids=negative_prompt_ids,
... jit=True,
... ).images
>>> output_images = pipe.numpy_to_pil(np.asarray(output.reshape((num_samples,) + output.shape[-3:])))
>>> output_images = make_image_grid(output_images, num_samples // 4, 4)
>>> output_images.save("generated_image.png")
FlaxStableDiffusionControlNetPipelineOutput
class diffusers.pipelines.stable_diffusion.FlaxStableDiffusionPipelineOutput
< source >( images: ndarray nsfw_content_detected: typing.List[bool] )
基于 Flax 的 Stable Diffusion pipelines 的输出类。
返回一个新对象,该对象将指定的字段替换为新值。