# 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. T5アーキテクチャをベースとしたエンコーダーデコーダーモデルである[FLAN-UL2](https://huggingface.co/google/flan-ul2)。
2. BigGAN-deepブロックを特徴とする新しいU-Netアーキテクチャは、パラメータ数を維持したまま深さを2倍にします。
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/main/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py#L59)

#### __call__[[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/main/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py#L334)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。

num_inference_steps (`int`, *optional*, デフォルトは 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`, *optional*, デフォルトは 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) 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`を直接渡す場合は、必ず指定する必要があります。

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/main/ja/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) または `tuple`

生成用のパイプラインを呼び出したときに実行される関数。

例:
```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/main/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py#L91)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト

device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス

num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数

do_classifier_free_guidance (`bool`、*任意*、デフォルトは`True`) : classifier free guidance を使用するかどうか

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` 入力引数から negative_prompt_embeds が生成されます。

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/main/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py#L56)

#### __call__[[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/main/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) 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`を直接渡す場合は、必ず指定する必要があります。

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/main/ja/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) または `tuple`

生成用のパイプラインを呼び出したときに実行される関数。

例:
```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/main/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` を直接渡す場合は、提供する必要があります。

