Diffusers documentation

潜在拡散

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

潜在拡散

Latent Diffusion は、Robin Rombach、Andreas Blattmann、Dominik Lorenz、Patrick Esser、Björn Ommer によって High-Resolution Image Synthesis with Latent Diffusion Models で提案されました。

論文の抄録は以下の通りです:

画像形成過程をデノイジングオートエンコーダの逐次適用に分解することで、拡散モデル(DM)は画像データおよびそれ以外のデータにおいて最先端の合成結果を実現しています。さらに、その定式化により、再学習なしで画像生成プロセスを制御するガイディング機構を適用できます。ただし、これらのモデルは通常、ピクセル空間で直接動作するため、強力なDMの最適化には数百GPU日が必要となり、逐次評価により推論コストが高くなります。限られた計算リソースでDMの訓練を可能にしつつ、その品質と柔軟性を維持するために、強力な事前学習済みオートエンコーダの潜在空間でDMを適用します。従来の研究とは異なり、このような表現上で拡散モデルを訓練することで、複雑性の低減と詳細の保持の間のほぼ最適な点に初めて到達し、視覚的忠実度を大幅に向上させます。モデルアーキテクチャにクロスアテンション層を導入することで、テキストやバウンディングボックスなどの一般的な条件付け入力に対する強力かつ柔軟なジェネレータとして拡散モデルを機能させ、畳み込み方式による高解像度合成を可能にします。私たちの潜在拡散モデル(LDM)は、画像インペインティングにおいて新たな最先端性能を達成するとともに、無条件画像生成、セマンティックシーン合成、スーパーリゾリューションを含むさまざまなタスクで非常に競争力のある性能を示し、ピクセルベースのDMと比較して計算要件を大幅に削減しています。

元のコードベースは、CompVis/latent-diffusion で確認できます。

スケジューラーのトレードオフ、すなわち速度と品質のバランスをどのように探求するかを学ぶには、ガイドを必ずご確認ください。また、同じコンポーネントを複数のパイプラインに効率的に読み込む方法については、パイプライン間でコンポーネントを再利用するセクションを参照してください。

LDMTextToImagePipeline

class diffusers.LDMTextToImagePipeline

< >

( vqvae: diffusers.models.autoencoders.vq_model.VQModel | diffusers.models.autoencoders.autoencoder_kl.AutoencoderKLbert: PreTrainedModeltokenizer: PythonBackendunet: diffusers.models.unets.unet_2d.UNet2DModel | diffusers.models.unets.unet_2d_condition.UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler )

パラメータ

  • vqvae (VQModel) — 画像を潜在表現にエンコードし、潜在表現からデコードするためのベクトル量子化(VQ)モデル。
  • bert (LDMBertModel) — BERT をベースとしたテキストエンコーダーモデル。
  • tokenizer (BertTokenizer) — テキストをトークン化するための BertTokenizer。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数からノイズを除去するためのUNet2DConditionModel。
  • scheduler (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。

潜在拡散モデルを用いたテキストから画像への生成を行うPipeline。

このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。

__call__

< >

( prompt: str | list[str]height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int | None = 50guidance_scale: float | None = 1.0eta: float | None = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = True**kwargs ) → ImagePipelineOutput or tuple

パラメータ

  • prompt (str または list[str]) — 画像生成をガイドするためのプロンプト、またはプロンプトのリスト。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像のピクセル単位の縦幅です。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • guidance_scale (float、任意、デフォルト値は 1.0) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合に guidance scale が有効になります。
  • eta (float、省略可、デフォルト値は 0.0) — DDIM論文のパラメータ eta (η) に対応します。DDIMSchedulerでのみ適用され、他のスケジューラーでは無視されます。
  • generator (torch.Generator、省略可) — 生成を決定論的にするためのtorch.Generator。
  • latents (torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き latents。画像生成のインプットとして使用します。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム generator を用いてサンプリングを行い、latents テンソルが生成されます。
  • output_type (str, 任意、デフォルトは "pil") — 生成された画像の出力形式です。"pil" (PIL.Image)、"np" (np.array)、または "pt" (torch.Tensor) から選択します。
  • return_dict (bool、省略可能、デフォルトは True) — True の場合、通常のタプルではなく ImagePipelineOutput を返します。

戻り値

ImagePipelineOutput または tuple

return_dict が True の場合、ImagePipelineOutput が返され、それ以外の場合は tuple が返されます。このとき、最初の要素は生成された画像のリストです。

生成用の pipeline への呼び出し関数。

例:

>>> from diffusers import DiffusionPipeline

>>> # load model and scheduler
>>> ldm = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")

>>> # run pipeline in inference (sample random noise and denoise)
>>> prompt = "A painting of a squirrel eating a burger"
>>> images = ldm([prompt], num_inference_steps=50, eta=0.3, guidance_scale=6).images

>>> # save images
>>> for idx, image in enumerate(images):
...     image.save(f"squirrel-{idx}.png")

LDMSuperResolutionPipeline

class diffusers.LDMSuperResolutionPipeline

< >

( vqvae: VQModelunet: UNet2DModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler | diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler | diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler )

パラメータ

潜在拡散モデルを用いた画像超解像のパイプライン。

このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。

__call__

< >

( image: typing.Union[torch.Tensor, PIL.Image.Image] = Nonebatch_size: int | None = 1num_inference_steps: int | None = 100eta: float | None = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = True ) → ImagePipelineOutput or tuple

パラメータ

  • image (torch.Tensor または PIL.Image.Image) — プロセスの開始点として使用する、Image または画像バッチを表すテンソル。
  • batch_size (int、任意、デフォルトは 1) — 生成する画像の枚数。
  • num_inference_steps (int、任意、デフォルト値は 100) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • eta (float、省略可、デフォルト値は 0.0) — DDIM論文のパラメータ eta (η) に対応します。DDIMSchedulerでのみ適用され、他のスケジューラーでは無視されます。
  • generator (torch.Generator または list[torch.Generator]、省略可) — 生成を決定論的にするための torch.Generator。
  • output_type (str, 任意、デフォルトは "pil") — 生成された画像の出力形式です。"pil" (PIL.Image)、"np" (np.array)、または "pt" (torch.Tensor) から選択します。
  • return_dict (bool、省略可能、デフォルトは True) — True の場合、通常のタプルではなく ImagePipelineOutput を返します。

戻り値

ImagePipelineOutput または tuple

return_dict が True の場合、ImagePipelineOutput が返され、それ以外の場合は tuple が返されます。このとき、最初の要素は生成された画像のリストです。

生成用の pipeline への呼び出し関数。

例:

>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import LDMSuperResolutionPipeline
>>> import torch

>>> # load model and scheduler
>>> pipeline = LDMSuperResolutionPipeline.from_pretrained("CompVis/ldm-super-resolution-4x-openimages")
>>> pipeline = pipeline.to("cuda")

>>> # let's download an  image
>>> url = (
...     "https://user-images.githubusercontent.com/38061659/199705896-b48e17b8-b231-47cd-a270-4ffa5a93fa3e.png"
... )
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))

>>> # run pipeline in inference (sample random noise and denoise)
>>> upscaled_image = pipeline(low_res_img, num_inference_steps=100, eta=1).images[0]
>>> # save image
>>> upscaled_image.save("ldm_generated_image.png")

ImagePipelineOutput

class diffusers.ImagePipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarray )

パラメータ

  • images (List[PIL.Image.Image] または np.ndarray) — batch_size 長さのデノイズ済み PIL 画像のリスト、または (batch_size, height, width, num_channels) の形状を持つ NumPy 配列です。

画像パイプライン用の出力クラス。

Update on GitHub