Buckets:

mishig's picture
|
download
raw
16 kB

画像のバリエーション

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

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

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

StableDiffusionImageVariationPipeline[[diffusers.StableDiffusionImageVariationPipeline]]

diffusers.StableDiffusionImageVariationPipeline[[diffusers.StableDiffusionImageVariationPipeline]]

diffusers.StableDiffusionImageVariationPipeline(vae: AutoencoderKL, image_encoder: CLIPVisionModelWithProjection, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, requires_safety_checker: bool = True)

ソース

パラメータ:

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

__call__(image: typing.Union[PIL.Image.Image, list[PIL.Image.Image], torch.Tensor], height: int | None = None, width: int | None = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1)

ソース

パラメータ:

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

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 はすべてのステップで呼び出されます。

戻り値: 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[[diffusers.StableDiffusionImageVariationPipeline.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.StableDiffusionImageVariationPipeline.disable_attention_slicing]]

disable_attention_slicing()

ソース

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

enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionImageVariationPipeline.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.StableDiffusionImageVariationPipeline.disable_xformers_memory_efficient_attention]]

disable_xformers_memory_efficient_attention()

ソース

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

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:
16 kB
·
Xet hash:
51f04a9bd11ea9ce13b03cddb0aaf3874f70d0cd6b98da74ae4c13cd423e9f1b

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