Diffusers 文档

GLIGEN (基于接地的语言到图像生成)

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

GLIGEN (基于接地的语言到图像生成)

GLIGEN 模型由来自威斯康星大学麦迪逊分校、哥伦比亚大学和微软的研究人员和工程师创建。StableDiffusionGLIGENPipelineStableDiffusionGLIGENTextImagePipeline 可以生成以接地输入为条件的光照片级真实感图像。除了带有 StableDiffusionGLIGENPipeline 的文本和边界框外,如果给定输入图像,StableDiffusionGLIGENTextImagePipeline 可以在边界框定义的区域中插入由文本描述的对象。否则,它将生成由标题/prompt 描述的图像,并在边界框定义的区域中插入由文本描述的对象。它在 COCO2014D 和 COCO2014CD 数据集上进行训练,该模型使用冻结的 CLIP ViT-L/14 文本编码器以接地输入为条件。

来自 论文 的摘要是

大规模文本到图像扩散模型取得了惊人的进展。然而,现状是仅使用文本输入,这可能会阻碍可控性。在这项工作中,我们提出了 GLIGEN,即基于接地的语言到图像生成,这是一种新颖的方法,它建立在现有预训练文本到图像扩散模型的功能之上并对其进行扩展,使其也能够以接地输入为条件。为了保留预训练模型的大量概念知识,我们冻结了其所有权重,并通过门控机制将接地信息注入到新的可训练层中。我们的模型实现了具有标题和边界框条件输入的开放世界接地 text2img 生成,并且接地能力可以很好地推广到新的空间配置和概念。GLIGEN 在 COCO 和 LVIS 上的零样本性能大大优于现有的监督布局到图像基线。

请务必查看 Stable Diffusion 技巧 部分,了解如何探索 scheduler 速度和质量之间的权衡,以及如何高效地重用 pipeline 组件!

如果您想为特定任务使用官方检查点之一,请浏览 gligen Hub 组织!

StableDiffusionGLIGENPipelineNikhil Gajendrakumar 贡献,StableDiffusionGLIGENTextImagePipelineNguyễn Công Tú Anh 贡献。

StableDiffusionGLIGENPipeline

class diffusers.StableDiffusionGLIGENPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记化文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜在表示进行去噪的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 调度器,与 unet 结合使用,以对编码后的图像潜在表示进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于估计生成的图像是否可能被认为是冒犯性或有害的。请参阅 模型卡片 以获取有关模型潜在危害的更多详细信息。
  • feature_extractor (CLIPImageProcessor) — CLIPImageProcessor,用于从生成的图像中提取特征;用作 safety_checker 的输入。

使用 Stable Diffusion 和 Grounded-Language-to-Image Generation (GLIGEN) 的文本到图像生成管线。

