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

画像のバリエーション

Stable Diffusionモデルは、入力画像からバリエーションを生成することもできます。LambdaのJustin PinkneyによるStable Diffusionモデルのファインチューニング済みバージョンを使用しています。

元のコードベースはLambdaLabsML/lambda-diffusersに、画像変異用の追加の公式チェックポイントはlambdalabs/sd-image-variations-diffusersにあります。

スケジューラーの速度と品質のトレードオフをどのように探索するか、またパイプラインのコンポーネントを効率的に再利用する方法を学ぶために、Stable DiffusionのTipsセクションをぜひご確認ください。

StableDiffusionImageVariationPipeline

class diffusers.StableDiffusionImageVariationPipeline

< >

( vae: AutoencoderKLimage_encoder: CLIPVisionModelWithProjectionunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_safety_checker: bool = True )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための Variational Auto-Encoder (VAE) モデル。
  • image_encoder (CLIPVisionModelWithProjection) — 凍結された CLIP 画像エンコーダー (clip-vit-large-patch14)。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — テキストをトークン化するためのCLIPTokenizer。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数からノイズを除去するためのUNet2DConditionModel。
  • scheduler (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。
  • safety_checker (StableDiffusionSafetyChecker) — 生成された画像が攻撃的または有害とみなされる可能性を推定する分類モジュールです。 モデルの潜在的な害に関する詳細については、モデルカードを参照してください。
  • feature_extractor (CLIPImageProcessor) — 生成された画像から特徴量を抽出するためのCLIPImageProcessor。safety_checkerの入力として使用されます。

Stable Diffusionを使用して入力画像から画像のバリエーションを生成するためのPipeline。

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

__call__

< >

( image: typing.Union[PIL.Image.Image, list[PIL.Image.Image], torch.Tensor]height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50guidance_scale: float = 7.5num_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1 ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • image (PIL.Image.Image または list[PIL.Image.Image] または torch.Tensor) — 画像生成をガイドするための画像です。テンソルを指定する場合は、CLIPImageProcessor と互換性がある必要があります。
  • 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)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。このパラメータは strength によって調整されます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • num_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。
  • eta (float、省略可、デフォルト値は 0.0) — DDIM論文のパラメータ eta (η) に対応します。DDIMSchedulerでのみ適用され、他のスケジューラーでは無視されます。
  • generator (torch.Generator または list[torch.Generator]、省略可) — 生成を決定論的にするための torch.Generator。
  • latents (torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き latents。画像生成のインプットとして使用します。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム generator を用いてサンプリングを行い、latents テンソルが生成されます。
  • output_type (str、任意、デフォルトは "pil") — 生成された画像の出力形式です。PIL.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトは True) — プレーンなタプルではなく StableDiffusionPipelineOutput を返すかどうかを指定します。
  • callback (Callable, 省略可) — 推論中に callback_steps ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int、任意、デフォルトは 1) — callback 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。

戻り値

StableDiffusionPipelineOutput または tuple

If return_dict is True, StableDiffusionPipelineOutput is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of bools indicating whether the corresponding generated image contains “not-safe-for-work” (nsfw) content.

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

例:

from diffusers import StableDiffusionImageVariationPipeline
from PIL import Image
from io import BytesIO
import requests

pipe = StableDiffusionImageVariationPipeline.from_pretrained(
    "lambdalabs/sd-image-variations-diffusers", revision="v2.0"
)
pipe = pipe.to("cuda")

url = "https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200"

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

out = pipe(image, num_images_per_prompt=3, guidance_scale=15)
out["images"][0].save("result.jpg")

enable_attention_slicing

< >

( slice_size: str | int = 'auto' )

パラメータ

  • slice_size (str または int、任意、デフォルトは "auto") — "auto" の場合、アテンションヘッドへの入力を半分にし、アテンションを2段階で計算します。 "max" の場合、一度に1つのスライスのみを実行することで、最大限のメモリを節約します。数値が指定された場合、attention_head_dim // slice_size 個のスライスを使用します。この場合、attention_head_dim は slice_size の倍数である必要があります。

スライスされたアテンション計算を有効にします。このオプションを有効にすると、アテンションモジュールは入力テンソルをスライスに分割し、複数ステップでアテンションを計算します。アテンションヘッドが1つを超える場合、各ヘッドに対して計算が逐次実行されます。これは、わずかな速度低下を代償にメモリを節約するために有用です。

> ⚠️ PyTorch > 2.0 または xFormers の scaled_dot_product_attention (SDPA) をすでに使用している場合は、attention slicing を有効にしないでください。これらの attention 計算はすでに非常にメモリ効率が高いため、この機能を有効にする必要はありません。SDPA や xFormers とともに attention slicing を有効にすると、重大なスローダウンを引き起こす可能性があります!

例:

>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]

disable_attention_slicing

< >

( )

スライスされたアテンションの計算を無効にします。enable_attention_slicingが以前に呼び出されていた場合、アテンションは1ステップで計算されます。

enable_xformers_memory_efficient_attention

< >

( attention_op: typing.Optional[typing.Callable] = None )

パラメータ

  • attention_op (Callable, 省略可) — xFormers の memory_efficient_attention() 関数の op 引数として使用する、デフォルトの None オペレータを上書きします。

xFormersからメモリ効率の高いアテンションを有効にします。このオプションを有効にすると、推論時にGPUメモリ使用量の低下と、場合によっては高速化が期待できます。ただし、学習時の高速化は保証されません。

> ⚠️ memory efficient attention と sliced attention の両方が有効な場合、memory efficient attention が > 優先されます。

例:

>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)

disable_xformers_memory_efficient_attention

< >

( )

xFormersからのメモリ効率の高いアテンションを無効にします。

StableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )

パラメータ

  • images (list[PIL.Image.Image] または np.ndarray) — batch_size 個のノイズ除去済み PIL 画像のリスト、または形状が (batch_size, height, width, num_channels) の NumPy 配列。
  • nsfw_content_detected (list[bool]) — 対応する生成画像に「不適切なコンテンツ」(nsfw) が含まれるかどうかを示すリスト。安全チェックを実行できなかった場合は None。

Stable Diffusion パイプライン用の出力クラスです。

Update on GitHub