Diffusers documentation

Kandinsky 2.2

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Kandinsky 2.2

Kandinsky 2.2 由 Arseniy Shakhmatov、Anton Razzhigaev、Aleksandr Nikolich、Vladimir Arkhipkin、Igor Pavlov、Andrey Kuznetsov 和 Denis Dimitrov 创建。

其 GitHub 页面上的描述为:

Kandinsky 2.2 相比其前代版本 Kandinsky 2.1 带来了显著改进,引入了更强大的新图像编码器 CLIP-ViT-G 以及 ControlNet 支持。将图像编码器切换为 CLIP-ViT-G 大幅提升了模型生成更具美感图像和理解文本的能力,从而增强了模型的整体性能。ControlNet 机制的加入使模型能够有效控制图像生成过程,从而产生更精确、更具视觉吸引力的输出,并为文本引导的图像操作开辟了新的可能性。

原始代码库可在 ai-forever/Kandinsky-2 中找到。

在 Hub 上查看 Kandinsky Community 组织,以获取文本生成图像、图像生成图像和图像修复等任务的官方模型检查点。

请务必查阅调度器指南,了解如何探索调度器速度与质量之间的权衡,并参阅跨流水线复用组件部分,了解如何高效地将相同组件加载到多个流水线中。

KandinskyV22PriorPipeline

class diffusers.KandinskyV22PriorPipeline

< >

( prior: PriorTransformerimage_encoder: CLIPVisionModelWithProjectiontext_encoder: CLIPTextModelWithProjectiontokenizer: CLIPTokenizerscheduler: UnCLIPSchedulerimage_processor: CLIPImageProcessorPil )

参数

  • prior (PriorTransformer) — 用于从文本嵌入近似图像嵌入的 unCLIP 标准先验模型。
  • image_encoder (CLIPVisionModelWithProjection) — 冻结的图像编码器。
  • text_encoder (CLIPTextModelWithProjection) — 冻结的文本编码器。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • scheduler (UnCLIPScheduler) — 用于与 prior 配合以生成图像嵌入的调度器。
  • image_processor (CLIPImageProcessor) — 用于预处理来自 clip 的图像的 image_processor。

用于生成 Kandinsky 图像先验的 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int = 1num_inference_steps: int = 25generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneguidance_scale: float = 4.0output_type: str | None = 'pt'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents'] ) → KandinskyPriorPipelineOutput or tuple

参数

  • prompt (str 或 list[str]) — 用于引导图像生成的提示词或提示词列表。
  • negative_prompt (str 或 list[str],可选) — 用于引导图像生成的反向提示词。当未使用引导时将被忽略(即当 guidance_scale 小于 1 时忽略)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • output_type (str,可选,默认为 "pt") — 生成图像的格式。可选值:"np"(np.array)或 "pt"(torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。

返回值

KandinskyPriorPipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

>>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline
>>> import torch

>>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")
>>> pipe_prior.to("cuda")
>>> prompt = "red cat, 4k photo"
>>> image_emb, negative_image_emb = pipe_prior(prompt).to_tuple()

>>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")
>>> pipe.to("cuda")
>>> image = pipe(
...     image_embeds=image_emb,
...     negative_image_embeds=negative_image_emb,
...     height=768,
...     width=768,
...     num_inference_steps=50,
... ).images
>>> image[0].save("cat.png")

interpolate

< >

( images_and_prompts: list[typing.Union[str, PIL.Image.Image, torch.Tensor]]weights: list[float]num_images_per_prompt: int = 1num_inference_steps: int = 25generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Nonenegative_prior_prompt: str | None = Nonenegative_prompt: str = ''guidance_scale: float = 4.0device = None ) → KandinskyPriorPipelineOutput or tuple

参数

  • images_and_prompts (list[str | PIL.Image.Image | torch.Tensor]) — 用于引导图像生成的提示词和图像列表。
  • weights — (list[float]): images_and_prompts 中每个条件对应的权重列表
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • negative_prior_prompt (str, 可选) — 用于不引导先验扩散过程的提示词。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。

返回值

KandinskyPriorPipelineOutput 或 tuple

在使用先前流水线进行插值时调用的函数。

示例:

>>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22Pipeline
>>> from diffusers.utils import load_image
>>> import PIL
>>> import torch
>>> from torchvision import transforms

>>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
... )
>>> pipe_prior.to("cuda")
>>> img1 = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... )
>>> img2 = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
...     "/kandinsky/starry_night.jpeg"
... )
>>> images_texts = ["a cat", img1, img2]
>>> weights = [0.3, 0.3, 0.4]
>>> out = pipe_prior.interpolate(images_texts, weights)
>>> pipe = KandinskyV22Pipeline.from_pretrained(
...     "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")
>>> image = pipe(
...     image_embeds=out.image_embeds,
...     negative_image_embeds=out.negative_image_embeds,
...     height=768,
...     width=768,
...     num_inference_steps=50,
... ).images[0]
>>> image.save("starry_cat.png")