此模型继承自 DiffusionPipeline。查看超类文档,了解库为所有管线实现的通用方法(例如下载或保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 gligen_scheduled_sampling_beta: float = 0.3 gligen_phrases: typing.List[str] = None gligen_boxes: typing.List[typing.List[float]] = None gligen_inpaint_image: typing.Optional[PIL.Image.Image] = None 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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[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 生效。
  • gligen_phrases (List[str]) — 用于引导在由相应的 gligen_boxes 定义的每个区域中包含什么内容的短语。每个边界框应只有一个短语。
  • gligen_boxes (List[List[float]]) — 边界框,用于标识将要填充由相应的 gligen_phrases 描述的内容的图像矩形区域。每个矩形框定义为包含 4 个元素的 List[float][xmin, ymin, xmax, ymax],其中每个值都在 [0,1] 之间。
  • gligen_inpaint_image (PIL.Image.Image, 可选) — 如果提供了输入图像,则会使用 gligen_boxesgligen_phrases 描述的对象对其进行图像修复。否则,它将被视为对空白输入图像的生成任务。
  • gligen_scheduled_sampling_beta (float, 默认为 0.3) — 来自 GLIGEN: Open-Set Grounded Text-to-Image Generation 的计划采样因子。计划采样因子仅在推理期间针对计划采样而变化,以提高质量和可控性。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含的内容的提示词。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时(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 进行采样来生成潜在变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 negative_prompt 输入参数生成 negative_prompt_embeds
  • 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 函数的频率。如果未指定,则在每一步都调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 self.processor 中定义的 AttentionProcessor
  • guidance_rescale (float, 可选, 默认为 0.0) — 来自 Common Diffusion Noise Schedules and Sample Steps are Flawed 的 Guidance 重缩放因子。当使用零终端 SNR 时,Guidance 重缩放因子应修复过度曝光。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。

返回

StableDiffusionPipelineOutputtuple

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

调用管道进行生成的功能。

示例

>>> import torch
>>> from diffusers import StableDiffusionGLIGENPipeline
>>> from diffusers.utils import load_image

>>> # Insert objects described by text at the region defined by bounding boxes
>>> pipe = StableDiffusionGLIGENPipeline.from_pretrained(
...     "masterful/gligen-1-4-inpainting-text-box", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> input_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/gligen/livingroom_modern.png"
... )
>>> prompt = "a birthday cake"
>>> boxes = [[0.2676, 0.6088, 0.4773, 0.7183]]
>>> phrases = ["a birthday cake"]

>>> images = pipe(
...     prompt=prompt,
...     gligen_phrases=phrases,
...     gligen_inpaint_image=input_image,
...     gligen_boxes=boxes,
...     gligen_scheduled_sampling_beta=1,
...     output_type="pil",
...     num_inference_steps=50,
... ).images

>>> images[0].save("./gligen-1-4-inpainting-text-box.jpg")

>>> # Generate an image described by the prompt and
>>> # insert objects described by text at the region defined by bounding boxes
>>> pipe = StableDiffusionGLIGENPipeline.from_pretrained(
...     "masterful/gligen-1-4-generation-text-box", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a waterfall and a modern high speed train running through the tunnel in a beautiful forest with fall foliage"
>>> boxes = [[0.1387, 0.2051, 0.4277, 0.7090], [0.4980, 0.4355, 0.8516, 0.7266]]
>>> phrases = ["a waterfall", "a modern high speed train running through the tunnel"]

>>> images = pipe(
...     prompt=prompt,
...     gligen_phrases=phrases,
...     gligen_boxes=boxes,
...     gligen_scheduled_sampling_beta=1,
...     output_type="pil",
...     num_inference_steps=50,
... ).images

>>> images[0].save("./gligen-1-4-generation-text-box.jpg")

enable_vae_slicing

< >

( )

启用切片 VAE 解码。启用此选项后,VAE 将把输入张量分割成切片,以分步计算解码。这对于节省一些内存并允许更大的批量大小很有用。

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果先前启用了 enable_vae_slicing,则此方法将返回到一步计算解码。

enable_vae_tiling

< >

( )

启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成平铺块,以分步计算解码和编码。这对于节省大量内存并允许处理更大的图像非常有用。

disable_vae_tiling

< >

( )

禁用平铺 VAE 解码。如果先前启用了 enable_vae_tiling,则此方法将返回到一步计算解码。

enable_model_cpu_offload

< >

( gpu_id: typing.Optional[int] = None device: typing.Union[torch.device, str] = 'cuda' )

参数

  • gpu_id (int, 可选) — 将在推理中使用的加速器的 ID。如果未指定,则默认为 0。
  • device (torch.Devicestr, 可选, 默认为 “cuda”) — 将在推理中使用的加速器的 PyTorch 设备类型。如果未指定,则默认为 “cuda”。

使用 accelerate 将所有模型卸载到 CPU,从而降低内存使用率,而对性能的影响很小。与 enable_sequential_cpu_offload 相比,此方法在调用其 forward 方法时一次将一个完整模型移动到 GPU,并且该模型将保留在 GPU 中,直到下一个模型运行。内存节省低于 enable_sequential_cpu_offload,但由于 unet 的迭代执行,性能要好得多。

prepare_latents

< >

( batch_size num_channels_latents height width dtype device generator latents = None )

enable_fuser

< >

( enabled = True )

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器 guidance
  • negative_prompt (strList[str], 可选) — 不引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用 guidance 时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本embeddings。 可以用来轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, optional) — LoRA 缩放比例,如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层。
  • clip_skip (int, optional) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。 值为 1 表示预倒数第二层的输出将用于计算 prompt embeddings。

将 prompt 编码为文本编码器隐藏状态。

StableDiffusionGLIGENTextImagePipeline

class diffusers.StableDiffusionGLIGENTextImagePipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer processor: CLIPProcessor image_encoder: CLIPVisionModelWithProjection image_project: CLIPImageProjection unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式,以及从潜在表示形式解码图像。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • processor (CLIPProcessor) — 用于处理参考图像的 CLIPProcessor
  • image_encoder (CLIPVisionModelWithProjection) — 冻结的图像编码器 (clip-vit-large-patch14)。
  • image_project (CLIPImageProjection) — 一个 CLIPImageProjection,用于将图像 embedding 投影到短语 embedding 空间。
  • unet (UNet2DConditionModel) — 用于对编码后的图像 latent 进行去噪的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 调度器,与 unet 结合使用,以对编码后的图像 latent 进行去噪。 可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于评估生成的图像是否可能被认为具有攻击性或有害。 有关模型潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — 一个 CLIPImageProcessor,用于从生成的图像中提取特征; 用作 safety_checker 的输入。

使用 Stable Diffusion 和 Grounded-Language-to-Image Generation (GLIGEN) 的文本到图像生成管线。

此模型继承自 DiffusionPipeline。查看超类文档,了解库为所有管线实现的通用方法(例如下载或保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 gligen_scheduled_sampling_beta: float = 0.3 gligen_phrases: typing.List[str] = None gligen_images: typing.List[PIL.Image.Image] = None input_phrases_mask: typing.Union[int, typing.List[int]] = None input_images_mask: typing.Union[int, typing.List[int]] = None gligen_boxes: typing.List[typing.List[float]] = None gligen_inpaint_image: typing.Optional[PIL.Image.Image] = None 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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None gligen_normalize_constant: float = 28.7 clip_skip: int = None ) StableDiffusionPipelineOutput or tuple

参数

  • prompt (strList[str], optional) — 用于引导图像生成的 prompt 或 prompts。 如果未定义,则需要传递 prompt_embeds
  • height (int, optional, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度像素。
  • width (int, optional, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度像素。
  • num_inference_steps (int, optional, 默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。
  • guidance_scale (float, optional, 默认为 7.5) — 较高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。 当 guidance_scale > 1 时,将启用 Guidance scale。
  • gligen_phrases (List[str]) — 用于指导在由相应 gligen_boxes 定义的每个区域中包含的内容的短语。 每个边界框应只有一个短语。
  • gligen_images (List[PIL.Image.Image]) — 用于指导在由相应的 gligen_boxes 定义的每个区域中包含哪些内容的图像。每个边界框应仅包含一张图像
  • input_phrases_mask (int or List[int]) — 由相应的 input_phrases_mask 定义的预短语掩码输入
  • input_images_mask (int or List[int]) — 由相应的 input_images_mask 定义的预图像掩码输入
  • gligen_boxes (List[List[float]]) — 用于标识图像矩形区域的边界框,这些区域将填充由相应的 gligen_phrases 描述的内容。每个矩形框都定义为一个包含 4 个元素的 List[float]`:`[xmin, ymin, xmax, ymax]`,其中每个值都在 [0,1] 之间。
  • gligen_inpaint_image (PIL.Image.Image, optional) — 如果提供了输入图像,则会使用由 gligen_boxesgligen_phrases 描述的对象对其进行修复。否则,它将被视为在空白输入图像上的生成任务。
  • gligen_scheduled_sampling_beta (float, defaults to 0.3) — 来自 GLIGEN: Open-Set Grounded Text-to-Image Generation 的 Scheduled Sampling 因子。Scheduled Sampling 因子仅在推理期间针对计划采样进行更改,以提高质量和可控性。
  • negative_prompt (str or List[str], optional) — 用于指导图像生成中不包含哪些内容的提示。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时忽略(guidance_scale < 1)。
  • num_images_per_prompt (int, optional, defaults to 1) — 每个提示要生成的图像数量。
  • eta (float, optional, defaults to 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.Generator or List[torch.Generator], optional) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, optional) — 从高斯分布中采样的预生成噪声 latent,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则通过使用提供的随机 generator 进行采样来生成 latent 张量。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则文本嵌入从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则 `negative_prompt_embeds` 从 `negative_prompt` 输入参数生成。
  • output_type (str, optional, defaults to "pil") — 生成的图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • callback (Callable, optional) — 一个在推理期间每 callback_steps 步调用一次的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, optional, defaults to 1) — 调用 callback 函数的频率。如果未指定,则在每个步骤都调用回调。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则将其传递给 self.processor 中定义的 AttentionProcessor
  • gligen_normalize_constant (float, optional, defaults to 28.7) — 图像嵌入的归一化值。
  • clip_skip (int, optional) — 在计算提示嵌入时要从 CLIP 跳过的层数。值为 1 表示预倒数第二层的输出将用于计算提示嵌入。

返回

StableDiffusionPipelineOutputtuple

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

调用管道进行生成的功能。

示例

>>> import torch
>>> from diffusers import StableDiffusionGLIGENTextImagePipeline
>>> from diffusers.utils import load_image

>>> # Insert objects described by image at the region defined by bounding boxes
>>> pipe = StableDiffusionGLIGENTextImagePipeline.from_pretrained(
...     "anhnct/Gligen_Inpainting_Text_Image", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> input_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/gligen/livingroom_modern.png"
... )
>>> prompt = "a backpack"
>>> boxes = [[0.2676, 0.4088, 0.4773, 0.7183]]
>>> phrases = None
>>> gligen_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/gligen/backpack.jpeg"
... )

>>> images = pipe(
...     prompt=prompt,
...     gligen_phrases=phrases,
...     gligen_inpaint_image=input_image,
...     gligen_boxes=boxes,
...     gligen_images=[gligen_image],
...     gligen_scheduled_sampling_beta=1,
...     output_type="pil",
...     num_inference_steps=50,
... ).images

>>> images[0].save("./gligen-inpainting-text-image-box.jpg")

>>> # Generate an image described by the prompt and
>>> # insert objects described by text and image at the region defined by bounding boxes
>>> pipe = StableDiffusionGLIGENTextImagePipeline.from_pretrained(
...     "anhnct/Gligen_Text_Image", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a flower sitting on the beach"
>>> boxes = [[0.0, 0.09, 0.53, 0.76]]
>>> phrases = ["flower"]
>>> gligen_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/gligen/pexels-pixabay-60597.jpg"
... )

>>> images = pipe(
...     prompt=prompt,
...     gligen_phrases=phrases,
...     gligen_images=[gligen_image],
...     gligen_boxes=boxes,
...     gligen_scheduled_sampling_beta=1,
...     output_type="pil",
...     num_inference_steps=50,
... ).images

>>> images[0].save("./gligen-generation-text-image-box.jpg")

>>> # Generate an image described by the prompt and
>>> # transfer style described by image at the region defined by bounding boxes
>>> pipe = StableDiffusionGLIGENTextImagePipeline.from_pretrained(
...     "anhnct/Gligen_Text_Image", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a dragon flying on the sky"
>>> boxes = [[0.4, 0.2, 1.0, 0.8], [0.0, 1.0, 0.0, 1.0]]  # Set `[0.0, 1.0, 0.0, 1.0]` for the style

>>> gligen_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/landscape.png"
... )

>>> gligen_placeholder = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/landscape.png"
... )

>>> images = pipe(
...     prompt=prompt,
...     gligen_phrases=[
...         "dragon",
...         "placeholder",
...     ],  # Can use any text instead of `placeholder` token, because we will use mask here
...     gligen_images=[
...         gligen_placeholder,
...         gligen_image,
...     ],  # Can use any image in gligen_placeholder, because we will use mask here
...     input_phrases_mask=[1, 0],  # Set 0 for the placeholder token
...     input_images_mask=[0, 1],  # Set 0 for the placeholder image
...     gligen_boxes=boxes,
...     gligen_scheduled_sampling_beta=1,
...     output_type="pil",
...     num_inference_steps=50,
... ).images

>>> images[0].save("./gligen-generation-text-image-box-style-transfer.jpg")

enable_vae_slicing

< >

( )

启用切片 VAE 解码。启用此选项后,VAE 将把输入张量分割成切片,以分步计算解码。这对于节省一些内存并允许更大的批量大小很有用。

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果先前启用了 enable_vae_slicing,则此方法将返回到一步计算解码。

enable_vae_tiling

< >

( )

启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成平铺块,以分步计算解码和编码。这对于节省大量内存并允许处理更大的图像非常有用。

disable_vae_tiling

< >

( )

禁用平铺 VAE 解码。如果先前启用了 enable_vae_tiling,则此方法将返回到一步计算解码。

enable_model_cpu_offload

< >

( gpu_id: typing.Optional[int] = None device: typing.Union[torch.device, str] = 'cuda' )

参数

  • gpu_id (int, optional) — 将在推理中使用的加速器的 ID。如果未指定,则默认为 0。
  • device (torch.Devicestr, 可选, 默认为 “cuda”) — 将用于推理的加速器的 PyTorch 设备类型。如果未指定,则默认为 “cuda”。

使用 accelerate 将所有模型卸载到 CPU,从而降低内存使用率,而对性能的影响很小。与 enable_sequential_cpu_offload 相比,此方法在调用其 forward 方法时一次将一个完整模型移动到 GPU,并且该模型将保留在 GPU 中,直到下一个模型运行。内存节省低于 enable_sequential_cpu_offload,但由于 unet 的迭代执行,性能要好得多。

prepare_latents

< >

( batch_size num_channels_latents height width dtype device generator latents = None )

enable_fuser

< >

( enabled = True )

complete_mask

< >

( has_mask max_objs device )

基于每个短语和图像的输入掩码对应值 0 或 1, 掩盖与短语和图像对应的特征。

crop

< >

( im new_width new_height )

将输入图像裁剪为指定的尺寸。

draw_inpaint_mask_from_boxes

< >

( boxes size )

基于给定的框创建修复掩码。此函数使用提供的框生成修复掩码,以标记需要修复的区域。

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds 来代替。当不使用引导时忽略(即,如果 guidance_scale 小于 1,则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重。 如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 缩放比例。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算提示词嵌入。值为 1 表示预最终层的输出将用于计算提示词嵌入。

将 prompt 编码为文本编码器隐藏状态。

get_clip_feature

< >

( input normalize_constant device is_image = False )

通过使用 CLIP 预训练模型获取图像和短语嵌入。图像嵌入通过投影转换为短语嵌入空间。

get_cross_attention_kwargs_with_grounded

< >

( hidden_size gligen_phrases gligen_images gligen_boxes input_phrases_mask input_images_mask repeat_batch normalize_constant max_objs device )

准备包含有关 grounded 输入(框、掩码、图像嵌入、短语嵌入)信息的交叉注意力 kwargs。

get_cross_attention_kwargs_without_grounded

< >

( hidden_size repeat_batch max_objs device )

准备不包含 grounded 输入(框、掩码、图像嵌入、短语嵌入)信息的交叉注意力 kwargs(全部为零张量)。

target_size_center_crop

< >

( im new_hw )

裁剪图像并调整大小至目标尺寸,同时保持中心对齐。

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 上更新