Diffusers 文档
图像修复
并获得增强的文档体验
开始使用
图像修复
Stable Diffusion 模型也可以应用于图像修复,它允许你通过提供蒙版和文本提示使用 Stable Diffusion 编辑图像的特定部分。
提示
建议将此pipeline与专门为图像修复(inpainting)微调的检查点(checkpoints)一起使用,例如 runwayml/stable-diffusion-inpainting。 默认的文本到图像(text-to-image)Stable Diffusion检查点,例如 stable-diffusion-v1-5/stable-diffusion-v1-5 也兼容,但性能可能稍逊。
请务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器(scheduler)速度和质量之间的权衡,以及如何高效地重用pipeline组件!
如果您有兴趣使用官方的检查点来完成特定任务,请浏览 CompVis、Runway 和 Stability AI Hub 组织!
StableDiffusionInpaintPipeline
class diffusers.StableDiffusionInpaintPipeline
< source >( vae: typing.Union[diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL, diffusers.models.autoencoders.autoencoder_asym_kl.AsymmetricAutoencoderKL] text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )
参数
- vae ([
AutoencoderKL
,AsymmetricAutoencoderKL
]) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。 - text_encoder (
CLIPTextModel
) — 冻结的文本编码器 (clip-vit-large-patch14)。 - tokenizer (CLIPTokenizer) — 用于标记文本的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用于对编码后的图像潜在空间进行去噪的
UNet2DConditionModel
。 - scheduler (SchedulerMixin) — 与
unet
结合使用的调度器,用于对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为具有攻击性或有害。 有关模型潜在危害的更多详细信息,请参阅模型卡。 - feature_extractor (CLIPImageProcessor) — 一个
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用 Stable Diffusion 进行文本引导的图像修复(inpainting)的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。
此 pipeline 还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演(textual inversion)嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- load_ip_adapter() 用于加载 IP 适配器(Adapters)
- 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 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 masked_image_latents: 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 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 clip_skip: 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 数组或张量,表示要进行图像修复的图像批次(使用mask_image
遮罩图像的哪些部分,并根据prompt
重新绘制)。 对于 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)
。 - 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) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。 此参数由strength
调节。 - 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]
, 可选) — 用于指导图像生成中不应包含的内容的 prompt 或 prompts。如果未定义,则需要传递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
, 可选) — 从高斯分布中采样的预生成噪声 latents,用作图像生成的输入。可用于通过不同的 prompts 调整相同的生成结果。如果未提供,则 latents tensor 将通过使用提供的随机generator
进行采样来生成。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则文本 embeddings 会从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则negative_prompt_embeds
会从negative_prompt
输入参数生成。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP 适配器的预生成图像 embeddings。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为(batch_size, num_images, emb_dim)
的 tensor。如果do_classifier_free_guidance
设置为True
,则应包含负面图像 embedding。如果未提供,则 embeddings 会从ip_adapter_image
输入参数计算得出。 - output_type (
str
, 可选, 默认为"pil"
) — 生成的图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通的 tuple。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示预最终层的输出将用于计算 prompt embeddings。 - 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
指定的所有 tensors 的列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的 tensor 输入列表。列表中指定的 tensors 将作为callback_kwargs
参数传递。你将只能包含在你的 pipeline 类的._callback_tensor_inputs
属性中列出的变量。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所”(nsfw)内容。
用于生成的 pipeline 的调用函数。
示例
>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO
>>> from diffusers import StableDiffusionInpaintPipeline
>>> def download_image(url):
... response = requests.get(url)
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = download_image(img_url).resize((512, 512))
>>> mask_image = download_image(mask_url).resize((512, 512))
>>> pipe = StableDiffusionInpaintPipeline.from_pretrained(
... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
enable_attention_slicing
< source >( slice_size: typing.Union[int, str, NoneType] = 'auto' )
启用切片 attention 计算。启用此选项后,attention 模块会将输入 tensor 分割成切片,以分几个步骤计算 attention。对于多个 attention head,计算将按顺序对每个 head 执行。这对于节省一些内存以换取速度的少量降低很有用。
⚠️ 如果你已经在使用 PyTorch 2.0 或 xFormers 中的 scaled_dot_product_attention
(SDPA),请不要启用 attention 切片。这些 attention 计算已经非常节省内存,因此你无需启用此功能。如果在使用 SDPA 或 xFormers 的情况下启用 attention 切片,则可能会导致严重的减速!
示例
>>> 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]
禁用切片 attention 计算。如果之前调用了 enable_attention_slicing
,则 attention 将在一个步骤中计算。
enable_xformers_memory_efficient_attention
< source >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, 可选) — 覆盖默认的None
运算符,用作 xFormers 的memory_efficient_attention()
函数的op
参数。
启用来自 xFormers 的内存高效 attention。启用此选项后,你应该会观察到更低的 GPU 内存使用率以及推理期间的潜在加速。不保证训练期间的加速。
⚠️ 当内存高效 attention 和切片 attention 都启用时,内存高效 attention 优先。
示例
>>> 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 的内存高效 attention。
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/
),其中包含 textual inversion 权重。 - 一个文件的路径(例如
./my_text_inversions.pt
),其中包含 textual inversion 权重。 - 一个 torch state dict。
- 一个字符串,即托管在 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")
load_lora_weights
< source >( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] adapter_name = None **kwargs )
参数
- pretrained_model_name_or_path_or_dict (
str
或os.PathLike
或dict
) — 请参阅 lora_state_dict()。 - adapter_name (
str
, 可选) — 用于引用加载的适配器模型的适配器名称。如果未指定,则将使用default_{i}
,其中 i 是正在加载的适配器总数。 - low_cpu_mem_usage (
bool
, 可选) — 通过仅加载预训练的 LoRA 权重而不初始化随机权重来加速模型加载。 - kwargs (
dict
, 可选) — 请参阅 lora_state_dict()。
将 pretrained_model_name_or_path_or_dict
中指定的 LoRA 权重加载到 self.unet
和 self.text_encoder
中。
所有 kwargs 都将转发到 self.lora_state_dict
。
有关状态字典如何加载的更多详细信息,请参阅 lora_state_dict()。
有关状态字典如何加载到 self.unet
中的更多详细信息,请参阅 load_lora_into_unet()。
有关状态字典如何加载到 self.text_encoder
中的更多详细信息,请参阅 load_lora_into_text_encoder()。
save_lora_weights
< source >( save_directory: typing.Union[str, os.PathLike] unet_lora_layers: typing.Dict[str, typing.Union[torch.nn.modules.module.Module, torch.Tensor]] = None text_encoder_lora_layers: typing.Dict[str, torch.nn.modules.module.Module] = None is_main_process: bool = True weight_name: str = None save_function: typing.Callable = None safe_serialization: bool = True )
参数
- save_directory (
str
或os.PathLike
) — 用于保存 LoRA 参数的目录。如果不存在,将创建该目录。 - unet_lora_layers (
Dict[str, torch.nn.Module]
或Dict[str, torch.Tensor]
) — 对应于unet
的 LoRA 层的状态字典。 - text_encoder_lora_layers (
Dict[str, torch.nn.Module]
或Dict[str, torch.Tensor]
) — 对应于text_encoder
的 LoRA 层的状态字典。必须显式传递文本编码器 LoRA 状态字典,因为它来自 🤗 Transformers。 - is_main_process (
bool
, 可选, 默认为True
) — 调用此函数的进程是否为主进程。在分布式训练期间很有用,您需要在所有进程上调用此函数。在这种情况下,仅在主进程上设置is_main_process=True
,以避免竞争条件。 - save_function (
Callable
) — 用于保存状态字典的函数。在分布式训练中,当您需要用另一种方法替换torch.save
时很有用。可以使用环境变量DIFFUSERS_SAVE_MODE
进行配置。 - safe_serialization (
bool
, 可选, 默认为True
) — 是否使用safetensors
或传统的 PyTorch 方式pickle
保存模型。
保存对应于 UNet 和文本编码器的 LoRA 参数。
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
) — 是否使用无分类器引导(classifier free guidance) - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
。当不使用引导时忽略(即,如果guidance_scale
小于1
则忽略)。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入(text embeddings)。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入(negative text embeddings)。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - lora_scale (
float
, 可选) — LoRA 缩放比例,如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层。 - clip_skip (
int
, 可选) — 在计算 prompt 嵌入时,要从 CLIP 跳过的层数。值为 1 表示预倒数第二层的输出将用于计算 prompt 嵌入。
将 prompt 编码为文本编码器的隐藏状态。
get_guidance_scale_embedding
< 源码 >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
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 管道的输出类。
FlaxStableDiffusionInpaintPipeline
class diffusers.FlaxStableDiffusionInpaintPipeline
< 源码 >( vae: FlaxAutoencoderKL text_encoder: FlaxCLIPTextModel tokenizer: CLIPTokenizer unet: FlaxUNet2DConditionModel 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
。 - scheduler (SchedulerMixin) — 与
unet
结合使用的调度器,用于对编码后的图像潜在空间进行去噪。可以是FlaxDDIMScheduler
、FlaxLMSDiscreteScheduler
、FlaxPNDMScheduler
或FlaxDPMSolverMultistepScheduler
之一。 - safety_checker (
FlaxStableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为是冒犯性或有害的。有关模型潜在危害的更多详细信息,请参阅 模型卡片。 - feature_extractor (CLIPImageProcessor) —
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
基于 Flax 的管线,用于使用 Stable Diffusion 进行文本引导的图像修复。
🧪 这是一个实验性功能!
此模型继承自 FlaxDiffusionPipeline。查看超类文档,了解为所有管线实现的通用方法(下载、保存、在特定设备上运行等)。
__call__
< source >( prompt_ids: Array mask: Array masked_image: Array params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array num_inference_steps: int = 50 height: typing.Optional[int] = None width: typing.Optional[int] = None guidance_scale: typing.Union[float, jax.Array] = 7.5 latents: Array = None neg_prompt_ids: Array = None return_dict: bool = True jit: bool = False ) → FlaxStableDiffusionPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
) — 用于引导图像生成的提示词。 - 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) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会以较慢的推理速度为代价。此参数受strength
调制。 - guidance_scale (
float
, 可选, 默认为 7.5) — 更高的引导尺度值会鼓励模型生成与文本prompt
紧密相关的图像,但会以降低图像质量为代价。当guidance_scale > 1
时,引导尺度启用。 - latents (
jnp.ndarray
, 可选) — 预生成的高斯分布噪声潜在空间,用作图像生成的输入。可用于使用不同的提示词调整相同的生成结果。如果未提供,则会通过使用提供的随机generator
进行采样来生成潜在空间数组。 - jit (
bool
, 默认为False
) — 是否运行生成和安全评分函数的pmap
版本。此参数的存在是因为
__call__
尚未实现端到端 pmap 化。它将在未来的版本中移除。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通元组。
返回值
如果 return_dict
为 True
,则返回 FlaxStableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场合的”(nsfw) 内容。
调用管线进行生成时调用的函数。
示例
>>> import jax
>>> import numpy as np
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> import PIL
>>> import requests
>>> from io import BytesIO
>>> from diffusers import FlaxStableDiffusionInpaintPipeline
>>> def download_image(url):
... response = requests.get(url)
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = download_image(img_url).resize((512, 512))
>>> mask_image = download_image(mask_url).resize((512, 512))
>>> pipeline, params = FlaxStableDiffusionInpaintPipeline.from_pretrained(
... "xvjiarui/stable-diffusion-2-inpainting"
... )
>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> prng_seed = jax.random.PRNGKey(0)
>>> num_inference_steps = 50
>>> num_samples = jax.device_count()
>>> prompt = num_samples * [prompt]
>>> init_image = num_samples * [init_image]
>>> mask_image = num_samples * [mask_image]
>>> prompt_ids, processed_masked_images, processed_masks = pipeline.prepare_inputs(
... prompt, init_image, mask_image
... )
# shard inputs and rng
>>> params = replicate(params)
>>> prng_seed = jax.random.split(prng_seed, jax.device_count())
>>> prompt_ids = shard(prompt_ids)
>>> processed_masked_images = shard(processed_masked_images)
>>> processed_masks = shard(processed_masks)
>>> images = pipeline(
... prompt_ids, processed_masks, processed_masked_images, params, prng_seed, num_inference_steps, jit=True
... ).images
>>> images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
FlaxStableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.FlaxStableDiffusionPipelineOutput
< source >( images: ndarray nsfw_content_detected: typing.List[bool] )
基于 Flax 的 Stable Diffusion 管线的输出类。
返回一个新对象,用新值替换指定的字段。