KandinskyV22Pipeline

class diffusers.KandinskyV22Pipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModel )

参数

  • scheduler (DDIMScheduler | DDPMScheduler) — 用于与 unet 配合以生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。

使用 Kandinsky 进行文本到图像生成的 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]negative_image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]height: int = 512width: int = 512num_inference_steps: int = 100guidance_scale: float = 4.0num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']**kwargs ) → ImagePipelineOutput or tuple

参数

  • image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • negative_image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于负面文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

>>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline
>>> import torch

>>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")
>>> pipe_prior.to("cuda")
>>> prompt = "red cat, 4k photo"
>>> out = pipe_prior(prompt)
>>> image_emb = out.image_embeds
>>> zero_image_emb = out.negative_image_embeds
>>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")
>>> pipe.to("cuda")
>>> image = pipe(
...     image_embeds=image_emb,
...     negative_image_embeds=zero_image_emb,
...     height=768,
...     width=768,
...     num_inference_steps=50,
... ).images
>>> image[0].save("cat.png")

KandinskyV22CombinedPipeline

class diffusers.KandinskyV22CombinedPipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModelprior_prior: PriorTransformerprior_image_encoder: CLIPVisionModelWithProjectionprior_text_encoder: CLIPTextModelWithProjectionprior_tokenizer: CLIPTokenizerprior_scheduler: UnCLIPSchedulerprior_image_processor: CLIPImageProcessorPil )

参数

  • scheduler (DDIMScheduler | DDPMScheduler) — 用于与 unet 配合以生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。
  • prior_prior (PriorTransformer) — 用于从文本嵌入近似图像嵌入的 unCLIP 标准先验模型。
  • prior_image_encoder (CLIPVisionModelWithProjection) — 冻结的图像编码器。
  • prior_text_encoder (CLIPTextModelWithProjection) — 冻结的文本编码器。
  • prior_tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • prior_scheduler (UnCLIPScheduler) — 用于与 prior 配合以生成图像嵌入的调度器。
  • prior_image_processor (CLIPImageProcessor) — 用于预处理来自 clip 的图像的 image_processor。

使用 Kandinsky 进行文本到图像生成的组合 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonenum_inference_steps: int = 100guidance_scale: float = 4.0num_images_per_prompt: int = 1height: int = 512width: int = 512prior_guidance_scale: float = 4.0prior_num_inference_steps: int = 25generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1return_dict: bool = Trueprior_callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Noneprior_callback_on_step_end_tensor_inputs: list[str] = ['latents']callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents'] ) → ImagePipelineOutput or tuple

参数

  • prompt (str 或 list[str]) — 用于引导图像生成的提示词或提示词列表。
  • negative_prompt (str 或 list[str],可选) — 用于引导图像生成的反向提示词。当未使用引导时将被忽略(即当 guidance_scale 小于 1 时忽略)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • prior_guidance_scale (float,可选,默认值为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • prior_num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但推理速度会变慢。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • callback (Callable, 可选) — 一个在推理过程中每隔 callback_steps 步调用一次的函数。该函数以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — 调用 callback 函数的频率。如果未指定,则会在每一步调用该回调。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • prior_callback_on_step_end (Callable, 可选) — 在 prior pipeline 推理过程中,每个去噪步骤结束时调用的函数。 该函数以以下参数被调用:prior_callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。
  • prior_callback_on_step_end_tensor_inputs (list,可选) — prior_callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传入。您只能包含先验流水线类的 ._callback_tensor_inputs 属性中列出的变量。
  • callback_on_step_end (Callable, 可选) — 在解码器流水线推理过程中,每个去噪步骤结束时调用的函数。 该函数以以下参数被调用: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 属性中列出的变量。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

from diffusers import AutoPipelineForText2Image
import torch

pipe = AutoPipelineForText2Image.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
)
pipe.enable_model_cpu_offload()

