Diffusers 文档
安全稳定扩散
并获得增强的文档体验
开始使用
安全稳定扩散
安全稳定扩散在Safe Latent Diffusion: Mitigating Inappropriate Degeneration in Diffusion Models中被提出,并缓解了来自 Stable Diffusion 模型的不适当退化,因为它们是在未经过滤的网络爬取数据集上训练的。例如,Stable Diffusion 可能会意外生成裸露、暴力、描绘自残以及其他冒犯性内容。安全稳定扩散是 Stable Diffusion 的扩展,它大大减少了此类内容。
论文摘要如下
文本条件图像生成模型最近在图像质量和文本对齐方面取得了惊人的成果,因此被广泛应用于快速增长的应用领域。正如我们所展示的,由于这些模型是高度数据驱动的,依赖于从互联网上随机抓取的数十亿大小的数据集,因此它们也遭受着人类行为退化和偏差的影响。反过来,它们甚至可能会强化这些偏见。为了帮助对抗这些不良的副作用,我们提出了安全潜在扩散(SLD)。具体而言,为了衡量由于未经过滤和不平衡的训练集导致的不适当的退化,我们建立了一个新的图像生成测试平台——不适当图像提示(I2P)——其中包含专门的、真实世界的图像到文本提示,涵盖了诸如裸露和暴力等概念。正如我们详尽的实证评估所表明的那样,引入的 SLD 在扩散过程中消除了和抑制了不适当的图像部分,无需额外的训练,并且对整体图像质量或文本对齐没有不利影响。
提示
使用 StableDiffusionPipelineSafe 的 safety_concept
属性来检查和编辑当前的安全概念
>>> from diffusers import StableDiffusionPipelineSafe
>>> pipeline = StableDiffusionPipelineSafe.from_pretrained("AIML-TUDA/stable-diffusion-safe")
>>> pipeline.safety_concept
'an image showing hate, harassment, violence, suffering, humiliation, harm, suicide, sexual, nudity, bodily fluids, blood, obscene gestures, illegal activity, drug use, theft, vandalism, weapons, child abuse, brutality, cruelty'
对于每次图像生成,活动概念也包含在 StableDiffusionSafePipelineOutput
中。
有 4 种配置 (SafetyConfig.WEAK
、SafetyConfig.MEDIUM
、SafetyConfig.STRONG
和 SafetyConfig.MAX
) 可以应用
>>> from diffusers import StableDiffusionPipelineSafe
>>> from diffusers.pipelines.stable_diffusion_safe import SafetyConfig
>>> pipeline = StableDiffusionPipelineSafe.from_pretrained("AIML-TUDA/stable-diffusion-safe")
>>> prompt = "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c. leyendecker"
>>> out = pipeline(prompt=prompt, **SafetyConfig.MAX)
请务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用 pipeline 组件!
StableDiffusionPipelineSafe
class diffusers.StableDiffusionPipelineSafe
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: SafeStableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None requires_safety_checker: bool = True )
参数
- vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式,以及从潜在表示形式解码为图像。
- 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
的输入。
基于 StableDiffusionPipeline 的 pipeline,用于使用安全潜在扩散进行文本到图像的生成。
此模型继承自 DiffusionPipeline。查看超类文档以获取为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。
该 pipeline 还继承了以下加载方法
- load_ip_adapter() 用于加载 IP Adapter
__call__
< source >( prompt: typing.Union[str, typing.List[str]] height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = 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 sld_guidance_scale: typing.Optional[float] = 1000 sld_warmup_steps: typing.Optional[int] = 10 sld_threshold: typing.Optional[float] = 0.01 sld_momentum_scale: typing.Optional[float] = 0.3 sld_mom_beta: typing.Optional[float] = 0.4 ) → StableDiffusionPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
) — 用于引导图像生成的提示或提示列表。 如果未定义,则需要传递prompt_embeds
。 - 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) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但会牺牲较慢的推理速度。 - guidance_scale (
float
, 可选, 默认为 7.5) — 较高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会牺牲较低的图像质量。 当guidance_scale > 1
时,guidance scale 被启用。 - negative_prompt (
str
或List[str]
, 可选) — 用于引导图像生成中不应包含的内容的提示或提示列表。 如果未定义,则需要传递negative_prompt_embeds
代替。 当不使用 guidance 时(guidance_scale < 1
),将被忽略。 - 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
, 可选) — 从高斯分布中采样的预生成噪声潜在空间,用作图像生成的输入。 可用于使用不同的 prompt 微调相同的生成。 如果未提供,则会通过使用提供的随机generator
进行采样来生成潜在空间 tensor。 - ip_adapter_image — (
PipelineImageInput
, 可选): 可选的图像输入,用于与 IP Adapter 一起使用。 - 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
, optional, defaults to 1) —callback
函数被调用的频率。如果未指定,则在每个步骤都调用回调函数。 - sld_guidance_scale (
float
, optional, defaults to 1000) — 如果sld_guidance_scale < 1
,则禁用安全引导。 - sld_warmup_steps (
int
, optional, defaults to 10) — 安全引导的预热步骤数。 SLD 仅应用于扩散步骤数大于sld_warmup_steps
的情况。 - sld_threshold (
float
, optional, defaults to 0.01) — 分隔适当和不适当图像之间的超平面的阈值。 - sld_momentum_scale (
float
, optional, defaults to 0.3) — 在每个扩散步骤中添加到安全引导的 SLD 动量的大小。 如果设置为 0.0,则禁用动量。 动量在预热期间建立,用于小于sld_warmup_steps
的扩散步骤。 - sld_mom_beta (
float
, optional, defaults to 0.4) — 定义安全引导动量如何建立。sld_mom_beta
指示保留先前动量的多少。 动量在预热期间建立,用于小于sld_warmup_steps
的扩散步骤。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
管道的调用函数,用于生成。
示例
import torch
from diffusers import StableDiffusionPipelineSafe
from diffusers.pipelines.stable_diffusion_safe import SafetyConfig
pipeline = StableDiffusionPipelineSafe.from_pretrained(
"AIML-TUDA/stable-diffusion-safe", torch_dtype=torch.float16
).to("cuda")
prompt = "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c. leyendecker"
image = pipeline(prompt=prompt, **SafetyConfig.MEDIUM).images[0]
StableDiffusionSafePipelineOutput
class diffusers.pipelines.stable_diffusion_safe.StableDiffusionSafePipelineOutput
< source >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] unsafe_images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray, NoneType] applied_safety_concept: typing.Optional[str] )
参数
- images (
List[PIL.Image.Image]
ornp.ndarray
) — 长度为batch_size
的去噪 PIL 图像列表或形状为(batch_size, height, width, num_channels)
的 numpy 数组。 PIL 图像或 numpy 数组表示扩散管道的去噪图像。 - nsfw_content_detected (
List[bool]
) — 标志列表,指示相应的生成图像是否可能表示“不适合工作场所观看”(nsfw)内容;如果无法执行安全检查,则为None
。 - images (
List[PIL.Image.Image]
ornp.ndarray
) — 安全检查器标记的并且可能包含“不适合工作场所观看”(nsfw)内容的去噪 PIL 图像列表;如果没有执行安全检查或没有图像被标记,则为None
。 - applied_safety_concept (
str
) — 用于安全引导的安全概念;如果安全引导被禁用,则为None
Safe Stable Diffusion 管道的输出类。