Buckets:

mishig's picture
|
download
raw
21 kB

超解像

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

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

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

StableDiffusionUpscalePipeline[[diffusers.StableDiffusionUpscalePipeline]]

diffusers.StableDiffusionUpscalePipeline[[diffusers.StableDiffusionUpscalePipeline]]

diffusers.StableDiffusionUpscalePipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, low_res_scheduler: DDPMScheduler, scheduler: KarrasDiffusionSchedulers, safety_checker: typing.Any | None = None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, watermarker: typing.Any | None = None, max_noise_level: int = 350)

ソース

パラメータ:

vae (AutoencoderKL) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(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[[diffusers.StableDiffusionUpscalePipeline.call]]

__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, num_inference_steps: int = 75, guidance_scale: float = 9.0, noise_level: int = 20, 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, latents: typing.Optional[torch.Tensor] = 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, clip_skip: int = None)

ソース

パラメータ:

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, optional, デフォルトは 20) : アップスケールされた入力画像に追加するノイズの量。max_noise_level はスケジューラによって定義されるため、[0, 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, 任意) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、ラテンツのテンソルが生成されます。

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、optional、デフォルトは 1) : callback 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。

cross_attention_kwargs (dict, 任意) : 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。

clip_skip (int, optional) : プロンプト埋め込みを計算する際に、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[[diffusers.StableDiffusionUpscalePipeline.enable_attention_slicing]]

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つを超える場合、各ヘッドに対して計算が順次実行されます。これは、わずかな速度低下を代償にメモリを節約するために有用です。

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

例:

>>> 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[[diffusers.StableDiffusionUpscalePipeline.disable_attention_slicing]]

disable_attention_slicing()

ソース

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

enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionUpscalePipeline.enable_xformers_memory_efficient_attention]]

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

ソース

パラメータ:

attention_op (Callable、任意) : xFormers の memory_efficient_attention() 関数の op 引数として使用するために、デフォルトの None オペレーターをオーバーライドします。

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

> ⚠️ メモリ効率の良いアテンションとスライスされたアテンションの両方が有効な場合、メモリ効率 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[[diffusers.StableDiffusionUpscalePipeline.disable_xformers_memory_efficient_attention]]

disable_xformers_memory_efficient_attention()

ソース

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

encode_prompt[[diffusers.StableDiffusionUpscalePipeline.encode_prompt]]

encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)

ソース

パラメータ:

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

device : (torch.device): torch デバイス

num_images_per_prompt (int) : プロンプトごとに生成すべき画像の数

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, optional) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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

StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_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]) : 対応する生成画像に「not-safe-for-work」(nsfw)コンテンツが含まれるかどうかを示すリスト。安全性チェックを実行できなかった場合はNone。

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

Xet Storage Details

Size:
21 kB
·
Xet hash:
974a04bd42c7bdc792780272f4d608cd190c8db6df32960ae1bcbe0520de754f

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.