prompt = "A lion in galaxies, spirals, nebulae, stars, smoke, iridescent, intricate detail, octane render, 8k"

image = pipe(prompt=prompt, num_inference_steps=25).images[0]

enable_sequential_cpu_offload

< >

( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )

Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet, text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a torch.device('meta') and loaded to GPU only when their specific submodule has itsforwardmethod called. Note that offloading happens on a submodule basis. Memory savings are higher than withenable_model_cpu_offload`, but performance is lower.

KandinskyV22ControlnetPipeline

class diffusers.KandinskyV22ControlnetPipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModel )

参数

  • scheduler (DDIMScheduler) — 用于与 unet 配合生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。

使用 Kandinsky 进行文本到图像生成的 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]negative_image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]hint: Tensorheight: int = 512width: int = 512num_inference_steps: int = 100guidance_scale: float = 4.0num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1return_dict: bool = True ) → ImagePipelineOutput or tuple

参数

  • hint (torch.Tensor) — ControlNet 条件。
  • image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • negative_image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于负面文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • callback (Callable, 可选) — 一个在推理过程中每隔 callback_steps 步调用一次的函数。该函数以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — 调用 callback 函数的频率。如果未指定,则会在每一步调用该回调。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

KandinskyV22PriorEmb2EmbPipeline

class diffusers.KandinskyV22PriorEmb2EmbPipeline

< >

( prior: PriorTransformerimage_encoder: CLIPVisionModelWithProjectiontext_encoder: CLIPTextModelWithProjectiontokenizer: CLIPTokenizerscheduler: UnCLIPSchedulerimage_processor: CLIPImageProcessorPil )

参数

  • prior (PriorTransformer) — 用于从文本嵌入近似图像嵌入的 unCLIP 标准先验模型。
  • image_encoder (CLIPVisionModelWithProjection) — 冻结的图像编码器。
  • text_encoder (CLIPTextModelWithProjection) — 冻结的文本编码器。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • scheduler (UnCLIPScheduler) — 用于与 prior 配合以生成图像嵌入的调度器。

用于生成 Kandinsky 图像先验的 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str]image: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]]strength: float = 0.3negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int = 1num_inference_steps: int = 25generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneguidance_scale: float = 4.0output_type: str | None = 'pt'return_dict: bool = True ) → KandinskyPriorPipelineOutput or tuple

参数

  • prompt (str 或 list[str]) — 用于引导图像生成的提示词或提示词列表。
  • image (torch.Tensor、PIL.Image.Image、list[torch.Tensor] 或 list[PIL.Image.Image]) — Image,或表示图像批次的张量,将用作图像嵌入的起点。如果直接传入潜在表示,也可以接受图像潜在表示作为 image,此时不会再次进行编码。
  • strength (float,可选,默认值为 0.8) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。
  • negative_prompt (str 或 list[str],可选) — 用于引导图像生成的反向提示词。当未使用引导时将被忽略(即当 guidance_scale 小于 1 时忽略)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • output_type (str,可选,默认为 "pt") — 生成图像的格式。可选值:"np"(np.array)或 "pt"(torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。

返回值

KandinskyPriorPipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

>>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorEmb2EmbPipeline
>>> import torch

>>> pipe_prior = KandinskyPriorPipeline.from_pretrained(
...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
... )
>>> pipe_prior.to("cuda")

>>> prompt = "red cat, 4k photo"
>>> img = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... )
>>> image_emb, nagative_image_emb = pipe_prior(prompt, image=img, strength=0.2).to_tuple()

>>> pipe = KandinskyPipeline.from_pretrained(
...     "kandinsky-community/kandinsky-2-2-decoder, torch_dtype=torch.float16"
... )
>>> pipe.to("cuda")

>>> image = pipe(
...     image_embeds=image_emb,
...     negative_image_embeds=negative_image_emb,
...     height=768,
...     width=768,
...     num_inference_steps=100,
... ).images

>>> image[0].save("cat.png")

interpolate

< >

( images_and_prompts: list[typing.Union[str, PIL.Image.Image, torch.Tensor]]weights: list[float]num_images_per_prompt: int = 1num_inference_steps: int = 25generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Nonenegative_prior_prompt: str | None = Nonenegative_prompt: str = ''guidance_scale: float = 4.0device = None ) → KandinskyPriorPipelineOutput or tuple

参数

  • images_and_prompts (list[str | PIL.Image.Image | torch.Tensor]) — 用于引导图像生成的提示词和图像列表。
  • weights — (list[float]): images_and_prompts 中每个条件对应的权重列表
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • negative_prior_prompt (str, 可选) — 用于不引导先验扩散过程的提示词。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。

返回值

KandinskyPriorPipelineOutput 或 tuple

在使用先前流水线进行插值时调用的函数。

示例:

>>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22Pipeline
>>> from diffusers.utils import load_image
>>> import PIL

>>> import torch
>>> from torchvision import transforms

>>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
... )
>>> pipe_prior.to("cuda")

>>> img1 = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... )

>>> img2 = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
...     "/kandinsky/starry_night.jpeg"
... )

>>> images_texts = ["a cat", img1, img2]
>>> weights = [0.3, 0.3, 0.4]
>>> image_emb, zero_image_emb = pipe_prior.interpolate(images_texts, weights)

>>> pipe = KandinskyV22Pipeline.from_pretrained(
...     "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")

>>> image = pipe(
...     image_embeds=image_emb,
...     negative_image_embeds=zero_image_emb,
...     height=768,
...     width=768,
...     num_inference_steps=150,
... ).images[0]

>>> image.save("starry_cat.png")

KandinskyV22Img2ImgPipeline

class diffusers.KandinskyV22Img2ImgPipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModel )

参数

  • scheduler (DDIMScheduler) — 用于与 unet 配合生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。

使用 Kandinsky 进行图像到图像生成的 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]image: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]]negative_image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]height: int = 512width: int = 512num_inference_steps: int = 100guidance_scale: float = 4.0strength: float = 0.3num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']**kwargs ) → ImagePipelineOutput or tuple

参数

  • image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image,或表示图像批次的张量,将用作该过程的起点。如果直接传入潜在表示,也可以接受图像潜在表示作为 image,此时不会再次进行编码。
  • strength (float,可选,默认值为 0.8) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声将达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 时基本上会忽略 image。
  • negative_image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于负面文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

KandinskyV22Img2ImgCombinedPipeline

class diffusers.KandinskyV22Img2ImgCombinedPipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModelprior_prior: PriorTransformerprior_image_encoder: CLIPVisionModelWithProjectionprior_text_encoder: CLIPTextModelWithProjectionprior_tokenizer: CLIPTokenizerprior_scheduler: UnCLIPSchedulerprior_image_processor: CLIPImageProcessorPil )

参数

  • scheduler (DDIMScheduler | DDPMScheduler) — 用于与 unet 配合以生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。
  • prior_prior (PriorTransformer) — 用于从文本嵌入近似图像嵌入的 unCLIP 标准先验模型。
  • prior_image_encoder (CLIPVisionModelWithProjection) — 冻结的图像编码器。
  • prior_text_encoder (CLIPTextModelWithProjection) — 冻结的文本编码器。
  • prior_tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • prior_scheduler (UnCLIPScheduler) — 用于与 prior 配合以生成图像嵌入的调度器。
  • prior_image_processor (CLIPImageProcessor) — 用于预处理来自 clip 的图像的 image_processor。

使用 Kandinsky 进行图像到图像生成的组合 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str]image: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]]negative_prompt: str | list[str] | None = Nonenum_inference_steps: int = 100guidance_scale: float = 4.0strength: float = 0.3num_images_per_prompt: int = 1height: int = 512width: int = 512prior_guidance_scale: float = 4.0prior_num_inference_steps: int = 25generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1return_dict: bool = Trueprior_callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Noneprior_callback_on_step_end_tensor_inputs: list[str] = ['latents']callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents'] ) → ImagePipelineOutput or tuple

参数

  • prompt (str 或 list[str]) — 用于引导图像生成的提示词或提示词列表。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image,或表示图像批次的张量,将用作该过程的起点。如果直接传入潜在表示,也可以接受图像潜在表示作为 image,此时不会再次进行编码。
  • negative_prompt (str 或 list[str],可选) — 用于引导图像生成的反向提示词。当未使用引导时将被忽略(即当 guidance_scale 小于 1 时忽略)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • strength (float, 可选,默认为 0.3) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 时,实际上会忽略 image。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • prior_guidance_scale (float,可选,默认值为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • prior_num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但推理速度会变慢。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • callback (Callable, 可选) — 一个在推理过程中每隔 callback_steps 步调用一次的函数。该函数以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — 调用 callback 函数的频率。如果未指定,则会在每一步调用该回调。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • prior_callback_on_step_end (Callable, 可选) — 在 prior pipeline 推理过程中,每个去噪步骤结束时调用的函数。 该函数以以下参数被调用:prior_callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。
  • prior_callback_on_step_end_tensor_inputs (list,可选) — prior_callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传入。您只能包含先验流水线类的 ._callback_tensor_inputs 属性中列出的变量。
  • callback_on_step_end (Callable, 可选) — 在解码器流水线推理过程中,每个去噪步骤结束时调用的函数。 该函数以以下参数被调用: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 属性中列出的变量。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

from diffusers import AutoPipelineForImage2Image
import torch
import requests
from io import BytesIO
from PIL import Image
import os

pipe = AutoPipelineForImage2Image.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
)
pipe.enable_model_cpu_offload()

prompt = "A fantasy landscape, Cinematic lighting"
negative_prompt = "low quality, bad quality"

url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"

response = requests.get(url)
image = Image.open(BytesIO(response.content)).convert("RGB")
image.thumbnail((768, 768))

image = pipe(prompt=prompt, image=original_image, num_inference_steps=25).images[0]

enable_model_cpu_offload

< >

( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )

使用 accelerate 将所有模型卸载到 CPU,在性能影响较小的情况下降低内存占用。与 enable_sequential_cpu_offload 相比,此方法在调用某个模型的 forward 方法时,会将整个模型一次性移至 GPU,并且该模型会一直保留在 GPU 上,直到下一个模型开始运行。与 enable_sequential_cpu_offload 相比,此方法的内存节省幅度较小,但由于 unet 的迭代执行,其性能要好得多。

enable_sequential_cpu_offload

< >

( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )

Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet, text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a torch.device('meta') and loaded to GPU only when their specific submodule has itsforwardmethod called. Note that offloading happens on a submodule basis. Memory savings are higher than withenable_model_cpu_offload`, but performance is lower.

