Buckets:
# DeepFloyd IF
## 概要
DeepFloyd IF は、高いフォトリアリズムと言語理解能力を備えた、最先端のオープンソースのテキストから画像を生成するモデルです。このモデルは、凍結されたテキストエンコーダーと、3 つの直列に接続されたピクセル拡散モジュールから構成されるモジュール型アーキテクチャです。
- ステージ1: テキストプロンプトに基づいて64x64 pxの画像を生成するベースモデル、
- ステージ2: 64x64 px => 256x256 px のスーパーリゾリューションモデル、および
- ステージ3: 256x256 px => 1024x1024 px の超解像モデル
Stage 1 と Stage 2 は、T5 トランスフォーマーに基づく凍結されたテキストエンコーダーを使用してテキスト埋め込みを抽出し、それをクロスアテンションとアテンションプーリングで強化された UNet アーキテクチャに投入します。Stage 3 は [Stability AI の x4 Upscaling モデル](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)です。その結果、現在の最先端モデルを上回る、非常に効率的なモデルが得られました。COCO データセット上でゼロショット FID スコア 6.66 を達成しています。本研究は、カスケード型拡散モデルの第一段階における大規模な UNet アーキテクチャの可能性を強調し、テキストから画像への合成における有望な未来を示しています。
## 使用方法
IFを使用するには、利用条件への同意が必要です。同意するには、以下を実行してください。
1. [Hugging Face アカウント](https://huggingface.co/join)をお持ちで、ログインしていることを確認してください。
2. [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/DeepFloyd/IF-I-XL-v1.0)のモデルカードでライセンスに同意してください。ステージIのモデルカードでライセンスに同意すると、他のIFモデルについても自動的に同意が適用されます。
3. ローカルでログインしていることを確認してください。`huggingface_hub`をインストールします:
```sh
pip install huggingface_hub --upgrade
```
Pythonシェルでログイン関数を実行します:
```py
from huggingface_hub import login
login()
```
[Hugging Face Hub アクセストークン](https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens)を入力してください。
次に、`diffusers` と依存関係をインストールします。
```sh
pip install -q diffusers accelerate transformers
```
以下のセクションでは、IFの使用方法についてより詳細な例を示します。具体的には、以下の内容です。
- [テキストから画像を生成](#text-to-image-generation)
- [画像から画像への生成](#text-guided-image-to-image-generation)
- [インペインティング](#text-guided-inpainting-generation)
- [モデルの重みの再利用](#converting-between-different-pipelines)
- [速度の最適化](#optimizing-for-speed)
- [メモリ最適化](#optimizing-for-memory)
**利用可能なチェックポイント**
- *ステージ1*
- [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/DeepFloyd/IF-I-XL-v1.0)
- [DeepFloyd/IF-I-L-v1.0](https://huggingface.co/DeepFloyd/IF-I-L-v1.0)
- [DeepFloyd/IF-I-M-v1.0](https://huggingface.co/DeepFloyd/IF-I-M-v1.0)
- *ステージ2*
- [DeepFloyd/IF-II-L-v1.0](https://huggingface.co/DeepFloyd/IF-II-L-v1.0)
- [DeepFloyd/IF-II-M-v1.0](https://huggingface.co/DeepFloyd/IF-II-M-v1.0)
- *ステージ3*
- [stabilityai/stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)
**Google Colab** [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/deepfloyd_if_free_tier_google_colab.ipynb)
### テキストから画像を生成
デフォルトでは、diffusers は [モデルの CPU オフロード](../../optimization/memory#model-offloading) を利用し、VRAM 14 GB 程度の最小構成で IF パイプライン全体を実行します。
```python
from diffusers import DiffusionPipeline
from diffusers.utils import pt_to_pil, make_image_grid
import torch
# stage 1
stage_1 = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, generator=generator, output_type="pt"
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, noise_level=100, generator=generator).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=3)
```
### テキストガイドによる画像から画像への生成
同じ IF モデルの重みは、テキストガイドによる画像から画像への翻訳や画像のバリエーション生成にも使用できます。この場合、[IFImg2ImgPipeline](/docs/diffusers/main/ja/api/pipelines/deepfloyd_if#diffusers.IFImg2ImgPipeline) と [IFImg2ImgSuperResolutionPipeline](/docs/diffusers/main/ja/api/pipelines/deepfloyd_if#diffusers.IFImg2ImgSuperResolutionPipeline) パイプラインを使用して重みをロードすることを確認してください。
**注**: [components](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline.components) 引数を利用することで、重みを2回読み込むことなく、テキストから画像へのパイプラインの重みを画像から画像へのパイプラインに直接移動できます。詳細は[こちら](#converting-between-different-pipelines)を参照してください。
```python
from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch
# download image
url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
original_image = load_image(url)
original_image = original_image.resize((768, 512))
# stage 1
stage_1 = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = IFImg2ImgSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = "A fantasy landscape in style minecraft"
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
image=original_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
original_image=original_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=4)
```
### テキストガイドインペインティング生成
同じ IF モデルの重みは、テキストガイド付きの画像から画像への翻訳や画像のバリエーション生成にも使用できます。この場合、[IFInpaintingPipeline](/docs/diffusers/main/ja/api/pipelines/deepfloyd_if#diffusers.IFInpaintingPipeline) と [IFInpaintingSuperResolutionPipeline](/docs/diffusers/main/ja/api/pipelines/deepfloyd_if#diffusers.IFInpaintingSuperResolutionPipeline) パイプラインを使用して重みをロードすることを確認してください。
**注記**: [こちら](#converting-between-different-pipelines)で説明されている `~DiffusionPipeline.components()` 関数を利用することで、テキストから画像へのパイプラインの重みを、2回読み込むことなく、画像から画像へのパイプラインに直接移動できます。
```python
from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch
# download image
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
original_image = load_image(url)
# download mask
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
mask_image = load_image(url)
# stage 1
stage_1 = IFInpaintingPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = IFInpaintingSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = "blue sunglasses"
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
image=original_image,
mask_image=mask_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
original_image=original_image,
mask_image=mask_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, mask_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=5)
```
### 異なるパイプライン間の変換
`from_pretrained` による読み込みに加えて、Pipelines は他の Pipeline から直接読み込むこともできます。
```python
from diffusers import IFPipeline, IFSuperResolutionPipeline
pipe_1 = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0")
pipe_2 = IFSuperResolutionPipeline.from_pretrained("DeepFloyd/IF-II-L-v1.0")
from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline
pipe_1 = IFImg2ImgPipeline(**pipe_1.components)
pipe_2 = IFImg2ImgSuperResolutionPipeline(**pipe_2.components)
from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline
pipe_1 = IFInpaintingPipeline(**pipe_1.components)
pipe_2 = IFInpaintingSuperResolutionPipeline(**pipe_2.components)
```
### 速度の最適化
IF をより高速に実行するための最もシンプルな最適化は、モデルのすべてのコンポーネントを GPU に移動することです。
```py
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
```
拡散プロセスをより少ないタイムステップ数で実行することもできます。
これは`num_inference_steps`引数によって行えます:
```py
pipe("<prompt>", num_inference_steps=30)
```
または、`timesteps`引数を使用します:
```py
from diffusers.pipelines.deepfloyd_if import fast27_timesteps
pipe("<prompt>", timesteps=fast27_timesteps)
```
画像のバリエーション生成やインペインティングを行う場合、strength 引数を用いてタイムステップ数を減らすこともできます。strength 引数は入力画像に追加するノイズの量を示し、デノイジングプロセスで実行するステップ数も決定します。値を小さくすると画像の変化は少なくなりますが、処理は速くなります。
```py
pipe = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = pipe(image=image, prompt="<prompt>", strength=0.3).images
```
[`torch.compile`](../../optimization/fp16#torchcompile)を使用することもできます。ただし、IFと`torch.compile`の組み合わせについては徹底的にテストしておらず、期待通りの結果が得られない場合があります。
```py
from diffusers import DiffusionPipeline
import torch
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
pipe.text_encoder = torch.compile(pipe.text_encoder, mode="reduce-overhead", fullgraph=True)
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
```
### メモリを最適化
GPU メモリを最適化する場合、標準的な diffusers の CPU オフロード API を使用できます。
モデルベースのCPUオフローディング、
```py
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.enable_model_cpu_offload()
```
または、より積極的なレイヤーベースのCPUオフローディング。
```py
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.enable_sequential_cpu_offload()
```
さらに、T5は8bit精度で読み込むこともできます。
```py
from transformers import T5EncoderModel
text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)
from diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=text_encoder, # pass the previously instantiated 8bit text encoder
unet=None,
device_map="auto",
)
prompt_embeds, negative_embeds = pipe.encode_prompt("<prompt>")
```
Google Colab の無料プランのように CPU RAM が制約されるマシンでは、すべてのモデルコンポーネントを一度に CPU にロードできない場合があります。そのような場合、必要なタイミングでテキストエンコーダーまたは UNet を持つパイプラインのみを手動でロードできます。
```py
from diffusers import IFPipeline, IFSuperResolutionPipeline
import torch
import gc
from transformers import T5EncoderModel
from diffusers.utils import pt_to_pil, make_image_grid
text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)
# text to image
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=text_encoder, # pass the previously instantiated 8bit text encoder
unet=None,
device_map="auto",
)
prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
# Remove the pipeline so we can re-load the pipeline with the unet
del text_encoder
del pipe
gc.collect()
torch.cuda.empty_cache()
pipe = IFPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16, device_map="auto"
)
generator = torch.Generator().manual_seed(0)
stage_1_output = pipe(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# Remove the pipeline so we can load the super-resolution pipeline
del pipe
gc.collect()
torch.cuda.empty_cache()
# First super resolution
pipe = IFSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16, device_map="auto"
)
generator = torch.Generator().manual_seed(0)
stage_2_output = pipe(
image=stage_1_output,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0]], rows=1, rows=2)
```
## 利用可能なパイプライン:
| パイプライン | タスク | Colab
|---|---|:---:|
| [pipeline_if.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py) | *テキストから画像を生成* | - |
| [pipeline_if_superresolution.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py) | *テキストから画像を生成* | - |
| [pipeline_if_img2img.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py) | *画像から画像への生成* | - |
| [pipeline_if_img2img_superresolution.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py) | *画像から画像への生成* | - |
| [pipeline_if_inpainting.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py) | *画像から画像への生成* | - |
| [pipeline_if_inpainting_superresolution.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py) | *画像から画像への生成* | - |
## IFPipeline[[diffusers.IFPipeline]]
#### diffusers.IFPipeline[[diffusers.IFPipeline]]
```python
diffusers.IFPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py#L96)
#### __call__[[diffusers.IFPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, num_inference_steps: int = 100, timesteps: list[int] = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, height: int | None = None, width: int | None = None, eta: float = 0.0, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py#L547)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。
num_inference_steps (`int`、*optional*、デフォルト値は 100) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
timesteps (`list[int]`、*任意*) : デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、等間隔の`num_inference_steps`個のタイムステップが使用されます。降順で指定する必要があります。
guidance_scale (`float`、*任意*、デフォルト値は 7.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) : 生成される画像の幅(ピクセル単位)。
eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。
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 が生成されます。
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 (`Callable`、*任意*) : 推論中に `callback_steps` ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback(step: int, timestep: int, latents: torch.Tensor)`。
callback_steps (`int`、*任意*、デフォルトは 1) : `callback` 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
clean_caption (`bool`、*任意*、デフォルトは`True`) : エンベディングを作成する前にキャプションをクリーンアップするかどうか。`beautifulsoup4` と `ftfy` のインストールが必要です。依存関係がインストールされていない場合、生のプロンプトからエンベディングが作成されます。
cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。
**戻り値:** `~pipelines.stable_diffusion.IFPipelineOutput` または `tuple`
`~pipelines.stable_diffusion.IFPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the `safety_checker`.
生成用のパイプラインを呼び出したときに実行される関数。
例:
```py
>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()
>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt"
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> safety_modules = {
... "feature_extractor": pipe.feature_extractor,
... "safety_checker": pipe.safety_checker,
... "watermarker": pipe.watermarker,
... }
>>> super_res_2_pipe = DiffusionPipeline.from_pretrained(
... "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16
... )
>>> super_res_2_pipe.enable_model_cpu_offload()
>>> image = super_res_2_pipe(
... prompt=prompt,
... image=image,
... ).images
>>> image[0].save("./if_stage_II.png")
```
#### encode_prompt[[diffusers.IFPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py#L168)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト
do_classifier_free_guidance (`bool`、*任意*、デフォルトは`True`) : classifier free guidance を使用するかどうか
num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数
device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス
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 が生成されます。
clean_caption (bool, デフォルトは `False`) : `True` の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
## IFSuperResolutionPipeline[[diffusers.IFSuperResolutionPipeline]]
#### diffusers.IFSuperResolutionPipeline[[diffusers.IFSuperResolutionPipeline]]
```python
diffusers.IFSuperResolutionPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, image_noising_scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py#L82)
#### __call__[[diffusers.IFSuperResolutionPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, height: int = None, width: int = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] = None, num_inference_steps: int = 50, timesteps: list[int] = None, guidance_scale: float = 4.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, noise_level: int = 250, clean_caption: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py#L614)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。
height (`int`、*任意*、デフォルトは None) : 生成される画像のピクセル単位の縦幅。
width (`int`、*任意*、デフォルトは None) : 生成される画像の幅(ピクセル単位)。
image (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`) : アップスケールする画像。
num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
timesteps (`list[int]`、*optional*、デフォルトは None) : デノイジングプロセスに使用するカスタムタイムステップ。定義されていない場合、等間隔の `num_inference_steps` 個のタイムステップが使用されます。降順である必要があります。
guidance_scale (`float`、*任意*、デフォルト値は 4.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) : プロンプトごとに生成する画像の数。
eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。
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 が生成されます。
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 (`Callable`、*任意*) : 推論中に `callback_steps` ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback(step: int, timestep: int, latents: torch.Tensor)`。
callback_steps (`int`、*任意*、デフォルトは 1) : `callback` 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。
noise_level (`int`、*optional*、デフォルト値は 250) : アップスケールされた画像に追加するノイズの量。`[0, 1000)` の範囲内である必要があります。
clean_caption (`bool`、*任意*、デフォルトは`True`) : エンベディングを作成する前にキャプションをクリーンアップするかどうか。`beautifulsoup4` と `ftfy` のインストールが必要です。依存関係がインストールされていない場合、生のプロンプトからエンベディングが作成されます。
**戻り値:** `~pipelines.stable_diffusion.IFPipelineOutput` または `tuple`
`~pipelines.stable_diffusion.IFPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the `safety_checker`.
生成用のパイプラインを呼び出したときに実行される関数。
例:
```py
>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()
>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds
... ).images
>>> image[0].save("./if_stage_II.png")
```
#### encode_prompt[[diffusers.IFSuperResolutionPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py#L302)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト
do_classifier_free_guidance (`bool`、*任意*、デフォルトは`True`) : classifier free guidance を使用するかどうか
num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数
device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス
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 が生成されます。
clean_caption (bool, デフォルトは `False`) : `True` の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
## IFImg2ImgPipeline[[diffusers.IFImg2ImgPipeline]]
#### diffusers.IFImg2ImgPipeline[[diffusers.IFImg2ImgPipeline]]
```python
diffusers.IFImg2ImgPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py#L120)
#### __call__[[diffusers.IFImg2ImgPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, strength: float = 0.7, num_inference_steps: int = 80, timesteps: list[int] = None, guidance_scale: float = 10.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py#L661)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。
image (`torch.Tensor` または `PIL.Image.Image`) : `Image`、または画像バッチを表すテンソル。このプロセスの開始点として使用されます。
strength (`float`、*任意*、デフォルト値は 0.7) : 概念的には、参照となる`image`をどの程度変換するかを示します。0 から 1 の間の値である必要があります。`image`は開始点として使用され、`strength`が大きいほど、それに加えられるノイズが増えます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength`が 1 の場合、追加されるノイズは最大となり、デノイジングプロセスは`num_inference_steps`で指定された全イテレーション数分実行されます。したがって、値が 1 である場合、`image`は実質的に無視されます。
num_inference_steps (`int`、*optional*、デフォルトは 80) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
timesteps (`list[int]`、*任意*) : デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、等間隔の`num_inference_steps`個のタイムステップが使用されます。降順で指定する必要があります。
guidance_scale (`float`、*任意*、デフォルト値は 10.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) : プロンプトごとに生成する画像の数。
eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。
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 が生成されます。
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 (`Callable`、*任意*) : 推論中に `callback_steps` ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback(step: int, timestep: int, latents: torch.Tensor)`。
callback_steps (`int`、*任意*、デフォルトは 1) : `callback` 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
clean_caption (`bool`、*任意*、デフォルトは`True`) : エンベディングを作成する前にキャプションをクリーンアップするかどうか。`beautifulsoup4` と `ftfy` のインストールが必要です。依存関係がインストールされていない場合、生のプロンプトからエンベディングが作成されます。
cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。
**戻り値:** `~pipelines.stable_diffusion.IFPipelineOutput` または `tuple`
`~pipelines.stable_diffusion.IFPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the `safety_checker`.
生成用のパイプラインを呼び出したときに実行される関数。
例:
```py
>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))
>>> pipe = IFImg2ImgPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0",
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0",
... text_encoder=None,
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
```
#### encode_prompt[[diffusers.IFImg2ImgPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py#L192)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト
do_classifier_free_guidance (`bool`、*任意*、デフォルトは`True`) : classifier free guidance を使用するかどうか
num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数
device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス
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 が生成されます。
clean_caption (bool, デフォルトは `False`) : `True` の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
## IFImg2ImgSuperResolutionPipeline[[diffusers.IFImg2ImgSuperResolutionPipeline]]
#### diffusers.IFImg2ImgSuperResolutionPipeline[[diffusers.IFImg2ImgSuperResolutionPipeline]]
```python
diffusers.IFImg2ImgSuperResolutionPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, image_noising_scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py#L124)
#### __call__[[diffusers.IFImg2ImgSuperResolutionPipeline.__call__]]
```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor], original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, strength: float = 0.8, prompt: str | list[str] = None, num_inference_steps: int = 50, timesteps: list[int] = None, guidance_scale: float = 4.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, noise_level: int = 250, clean_caption: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py#L744)
**パラメータ:**
image (`torch.Tensor` または `PIL.Image.Image`) : `Image`、または画像バッチを表すテンソル。このプロセスの開始点として使用されます。
original_image (`torch.Tensor` または `PIL.Image.Image`) : `image` が変異する前の元の画像。
strength (`float`、*任意*、デフォルト値は 0.8) : 概念的には、参照となる`image`をどの程度変換するかを示します。0 から 1 の間の値である必要があります。`image`は開始点として使用され、`strength`が大きいほど、それに加えられるノイズが増えます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength`が 1 の場合、追加されるノイズは最大となり、デノイジングプロセスは`num_inference_steps`で指定された全イテレーション数分実行されます。したがって、値が 1 である場合、`image`は実質的に無視されます。
prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。
num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
timesteps (`list[int]`、*任意*) : デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、等間隔の`num_inference_steps`個のタイムステップが使用されます。降順で指定する必要があります。
guidance_scale (`float`、*任意*、デフォルト値は 4.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) : プロンプトごとに生成する画像の数。
eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。
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 が生成されます。
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 (`Callable`、*任意*) : 推論中に `callback_steps` ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback(step: int, timestep: int, latents: torch.Tensor)`。
callback_steps (`int`、*任意*、デフォルトは 1) : `callback` 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。
noise_level (`int`、*optional*、デフォルト値は 250) : アップスケールされた画像に追加するノイズの量。`[0, 1000)` の範囲内である必要があります。
clean_caption (`bool`、*任意*、デフォルトは`True`) : エンベディングを作成する前にキャプションをクリーンアップするかどうか。`beautifulsoup4` と `ftfy` のインストールが必要です。依存関係がインストールされていない場合、生のプロンプトからエンベディングが作成されます。
**戻り値:** `~pipelines.stable_diffusion.IFPipelineOutput` または `tuple`
`~pipelines.stable_diffusion.IFPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the `safety_checker`.
生成用のパイプラインを呼び出したときに実行される関数。
例:
```py
>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))
>>> pipe = IFImg2ImgPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0",
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0",
... text_encoder=None,
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
```
#### encode_prompt[[diffusers.IFImg2ImgSuperResolutionPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py#L344)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト
do_classifier_free_guidance (`bool`、*任意*、デフォルトは`True`) : classifier free guidance を使用するかどうか
num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数
device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス
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 が生成されます。
clean_caption (bool, デフォルトは `False`) : `True` の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
## IFInpaintingPipeline[[diffusers.IFInpaintingPipeline]]
#### diffusers.IFInpaintingPipeline[[diffusers.IFInpaintingPipeline]]
```python
diffusers.IFInpaintingPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py#L123)
#### __call__[[diffusers.IFInpaintingPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, strength: float = 1.0, num_inference_steps: int = 50, timesteps: list[int] = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py#L753)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。
image (`torch.Tensor` または `PIL.Image.Image`) : `Image`、または画像バッチを表すテンソル。このプロセスの開始点として使用されます。
mask_image (`PIL.Image.Image`) : `Image`、または画像バッチを表すテンソル。`image`にマスクを適用します。マスクの白いピクセルは再描画され、黒いピクセルは保持されます。`mask_image`がPIL画像の場合、使用の前に単一チャネル(輝度)に変換されます。テンソルの場合は、3つのカラーチャネルではなく1つのカラーチャネル(L)を含む必要があります。したがって、期待される形状は`(B, H, W, 1)`です。
strength (`float`、*任意*、デフォルト値は 1.0) : 概念的には、参照となる`image`をどの程度変換するかを示します。0 から 1 の範囲である必要があります。`image`は開始点として使用され、`strength`が大きいほど、それに加えられるノイズが増えます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength`が 1 の場合、追加されるノイズは最大となり、デノイジングプロセスは`num_inference_steps`で指定された全イテレーション数分実行されます。したがって、値が 1 である場合、`image`は実質的に無視されます。
num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
timesteps (`list[int]`、*任意*) : デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、等間隔の`num_inference_steps`個のタイムステップが使用されます。降順で指定する必要があります。
guidance_scale (`float`、*任意*、デフォルト値は 7.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) : プロンプトごとに生成する画像の数。
eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。
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 が生成されます。
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 (`Callable`、*任意*) : 推論中に `callback_steps` ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback(step: int, timestep: int, latents: torch.Tensor)`。
callback_steps (`int`、*任意*、デフォルトは 1) : `callback` 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
clean_caption (`bool`、*任意*、デフォルトは`True`) : エンベディングを作成する前にキャプションをクリーンアップするかどうか。`beautifulsoup4` と `ftfy` のインストールが必要です。依存関係がインストールされていない場合、生のプロンプトからエンベディングが作成されます。
cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。
**戻り値:** `~pipelines.stable_diffusion.IFPipelineOutput` または `tuple`
`~pipelines.stable_diffusion.IFPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the `safety_checker`.
生成用のパイプラインを呼び出したときに実行される関数。
例:
```py
>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image
>>> pipe = IFInpaintingPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "blue sunglasses"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... mask_image=mask_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... mask_image=mask_image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
```
#### encode_prompt[[diffusers.IFInpaintingPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py#L195)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト
do_classifier_free_guidance (`bool`、*任意*、デフォルトは`True`) : classifier free guidance を使用するかどうか
num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数
device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス
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 が生成されます。
clean_caption (bool, デフォルトは `False`) : `True` の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
## IFInpaintingSuperResolutionPipeline[[diffusers.IFInpaintingSuperResolutionPipeline]]
#### diffusers.IFInpaintingSuperResolutionPipeline[[diffusers.IFInpaintingSuperResolutionPipeline]]
```python
diffusers.IFInpaintingSuperResolutionPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, image_noising_scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py#L126)
#### __call__[[diffusers.IFInpaintingSuperResolutionPipeline.__call__]]
```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor], original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, strength: float = 0.8, prompt: str | list[str] = None, num_inference_steps: int = 100, timesteps: list[int] = None, guidance_scale: float = 4.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, noise_level: int = 0, clean_caption: bool = True)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py#L832)
**パラメータ:**
image (`torch.Tensor` または `PIL.Image.Image`) : `Image`、または画像バッチを表すテンソル。このプロセスの開始点として使用されます。
original_image (`torch.Tensor` または `PIL.Image.Image`) : `image` が変異する前の元の画像。
mask_image (`PIL.Image.Image`) : `Image`、または画像バッチを表すテンソル。`image`にマスクを適用します。マスクの白いピクセルは再描画され、黒いピクセルは保持されます。`mask_image`がPIL画像の場合、使用の前に単一チャネル(輝度)に変換されます。テンソルの場合は、3つのカラーチャネルではなく1つのカラーチャネル(L)を含む必要があります。したがって、期待される形状は`(B, H, W, 1)`です。
strength (`float`、*任意*、デフォルト値は 0.8) : 概念的には、参照となる`image`をどの程度変換するかを示します。0 から 1 の間の値である必要があります。`image`は開始点として使用され、`strength`が大きいほど、それに加えられるノイズが増えます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength`が 1 の場合、追加されるノイズは最大となり、デノイジングプロセスは`num_inference_steps`で指定された全イテレーション数分実行されます。したがって、値が 1 である場合、`image`は実質的に無視されます。
prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。
num_inference_steps (`int`、*optional*、デフォルト値は 100) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
timesteps (`list[int]`、*任意*) : デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、等間隔の`num_inference_steps`個のタイムステップが使用されます。降順で指定する必要があります。
guidance_scale (`float`、*任意*、デフォルト値は 4.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) : プロンプトごとに生成する画像の数。
eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。
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 が生成されます。
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 (`Callable`、*任意*) : 推論中に `callback_steps` ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback(step: int, timestep: int, latents: torch.Tensor)`。
callback_steps (`int`、*任意*、デフォルトは 1) : `callback` 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。
noise_level (`int`、*optional*、デフォルトは 0) : アップスケールされた画像に追加するノイズの量。`[0, 1000)` の範囲内である必要があります。
clean_caption (`bool`、*任意*、デフォルトは`True`) : エンベディングを作成する前にキャプションをクリーンアップするかどうか。`beautifulsoup4` と `ftfy` のインストールが必要です。依存関係がインストールされていない場合、生のプロンプトからエンベディングが作成されます。
**戻り値:** `~pipelines.stable_diffusion.IFPipelineOutput` または `tuple`
`~pipelines.stable_diffusion.IFPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the `safety_checker`.
生成用のパイプラインを呼び出したときに実行される関数。
例:
```py
>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image
>>> pipe = IFInpaintingPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "blue sunglasses"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... mask_image=mask_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... mask_image=mask_image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
```
#### encode_prompt[[diffusers.IFInpaintingSuperResolutionPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False)
```
[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py#L346)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト
do_classifier_free_guidance (`bool`、*任意*、デフォルトは`True`) : classifier free guidance を使用するかどうか
num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数
device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス
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 が生成されます。
clean_caption (bool, デフォルトは `False`) : `True` の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
# DeepFloyd IF
## 概要
DeepFloyd IF は、高いフォトリアリズムと言語理解能力を備えた、最先端のオープンソースのテキストから画像を生成するモデルです。このモデルは、凍結されたテキストエンコーダーと、3 つの直列に接続されたピクセル拡散モジュールから構成されるモジュール型アーキテクチャです。
- ステージ1: テキストプロンプトに基づいて64x64 pxの画像を生成するベースモデル、
- ステージ2: 64x64 px => 256x256 px のスーパーリゾリューションモデル、および
- ステージ3: 256x256 px => 1024x1024 px の超解像モデル
Stage 1 と Stage 2 は、T5 トランスフォーマーに基づく凍結されたテキストエンコーダーを使用してテキスト埋め込みを抽出し、それをクロスアテンションとアテンションプーリングで強化された UNet アーキテクチャに投入します。Stage 3 は [Stability AI の x4 Upscaling モデル](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)です。その結果、現在の最先端モデルを上回る、非常に効率的なモデルが得られました。COCO データセット上でゼロショット FID スコア 6.66 を達成しています。本研究は、カスケード型拡散モデルの第一段階における大規模な UNet アーキテクチャの可能性を強調し、テキストから画像への合成における有望な未来を示しています。
## 使用方法
IFを使用するには、利用条件への同意が必要です。同意するには、以下を実行してください。
1. [Hugging Face アカウント](https://huggingface.co/join)をお持ちで、ログインしていることを確認してください。
2. [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/DeepFloyd/IF-I-XL-v1.0)のモデルカードでライセンスに同意してください。ステージIのモデルカードでライセンスに同意すると、他のIFモデルについても自動的に同意が適用されます。
3. ローカルでログインしていることを確認してください。`huggingface_hub`をインストールします:
```sh
pip install huggingface_hub --upgrade
```
Pythonシェルでログイン関数を実行します:
```py
from huggingface_hub import login
login()
```
[Hugging Face Hub アクセストークン](https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens)を入力してください。
次に、`diffusers` と依存関係をインストールします。
```sh
pip install -q diffusers accelerate transformers
```
以下のセクションでは、IFの使用方法についてより詳細な例を示します。具体的には、以下の内容です。
- [テキストから画像を生成](#text-to-image-generation)
- [画像から画像への生成](#text-guided-image-to-image-generation)
- [インペインティング](#text-guided-inpainting-generation)
- [モデルの重みの再利用](#converting-between-different-pipelines)
- [速度の最適化](#optimizing-for-speed)
- [メモリ最適化](#optimizing-for-memory)
**利用可能なチェックポイント**
- *ステージ1*
- [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/DeepFloyd/IF-I-XL-v1.0)
- [DeepFloyd/IF-I-L-v1.0](https://huggingface.co/DeepFloyd/IF-I-L-v1.0)
- [DeepFloyd/IF-I-M-v1.0](https://huggingface.co/DeepFloyd/IF-I-M-v1.0)
- *ステージ2*
- [DeepFloyd/IF-II-L-v1.0](https://huggingface.co/DeepFloyd/IF-II-L-v1.0)
- [DeepFloyd/IF-II-M-v1.0](https://huggingface.co/DeepFloyd/IF-II-M-v1.0)
- *ステージ3*
- [stabilityai/stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)
**Google Colab** [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/deepfloyd_if_free_tier_google_colab.ipynb)
### テキストから画像を生成
デフォルトでは、diffusers は [モデルの CPU オフロード](../../optimization/memory#model-offloading) を利用し、VRAM 14 GB 程度の最小構成で IF パイプライン全体を実行します。
```python
from diffusers import DiffusionPipeline
from diffusers.utils import pt_to_pil, make_image_grid
import torch
# stage 1
stage_1 = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
Xet Storage Details
- Size:
- 92.6 kB
- Xet hash:
- bb5c5d82723e7073518eadff3a0ba3dd39af7a01c332416752094e65de91f32a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.