# Kandinsky 3

  

Kandinsky 3 由 [Vladimir Arkhipkin](https://github.com/oriBetelgeuse)、[Anastasia Maltseva](https://github.com/NastyaMittseva)、[Igor Pavlov](https://github.com/boomb0om)、[Andrei Filatov](https://github.com/anvilarth)、[Arseniy Shakhmatov](https://github.com/cene555)、[Andrey Kuznetsov](https://github.com/kuznetsoffandrey)、[Denis Dimitrov](https://github.com/denndimitrov) 和 [Zein Shaheen](https://github.com/zeinsh) 创建

其 GitHub 页面上的描述：

*Kandinsky 3.0 是一个基于 Kandinsky2-x 模型系列构建的开源文本到图像扩散模型。与之前的版本相比，该模型在文本理解和视觉质量方面进行了增强，分别通过增大文本编码器和 Diffusion U-Net 模型的规模来实现。*

其架构包含 3 个主要组件：
1. [FLAN-UL2](https://huggingface.co/google/flan-ul2)，这是一个基于 T5 架构的编码器-解码器模型。
2. 新的 U-Net 架构采用 BigGAN-deep 块，在保持参数量不变的情况下将深度加倍。
3. Sber-MoVQGAN 是一种解码器，已被证明在图像修复方面具有更优的效果。

原始代码库可在 [ai-forever/Kandinsky-3](https://github.com/ai-forever/Kandinsky-3) 中找到。

> [!TIP]
> 在 Hub 上查看 [Kandinsky Community](https://huggingface.co/kandinsky-community) 组织，以获取文本生成图像、图像生成图像和图像修复等任务的官方模型检查点。

> [!TIP]
> 请务必查阅调度器[指南](../../using-diffusers/schedulers)，了解如何探索调度器速度与质量之间的权衡，并参阅[跨流水线复用组件](../../using-diffusers/loading#reusing-models-in-multiple-pipelines)部分，了解如何高效地将相同组件加载到多个流水线中。

## Kandinsky3Pipeline[[diffusers.Kandinsky3Pipeline]]

#### diffusers.Kandinsky3Pipeline[[diffusers.Kandinsky3Pipeline]]

```python
diffusers.Kandinsky3Pipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: Kandinsky3UNet, scheduler: DDPMScheduler, movq: VQModel)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py#L59)

#### __调用__[[diffusers.Kandinsky3Pipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, num_inference_steps: int = 25, guidance_scale: float = 3.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, height: int | None = 1024, width: int | None = 1024, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, negative_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, latents = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py#L334)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

num_inference_steps (`int`, *可选*，默认为 25)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。

guidance_scale (`float`，*可选*，默认值为 3.0)：如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，通常以牺牲图像质量为代价。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

height (`int`，*可选*，默认为 self.unet.config.sample_size)：生成图像的高度（以像素为单位）。

width (`int`，*可选*，默认为 self.unet.config.sample_size)：生成图像的像素宽度。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

attention_mask (`torch.Tensor`, *可选*) : 预生成的注意力掩码。如果直接传入 `prompt_embeds`，则必须提供此项。

negative_attention_mask (`torch.Tensor`，*可选*)：预生成的负注意力掩码。如果直接传入 `negative_prompt_embeds`，则必须提供此项。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion.IFPipelineOutput` 而不是普通元组。

latents (`torch.Tensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

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](/docs/diffusers/v0.43.0/zh/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) 或 `tuple`

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

示例：
```py
>>> from diffusers import AutoPipelineForText2Image
>>> import torch

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()

>>> prompt = "A photograph of the inside of a subway train. There are raccoons sitting on the seats. One of them is reading a newspaper. The window shows the city in the background."

>>> generator = torch.Generator(device="cpu").manual_seed(0)
>>> image = pipe(prompt, num_inference_steps=25, generator=generator).images[0]
```

#### encode_prompt[[diffusers.Kandinsky3Pipeline.encode_prompt]]

```python
encode_prompt(prompt, do_classifier_free_guidance = True, num_images_per_prompt = 1, device = None, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, _cut_context = False, attention_mask: typing.Optional[torch.Tensor] = None, negative_attention_mask: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py#L91)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

device : (`torch.device`, *可选*): 用于放置生成的嵌入的 torch 设备

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的图像数量

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须改为传入 `negative_prompt_embeds`。如果未定义，则必须改为传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时）将被忽略。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

attention_mask (`torch.Tensor`, *可选*) : 预生成的注意力掩码。如果直接传入 `prompt_embeds`，则必须提供此项。

negative_attention_mask (`torch.Tensor`，*可选*)：预生成的负注意力掩码。如果直接传入 `negative_prompt_embeds`，则必须提供此项。

将提示词编码为文本编码器的隐藏状态。

## Kandinsky3Img2ImgPipeline[[diffusers.Kandinsky3Img2ImgPipeline]]

#### diffusers.Kandinsky3Img2ImgPipeline[[diffusers.Kandinsky3Img2ImgPipeline]]

```python
diffusers.Kandinsky3Img2ImgPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: Kandinsky3UNet, scheduler: DDPMScheduler, movq: VQModel)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py#L56)

#### __调用__[[diffusers.Kandinsky3Img2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]] = None, strength: float = 0.3, num_inference_steps: int = 25, guidance_scale: float = 3.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, negative_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py#L400)

**参数：**

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`，或表示图像批次的张量，将作为该流程的起始点。

strength (`float`，*可选*，默认值为 0.8)：指示对参考 `image` 进行变换的程度。取值必须在 0 到 1 之间。`image` 用作起始点，`strength` 越高，添加的噪声越多。去噪步数取决于初始添加的噪声量。当 `strength` 为 1 时，添加的噪声达到最大值，去噪过程将运行 `num_inference_steps` 中指定的完整迭代次数。值为 1 时，基本上会忽略 `image`。

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

guidance_scale (`float`，*可选*，默认值为 3.0)：如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，通常以牺牲图像质量为代价。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

attention_mask (`torch.Tensor`, *可选*) : 预生成的注意力掩码。如果直接传入 `prompt_embeds`，则必须提供此项。

negative_attention_mask (`torch.Tensor`，*可选*)：预生成的负注意力掩码。如果直接传入 `negative_prompt_embeds`，则必须提供此项。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion.IFPipelineOutput` 而不是普通元组。

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](/docs/diffusers/v0.43.0/zh/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) 或 `tuple`

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

示例：
```py
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image
>>> import torch

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()

>>> prompt = "A painting of the inside of a subway train with tiny raccoons."
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky3/t2i.png"
... )

>>> generator = torch.Generator(device="cpu").manual_seed(0)
>>> image = pipe(prompt, image=image, strength=0.75, num_inference_steps=25, generator=generator).images[0]
```

#### encode_prompt[[diffusers.Kandinsky3Img2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt, do_classifier_free_guidance = True, num_images_per_prompt = 1, device = None, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, _cut_context = True, attention_mask: typing.Optional[torch.Tensor] = None, negative_attention_mask: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py#L106)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

将提示词编码为文本编码器的隐藏状态。

device: (`torch.device`, *可选*): 用于放置生成嵌入的 torch 设备 num_images_per_prompt (`int`, *可选*, 默认为 1): 每个提示词应生成的图像数量 do_classifier_free_guidance (`bool`, *可选*, 默认为 `True`): 是否使用 classifier free guidance negative_prompt (`str` 或 `list[str]`, *可选*): 用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `negative_prompt_embeds`。如果未定义，则必须改为传入 `negative_prompt_embeds`。如果未使用 guidance（即 `guidance_scale` 小于 `1`），则忽略此参数。 prompt_embeds (`torch.Tensor`, *可选*): 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，则将从 `prompt` 输入参数生成文本嵌入。 negative_prompt_embeds (`torch.Tensor`, *可选*): 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，则将从 `negative_prompt` 输入参数生成 negative_prompt_embeds。 attention_mask (`torch.Tensor`, *可选*): 预生成的注意力掩码。如果直接传入 `prompt_embeds`，则必须提供此参数。 negative_attention_mask (`torch.Tensor`, *可选*): 预生成的负向注意力掩码。如果直接传入 `negative_prompt_embeds`，则必须提供此参数。