KandinskyV22ControlnetImg2ImgPipeline

class diffusers.KandinskyV22ControlnetImg2ImgPipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModel )

参数

  • scheduler (DDIMScheduler) — 用于与 unet 配合生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。

使用 Kandinsky 进行图像到图像生成的 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]image: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]]negative_image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]hint: Tensorheight: int = 512width: int = 512num_inference_steps: int = 100guidance_scale: float = 4.0strength: float = 0.3num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1return_dict: bool = True ) → ImagePipelineOutput or tuple

参数

  • image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image,或表示图像批次的张量,将用作该过程的起点。如果直接传入潜在表示,也可以接受图像潜在表示作为 image,此时不会再次进行编码。
  • strength (float,可选,默认值为 0.8) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声将达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 时基本上会忽略 image。
  • hint (torch.Tensor) — ControlNet 条件。
  • negative_image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于负面文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • callback (Callable, 可选) — 一个在推理过程中每隔 callback_steps 步调用一次的函数。该函数以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — 调用 callback 函数的频率。如果未指定,则会在每一步调用该回调。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

KandinskyV22InpaintPipeline

class diffusers.KandinskyV22InpaintPipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModel )

参数

  • scheduler (DDIMScheduler) — 用于与 unet 配合生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。

使用 Kandinsky2.1 进行文本引导图像修复的 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]image: typing.Union[torch.Tensor, PIL.Image.Image]mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray]negative_image_embeds: typing.Union[torch.Tensor, list[torch.Tensor]]height: int = 512width: int = 512num_inference_steps: int = 100guidance_scale: float = 4.0num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']**kwargs ) → ImagePipelineOutput or tuple

