Diffusers 文档
图像变体
并获取增强的文档体验
开始使用
图像变体
Stable Diffusion 模型还可以从输入图像生成变体。它使用了 Justin Pinkney(来自 Lambda)对 Stable Diffusion 模型进行微调的版本。
原始代码库可以在 LambdaLabsML/lambda-diffusers 找到,其他用于图像变体的官方检查点可以在 lambdalabs/sd-image-variations-diffusers 找到。
请务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用 pipeline 组件!
StableDiffusionImageVariationPipeline
class diffusers.StableDiffusionImageVariationPipeline
< 源代码 >( vae: AutoencoderKL image_encoder: CLIPVisionModelWithProjection unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor 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。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。
__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 ) → StableDiffusionPipelineOutput 或 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) — 每个 prompt 生成的图像数量。 - eta (
float
, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成具有确定性的torch.Generator
。 - latents (
torch.Tensor
, 可选) — 预生成的噪声潜在空间,从高斯分布中采样,用作图像生成的输入。可用于通过不同的 prompts 调整相同的生成。如果未提供,则会通过使用提供的随机generator
进行采样来生成潜在空间张量。 - output_type (
str
, 可选,默认为"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选,默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通的 tuple。 - callback (
Callable
, 可选) — 一个在推理期间每callback_steps
步调用的函数。该函数被以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选, 默认为 1) — 调用callback
函数的频率。如果未指定,则在每个步骤都调用回调。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适宜工作场所观看”(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
< source >( slice_size: typing.Union[int, str, NoneType] = 'auto' )
启用切片注意力计算。 启用此选项后,注意力模块会将输入张量分割成切片,以分几步计算注意力。 对于多个注意力头,计算将按顺序对每个头执行。 这有助于节省一些内存,以换取较小的速度下降。
⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 的 scaled_dot_product_attention
(SDPA),请不要启用注意力切片。 这些注意力计算已经非常节省内存,因此您无需启用此功能。 如果您在使用 SDPA 或 xFormers 的情况下启用注意力切片,可能会导致严重的减速!
示例
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "runwayml/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]
禁用切片注意力计算。 如果之前调用了 enable_attention_slicing
,则注意力计算将在一个步骤中完成。
enable_xformers_memory_efficient_attention
< source >( 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)
禁用来自 xFormers 的内存高效注意力。
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion 管道的输出类。