Diffusers 文档
InstructPix2Pix
并获取增强的文档体验
开始使用
InstructPix2Pix
InstructPix2Pix: Learning to Follow Image Editing Instructions 由 Tim Brooks, Aleksander Holynski 和 Alexei A. Efros 创作。
该论文的摘要如下
我们提出了一种通过人类指令编辑图像的方法:给定输入图像和书面指令,告知模型要执行的操作,我们的模型会遵循这些指令来编辑图像。为了获得此问题的训练数据,我们结合了两个大型预训练模型的知识——语言模型 (GPT-3) 和文本到图像模型 (Stable Diffusion) ——以生成大量的图像编辑示例数据集。我们的条件扩散模型 InstructPix2Pix 在我们生成的数据上进行训练,并在推理时推广到真实图像和用户编写的指令。由于它在前向传递中执行编辑,并且不需要每个示例的微调或反演,因此我们的模型可以快速编辑图像,只需几秒钟。我们展示了针对各种输入图像和书面指令的引人注目的编辑结果。
您可以在项目页面、原始代码库上找到有关 InstructPix2Pix 的更多信息,并在演示中尝试使用它。
请务必查看 Schedulers 指南,了解如何探索调度器速度和质量之间的权衡,并查看跨 pipelines 重用组件部分,了解如何有效地将相同的组件加载到多个 pipelines 中。
StableDiffusionInstructPix2PixPipeline
class diffusers.StableDiffusionInstructPix2PixPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None requires_safety_checker: bool = True )
参数
- vae (AutoencoderKL) — 变分自动编码器 (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
的输入。
通过遵循文本指令进行像素级图像编辑的 Pipeline(基于 Stable Diffusion)。
此模型继承自 DiffusionPipeline。查看超类文档以获取为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。
该 pipeline 还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演 embeddings
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- 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 num_inference_steps: int = 100 guidance_scale: float = 7.5 image_guidance_scale: float = 1.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 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'] cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **kwargs ) → StableDiffusionPipelineOutput or tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的 prompt 或 prompts。如果未定义,则需要传递prompt_embeds
。 - image (
torch.Tensor
np.ndarray
,PIL.Image.Image
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) —Image
或 tensor,表示要根据prompt
重新绘制的图像批次。也可以接受图像潜在空间作为image
,但如果直接传递潜在空间,则不会再次编码。 - num_inference_steps (
int
, optional, 默认为 100) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。 - guidance_scale (
float
, optional, 默认为 7.5) — 较高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会降低图像质量。当guidance_scale > 1
时,guidance scale 生效。 - image_guidance_scale (
float
, optional, 默认为 1.5) — 将生成的图像推向初始image
。通过设置image_guidance_scale > 1
启用图像 guidance scale。较高的图像 guidance scale 会鼓励生成与源image
紧密相关的图像,但通常会以降低图像质量为代价。此 pipeline 需要至少为1
的值。 - negative_prompt (
str
或List[str]
, 可选) — 用于引导图像生成中不应包含的内容的 prompt 或 prompts。如果未定义,则需要传递negative_prompt_embeds
代替。当不使用 guidance 时(guidance_scale < 1
),将被忽略。 - num_images_per_prompt (
int
, optional, 默认为 1) — 每个 prompt 生成的图像数量。 - eta (
float
, optional, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。 - generator (
torch.Generator
, optional) — 用于使生成结果具有确定性的torch.Generator
。 - latents (
torch.Tensor
, optional) — 预生成的噪声潜在空间,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompts 调整相同的生成结果。如果未提供,则会通过使用提供的随机generator
进行采样来生成潜在空间 tensor。 - prompt_embeds (
torch.Tensor
, optional) — 预生成的文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则文本 embeddings 会从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, optional) — 预生成的负面文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则negative_prompt_embeds
会从negative_prompt
输入参数生成。 - ip_adapter_image — (
PipelineImageInput
, optional): 可选的图像输入,用于与 IP 适配器一起使用。 - output_type (
str
, optional, 默认为"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, optional, 默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通 tuple。 - 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
指定的所有 tensor 列表。 - callback_on_step_end_tensor_inputs (
List
, optional) —callback_on_step_end
函数的 tensor 输入列表。列表中指定的 tensor 将作为callback_kwargs
参数传递。您将只能包含 pipeline 类的._callback_tensor_inputs
属性中列出的变量。 - cross_attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
pipeline 的调用函数,用于生成图像。
示例
>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO
>>> from diffusers import StableDiffusionInstructPix2PixPipeline
>>> def download_image(url):
... response = requests.get(url)
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
>>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
>>> image = download_image(img_url).resize((512, 512))
>>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
... "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> prompt = "make the mountains snowy"
>>> image = pipe(prompt=prompt, image=image).images[0]
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]
, 可选) — 覆盖用于文本反演权重的令牌。如果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 格式中加载文本反演嵌入向量
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 格式中加载文本反演嵌入向量,请确保先下载向量(例如从 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
, optional, defaults toTrue
) — 是否使用safetensors
或传统的 PyTorch 方式 (使用pickle
) 来保存模型。
保存对应于 UNet 和文本编码器的 LoRA 参数。
StableDiffusionXLInstructPix2PixPipeline
class diffusers.StableDiffusionXLInstructPix2PixPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None is_cosxl_edit: typing.Optional[bool] = False )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
- text_encoder (
CLIPTextModel
) — 冻结的文本编码器。 Stable Diffusion XL 使用 CLIP 的文本部分, 特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
CLIPTextModelWithProjection
) — 第二个冻结的文本编码器。 Stable Diffusion XL 使用 CLIP 的文本和池化部分, 特别是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - tokenizer_2 (
CLIPTokenizer
) — 第二个 CLIPTokenizer 类的分词器。 - unet (UNet2DConditionModel) — 条件 U-Net 架构,用于对编码后的图像潜在空间进行去噪。
- scheduler (SchedulerMixin) — 调度器,与
unet
结合使用,以对编码后的图像潜在空间进行去噪。 可以是 DDIMScheduler、 LMSDiscreteScheduler 或 PNDMScheduler 之一。 - requires_aesthetics_score (
bool
, optional, defaults to"False"
) — 是否unet
需要在推理期间传递 aesthetic_score 条件。另请参阅stabilityai/stable-diffusion-xl-refiner-1-0
的配置。 - force_zeros_for_empty_prompt (
bool
, optional, defaults to"True"
) — 负面 prompt 嵌入是否应始终强制设置为 0。另请参阅stabilityai/stable-diffusion-xl-base-1-0
的配置。 - add_watermarker (
bool
, optional) — 是否使用 invisible_watermark library 库为输出图像添加水印。 如果未定义,如果已安装该包,则默认为 True,否则将不使用水印。 - is_cosxl_edit (
bool
, optional) — 设置后,图像潜在空间将被缩放。
通过遵循文本指令进行像素级图像编辑的 Pipeline。 基于 Stable Diffusion XL。
此模型继承自 DiffusionPipeline。 查看超类文档,了解库为所有 pipeline 实现的通用方法(例如下载或保存、在特定设备上运行等)。
该 pipeline 还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演 embeddings
- from_single_file() 用于加载
.ckpt
文件 - load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = 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 = 100 denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 image_guidance_scale: float = 1.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None ) → ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
或 tuple
参数
- prompt (
str
或List[str]
, optional) — 用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递prompt_embeds
。 - prompt_2 (
str
或List[str]
, optional) — 将发送到tokenizer_2
和text_encoder_2
的 prompt 或 prompts。 如果未定义,则prompt
将在两个文本编码器中使用 - image (
torch.Tensor
或PIL.Image.Image
或np.ndarray
或List[torch.Tensor]
或List[PIL.Image.Image]
或List[np.ndarray]
) — 要使用 pipeline 修改的图像。 - height (
int
, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度像素值。 - width (
int
, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度像素值。 - num_inference_steps (
int
, optional, defaults to 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。 - denoising_end (
float
, optional) — 如果指定,则确定在有意提前终止之前要完成的总去噪过程的比例(介于 0.0 和 1.0 之间)。 因此,返回的样本仍将保留大量的噪声,这由调度器选择的离散时间步长决定。 当此 pipeline 构成“混合去噪器”多 pipeline 设置的一部分时,应理想地使用 denoising_end 参数,如 优化图像输出 中详述的那样。 - guidance_scale (
float
, optional, defaults to 5.0) — 无分类器扩散引导 中定义的引导缩放。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。 通过设置guidance_scale > 1
启用引导缩放。 较高的引导缩放鼓励生成与文本prompt
紧密相关的图像,通常以降低图像质量为代价。 - image_guidance_scale (
float
, optional, defaults to 1.5) — 图像引导缩放旨在将生成的图像推向初始图像image
。 通过设置image_guidance_scale > 1
启用图像引导缩放。 较高的图像引导缩放鼓励生成与源图像image
紧密相关的图像,通常以降低图像质量为代价。 此 pipeline 需要至少为1
的值。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须传递negative_prompt_embeds
。当不使用引导时忽略(即,如果guidance_scale
小于1
则忽略)。 - negative_prompt_2 (
str
或List[str]
, 可选) — 不用于引导图像生成的提示或提示列表,将发送到tokenizer_2
和text_encoder_2
。如果未定义,则negative_prompt
将用于两个文本编码器。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示生成的图像数量。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,对于其他调度器将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成具有确定性的一个或一组 torch generator(s)。 - latents (
torch.Tensor
, 可选) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成结果。如果未提供,将使用提供的随机generator
采样生成潜变量张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从negative_prompt
输入参数生成池化 negative_prompt_embeds。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
而不是普通元组。 - callback (
Callable
, 可选) — 将在推理期间每callback_steps
步调用的函数。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选, 默认为 1) — 将调用callback
函数的频率。如果未指定,则将在每个步骤调用回调。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给AttentionProcessor
,如 diffusers.models.attention_processor 中self.processor
下的定义。 - guidance_rescale (
float
, 可选, 默认为 0.0) — Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的引导重缩放因子。guidance_scale
在 Common Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中定义为φ
。当使用零终端信噪比时,引导重缩放因子应修复过度曝光。 - original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 如果original_size
与target_size
不同,则图像将显示为缩小或放大。如果未指定,original_size
默认为(height, width)
。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。 - crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) —crops_coords_top_left
可用于生成看起来从crops_coords_top_left
位置向下“裁剪”的图像。通常通过将crops_coords_top_left
设置为 (0, 0) 来获得良好的、居中的图像。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。 - target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size
应设置为生成图像所需的宽度和高度。如果未指定,则默认为(height, width)
。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。 - aesthetic_score (
float
, 可选, 默认为 6.0) — 用于通过影响正面文本条件来模拟生成图像的美学评分。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。 - negative_aesthetic_score (
float
, 可选, 默认为 2.5) — SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。可用于通过影响负面文本条件来模拟生成图像的美学评分。
返回值
~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
或 tuple
~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
如果 return_dict
为 True,否则为 tuple
。当返回元组时,第一个元素是包含生成图像的列表。
调用管道进行生成时调用的函数。
示例
>>> import torch
>>> from diffusers import StableDiffusionXLInstructPix2PixPipeline
>>> from diffusers.utils import load_image
>>> resolution = 768
>>> image = load_image(
... "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
... ).resize((resolution, resolution))
>>> edit_instruction = "Turn sky into a cloudy one"
>>> pipe = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
... "diffusers/sdxl-instructpix2pix-768", torch_dtype=torch.float16
... ).to("cuda")
>>> edited_image = pipe(
... prompt=edit_instruction,
... image=image,
... height=resolution,
... width=resolution,
... guidance_scale=3.0,
... image_guidance_scale=1.5,
... num_inference_steps=30,
... ).images[0]
>>> edited_image
encode_prompt
< source >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的提示 - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的提示或提示列表。如果未定义,则prompt
将用于两个文本编码器 - 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
则忽略)。 - negative_prompt_2 (
str
或List[str]
, 可选) — 不希望引导图像生成的提示或提示语,将被发送到tokenizer_2
和text_encoder_2
。 如果未定义,则在两个文本编码器中都使用negative_prompt
。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从negative_prompt
输入参数生成池化 negative_prompt_embeds。 - lora_scale (
float
, 可选) — 一个 lora 缩放比例,如果加载了 LoRA 层,它将被应用于文本编码器的所有 LoRA 层。
将 prompt 编码为文本编码器隐藏状态。