参数

  • image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • image (PIL.Image.Image) — Image,或表示图像批次的张量,该图像将被进行修复,即图像的部分区域将被 mask_image 掩码,并根据 prompt 重新绘制。
  • mask_image (np.array) — 表示图像批次的张量,用于对 image 进行遮罩。遮罩中的白色像素将被重绘,而黑色像素将保留。如果 mask_image 是 PIL 图像,在使用前会先转换为单通道(亮度)。如果它是张量,则应包含一个颜色通道(L)而不是 3 个,因此预期的形状应为 (B, H, W, 1)。
  • negative_image_embeds (torch.Tensor 或 list[torch.Tensor]) — 用于负面文本提示的 CLIP 图像嵌入,将用于条件化图像生成。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

KandinskyV22InpaintCombinedPipeline

class diffusers.KandinskyV22InpaintCombinedPipeline

< >

( unet: UNet2DConditionModelscheduler: DDPMSchedulermovq: VQModelprior_prior: PriorTransformerprior_image_encoder: CLIPVisionModelWithProjectionprior_text_encoder: CLIPTextModelWithProjectionprior_tokenizer: CLIPTokenizerprior_scheduler: UnCLIPSchedulerprior_image_processor: CLIPImageProcessorPil )

参数

  • scheduler (DDIMScheduler | DDPMScheduler) — 用于与 unet 配合以生成图像潜变量的调度器。
  • unet (UNet2DConditionModel) — 用于对图像嵌入进行去噪的条件 U-Net 架构。
  • movq (VQModel) — MoVQ 解码器,用于从潜变量生成图像。
  • prior_prior (PriorTransformer) — 用于从文本嵌入近似图像嵌入的 unCLIP 标准先验模型。
  • prior_image_encoder (CLIPVisionModelWithProjection) — 冻结的图像编码器。
  • prior_text_encoder (CLIPTextModelWithProjection) — 冻结的文本编码器。
  • prior_tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • prior_scheduler (UnCLIPScheduler) — 用于与 prior 配合以生成图像嵌入的调度器。
  • prior_image_processor (CLIPImageProcessor) — 用于预处理来自 clip 的图像的 image_processor。

