Diffusers documentation
图像变体
图像变体
Stable Diffusion 模型还可以根据输入图像生成变体。它使用了来自 Lambda 的 Justin Pinkney 微调的 Stable Diffusion 模型版本。
原始代码库可在 LambdaLabsML/lambda-diffusers 中找到,图像变体的额外官方检查点可在 lambdalabs/sd-image-variations-diffusers 中找到。
请务必查看 Stable Diffusion 的 技巧 部分,了解如何探索调度器速度与质量之间的权衡,以及如何高效地复用流水线组件!
StableDiffusionImageVariationPipeline
类 diffusers.StableDiffusionImageVariationPipeline
< source >( vae: AutoencoderKLimage_encoder: CLIPVisionModelWithProjectionunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_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__
< source >( image: typing.Union[PIL.Image.Image, list[PIL.Image.Image], torch.Tensor]height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50guidance_scale: float = 7.5num_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: 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 = 1 ) → StableDiffusionPipelineOutput or 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) — 每个提示词生成的图像数量。 - 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,可选,默认为 1) — 调用callback函数的频率。如果未指定,则会在每一步调用该回调。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 StableDiffusionPipelineOutput;否则返回一个 tuple,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,用于指示对应的生成图像是否包含“不适合工作场所”(nsfw)内容。
用于生成的 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
< source >( slice_size: str | int = 'auto' )
启用切片注意力计算。启用此选项后,注意力模块会将输入张量切分为多个切片,分步计算注意力。当存在多个注意力头时,计算将按顺序针对每个头执行。此功能可用于节省部分内存,代价是速度略有下降。
> ⚠️ 如果您已经在使用 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",
... 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 内存占用,并且在推理期间可能会获得加速。训练期间的加速并不保证。
> ⚠️ 当同时启用 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)禁用来自 xFormers 的内存高效注意力。
StableDiffusionPipelineOutput
类 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
Stable Diffusion 管道的输出类。