Diffusers 文档

图像变体

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

图像变体

Stable Diffusion 模型还可以从输入图像生成变体。它使用了 Justin Pinkney(来自 Lambda)的 Stable Diffusion 模型的一个微调版本。

原始代码库可在 LambdaLabsML/lambda-diffusers 找到,图像变体的其他官方检查点可在 lambdalabs/sd-image-variations-diffusers 找到。

请务必查看 Stable Diffusion 的提示部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用管道组件!

StableDiffusionImageVariationPipeline

class diffusers.StableDiffusionImageVariationPipeline

< >

( vae: AutoencoderKL image_encoder: CLIPVisionModelWithProjection unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )

参数

用于从输入图像生成图像变体的 Stable Diffusion 管道。

此模型继承自 DiffusionPipeline。有关所有管道实现的通用方法(下载、保存、在特定设备上运行等),请查看超类文档。

__call__

< >

( image: typing.Union[PIL.Image.Image, typing.List[PIL.Image.Image], torch.Tensor] height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 ) StableDiffusionPipelineOutputtuple

参数

  • image (PIL.Image.ImageList[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) — 较高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但图像质量会降低。当 guidance_scale > 1 时,启用引导比例。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个 torch.Generator,用于使生成具有确定性。
  • latents (torch.Tensor, 可选) — 预生成的从高斯分布中采样的带噪潜在变量,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则使用提供的随机generator通过采样生成一个潜在变量张量。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 在推理过程中每隔 callback_steps 步调用的函数。该函数通过以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每个步骤中调用回调。

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是布尔值列表,指示相应的生成的图像是否包含“不适合工作”(nsfw) 内容。

用于生成的管道的调用函数。

示例

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: typing.Union[int, str, NoneType] = 'auto' )

参数

  • slice_size (strint, 可选, 默认为 "auto") — 当为 "auto" 时,将注意力头部的输入减半,因此注意力将分两步计算。如果为 "max",通过每次只运行一个切片来节省最大内存。如果提供了数字,则使用 attention_head_dim // slice_size 个切片。在这种情况下,attention_head_dim 必须是 slice_size 的倍数。

启用分片注意力计算。启用此选项后,注意力模块将输入张量分割成切片,分多步计算注意力。对于多个注意力头,计算按每个头顺序执行。这有助于节省一些内存,但会略微降低速度。

⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 中的 scaled_dot_product_attention (SDPA),请不要启用注意力分片。这些注意力计算已经非常节省内存,因此您无需启用此功能。如果您将注意力分片与 SDPA 或 xFormers 一起启用,可能会导致严重的速度下降!

示例

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

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     torch_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,则注意力将一步计算完成。

enable_xformers_memory_efficient_attention

< >

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

参数

  • attention_op (Callable, 可选) — 覆盖默认的 None 操作符,用作 xFormers 的 memory_efficient_attention() 函数的 op 参数。

启用 xFormers 的内存高效注意力。启用此选项后,您将观察到 GPU 内存使用量降低,推理速度可能会加快。训练期间的速度提升不保证。

⚠️ 当内存高效注意力和切片注意力同时启用时,内存高效注意力优先。

示例

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

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_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: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )

参数

  • 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 管道的输出类。

< > 在 GitHub 上更新