使用 Kandinsky 进行修复生成的组合 Pipeline

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str]image: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]]mask_image: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]]negative_prompt: str | list[str] | None = Nonenum_inference_steps: int = 100guidance_scale: float = 4.0num_images_per_prompt: int = 1height: int = 512width: int = 512prior_guidance_scale: float = 4.0prior_num_inference_steps: int = 25generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueprior_callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Noneprior_callback_on_step_end_tensor_inputs: list[str] = ['latents']callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']**kwargs ) → ImagePipelineOutput or tuple

参数

  • prompt (str 或 list[str]) — 用于引导图像生成的提示词或提示词列表。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image,或表示图像批次的张量,将用作该过程的起点。如果直接传入潜在表示,也可以接受图像潜在表示作为 image,此时不会再次进行编码。
  • mask_image (np.array) — 表示图像批次的张量,用于对 image 进行遮罩。遮罩中的白色像素将被重绘,而黑色像素将保留。如果 mask_image 是 PIL 图像,在使用前会先转换为单通道(亮度)。如果它是张量,则应包含一个颜色通道(L)而不是 3 个,因此预期的形状应为 (B, H, W, 1)。
  • negative_prompt (str 或 list[str],可选) — 用于引导图像生成的反向提示词。当未使用引导时将被忽略(即当 guidance_scale 小于 1 时忽略)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • height (int,可选,默认值为 512) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认值为 512) — 生成图像的宽度(以像素为单位)。
  • prior_guidance_scale (float,可选,默认值为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • prior_num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但推理速度会变慢。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值:"pil" (PIL.Image.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • prior_callback_on_step_end (Callable, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数。该函数以以下参数被调用:prior_callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。
  • prior_callback_on_step_end_tensor_inputs (list,可选) — prior_callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传入。您只能包含流水线类的 ._callback_tensor_inputs 属性中列出的变量。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。

返回值

ImagePipelineOutput 或 tuple

调用生成 pipeline 时调用的函数。

示例:

from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image
import torch
import numpy as np

pipe = AutoPipelineForInpainting.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder-inpaint", torch_dtype=torch.float16
)
pipe.enable_model_cpu_offload()

prompt = "A fantasy landscape, Cinematic lighting"
negative_prompt = "low quality, bad quality"

original_image = load_image(
    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
)

mask = np.zeros((768, 768), dtype=np.float32)
# Let's mask out an area above the cat's head
mask[:250, 250:-250] = 1

image = pipe(prompt=prompt, image=original_image, mask_image=mask, num_inference_steps=25).images[0]

enable_sequential_cpu_offload

< >

( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )

Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet, text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a torch.device('meta') and loaded to GPU only when their specific submodule has itsforwardmethod called. Note that offloading happens on a submodule basis. Memory savings are higher than withenable_model_cpu_offload`, but performance is lower.

Update on GitHub