Diffusers documentation

超解像

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

超解像

LoRA

Stable Diffusion upscaler拡散モデルは、CompVis、Stability AI、LAIONの研究者およびエンジニアによって作成されました。入力画像の解像度を4倍に高めるために使用されます。

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

タスクに公式チェックポイントのいずれかを使用する場合は、CompVis と Stability AI の Hub 組織を探索してください!

StableDiffusionUpscalePipeline

class diffusers.StableDiffusionUpscalePipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModellow_res_scheduler: DDPMSchedulerscheduler: KarrasDiffusionSchedulerssafety_checker: typing.Any | None = Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Nonewatermarker: typing.Any | None = Nonemax_noise_level: int = 350 )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための Variational Auto-Encoder (VAE) モデル。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — テキストをトークン化するためのCLIPTokenizer。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数からノイズを除去するためのUNet2DConditionModel。
  • low_res_scheduler (SchedulerMixin) — 低解像度の条件付け画像に初期ノイズを追加するために使用されるスケジューラーです。DDPMScheduler のインスタンスである必要があります。
  • scheduler (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。

Stable Diffusion 2 を用いたテキストガイド型画像スーパーリゾリューションのパイプライン。

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

パイプラインは、以下の読み込みメソッドも継承します:

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 75guidance_scale: float = 9.0noise_level: int = 20negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: 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 = 1cross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int = None ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • 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 または、アップスケール対象の画像バッチを表すテンソル。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • noise_level (int、任意、デフォルトは 20) — アップスケールされた入力画像に追加するノイズの量です。[0, max_noise_level] の範囲内である必要があります。ここで max_noise_level はスケジューラによって定義されます。noise_level が大きいほど入力に多くのノイズが加わり、バリエーションは増加しますが、元の画像への忠実度は低下します。
  • negative_prompt (str または list[str]、任意) — 画像生成において含めるべきでない内容を指定するためのプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合(guidance_scale < 1)は無視されます。
  • 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 テンソルが生成されます。
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込みです。テキスト入力(プロンプトの重み付けなど)を簡単に調整するために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt_embeds は negative_prompt 入力引数から生成されます。
  • 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 はすべてのステップで呼び出されます。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

戻り値

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 への呼び出し関数。

例:

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

>>> # load model and scheduler
>>> model_id = "stabilityai/stable-diffusion-x4-upscaler"
>>> pipeline = StableDiffusionUpscalePipeline.from_pretrained(
...     model_id, variant="fp16", torch_dtype=torch.float16
... )
>>> pipeline = pipeline.to("cuda")

>>> # let's download an  image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))
>>> prompt = "a white cat"

>>> upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
>>> upscaled_image.save("upsampled_cat.png")

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からのメモリ効率の高いアテンションを無効にします。

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • device — (torch.device): torch デバイス
  • num_images_per_prompt (int) — 1つのプロンプトに対して生成する画像の数
  • do_classifier_free_guidance (bool) — classifier free guidance を使用するかどうか
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • lora_scale (float, 任意) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

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