#
# 根据 Apache 许可证 2.0 版本（“许可证”）授权
# 您只能在遵守许可证的情况下使用本文件。
# 您可以在以下位置获取许可证副本
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或双方书面同意，软件
# 根据许可证分发，本软件按“原样”
# 不附带任何明示或暗示的保证或条件。
# 请参阅许可证中关于权限的具体语言
# 许可证下的限制。
-->

# CogView3Plus

来自清华大学 & 智谱AI 的 [CogView3: Finer and Faster Text-to-Image Generation via Relay Diffusion](https://huggingface.co/papers/2403.05121)，作者为 Wendi Zheng, Jiayan Teng, Zhuoyi Yang, Weihan Wang, Jidong Chen, Xiaotao Gu, Yuxiao Dong, Ming Ding, Jie Tang。

该论文的摘要如下：

*文本到图像生成系统的最新进展在很大程度上得益于扩散模型。然而，单阶段文本到图像扩散模型在计算效率和图像细节优化方面仍面临挑战。为解决这一问题，我们提出了 CogView3，这是一种创新的级联框架，旨在提升文本到图像扩散模型的性能。CogView3 是首个在文本到图像生成领域实现接力扩散的模型，其工作流程为先生成低分辨率图像，随后应用基于接力的超分辨率技术。该方法不仅产生了具有竞争力的文本到图像输出，还大幅降低了训练和推理成本。实验结果表明，在人工评估中，CogView3 的性能比当前最先进的开源文本到图像扩散模型 SDXL 高出 77.0%，同时所需的推理时间仅为 SDXL 的约 1/2。CogView3 的蒸馏变体在性能相当的情况下，推理时间仅为 SDXL 的 1/10。*

> [!TIP]
> 请务必参阅 [调度器指南](../../using-diffusers/schedulers)，了解如何探索调度器速度与质量之间的权衡，并查看 [跨流水线复用组件](../../using-diffusers/loading#reusing-models-in-multiple-pipelines) 部分，了解如何高效地将相同组件加载到多个流水线中。

此流水线由 [zRzRzRzRzRzRzR](https://github.com/zRzRzRzRzRzRzR) 贡献。原始代码库可在 [此处](https://huggingface.co/THUDM) 找到。原始权重可在 [hf.co/THUDM](https://huggingface.co/THUDM) 下找到。

## CogView3PlusPipeline[[diffusers.CogView3PlusPipeline]]

#### diffusers.CogView3PlusPipeline[[diffusers.CogView3PlusPipeline]]

```python
diffusers.CogView3PlusPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, vae: AutoencoderKL, transformer: CogView3PlusTransformer2DModel, scheduler: diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler | diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/cogview3/pipeline_cogview3plus.py#L118)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder (`T5EncoderModel`)：冻结的文本编码器。CogView3Plus 使用 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel)，具体为 [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) 变体。

tokenizer (`T5Tokenizer`)：[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer) 类的分词器。

transformer ([CogView3PlusTransformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/cogview3plus_transformer2d#diffusers.CogView3PlusTransformer2DModel))：一个以文本为条件的 `CogView3PlusTransformer2DModel`，用于对编码后的图像潜在表示进行去噪。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

使用 CogView3Plus 进行文本到图像生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

#### __调用__[[diffusers.CogView3PlusPipeline.__call__]]

```python
__call__(prompt: str | list[str] | None = None, negative_prompt: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] | None = None, guidance_scale: float = 5.0, num_images_per_prompt: int = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, original_size: tuple[int, int] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), output_type: str = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 224)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/cogview3/pipeline_cogview3plus.py#L407)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

height (`int`，*可选*，默认为 self.transformer.config.sample_size * self.vae_scale_factor)：生成图像的高度（以像素为单位）。如果未提供，则设置为 1024。

width (`int`，*可选*，默认为 self.transformer.config.sample_size * self.vae_scale_factor)：生成图像的宽度（以像素为单位）。如果未提供，则设置为 1024。

num_inference_steps (`int`，*可选*，默认值为 `50`)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

guidance_scale (`float`，*可选*，默认值为 `5.0`)：如 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

num_images_per_prompt (`int`，*可选*，默认为 `1`)：每个提示词生成的图像数量。

eta (`float`，*可选*，默认值为 0.0)：对应 [DDIM](https://arxiv.org/abs/2010.02502) 论文中的参数 eta (η)。仅适用于 [DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，在其他调度器中会被忽略。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.FloatTensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.FloatTensor`，*可选*)：预生成的文本嵌入。可用于轻松调整文本输入，*例如*提示词加权。如果未提供，则将从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如*提示词权重。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

original_size (`tuple[int]`，*可选*，默认为 (1024, 1024))：如果 `original_size` 与 `target_size` 不同，图像将看起来像是被下采样或上采样了。如果未指定，`original_size` 默认为 `(height, width)`。这是 SDXL 微条件的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。

crops_coords_top_left (`tuple[int]`，*可选*，默认值为 (0, 0))：`crops_coords_top_left` 可用于生成一张看似从 `crops_coords_top_left` 位置向下裁剪的图像。通常将 `crops_coords_top_left` 设置为 (0, 0) 即可获得构图良好、居中效果佳的图像。这是 SDXL 微条件的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` 而不是普通元组。

callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，默认为 `224`)：编码提示词的最大序列长度。可以设置为其他值，但可能会导致效果变差。

**返回：** [CogView3PipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/cogview3#diffusers.pipelines.cogview3.pipeline_output.CogView3PipelineOutput) 或 `tuple`

如果 `return_dict` 为 True，则返回 [CogView3PipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/cogview3#diffusers.pipelines.cogview3.pipeline_output.CogView3PipelineOutput)，否则返回 `tuple`。当返回元组时，第一个元素是一个包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```python
>>> import torch
>>> from diffusers import CogView3PlusPipeline

>>> pipe = CogView3PlusPipeline.from_pretrained("THUDM/CogView3-Plus-3B", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt).images[0]
>>> image.save("output.png")
```

#### encode_prompt[[diffusers.CogView3PlusPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 224, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/cogview3/pipeline_cogview3plus.py#L210)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的图像数量。用于放置最终嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

max_sequence_length (`int`，默认为 `224`)：编码提示词的最大序列长度。可以设置为其他值，但可能会导致效果变差。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

## CogView3PipelineOutput[[diffusers.pipelines.cogview3.pipeline_output.CogView3PipelineOutput]]

#### diffusers.pipelines.cogview3.pipeline_output.CogView3PipelineOutput[[diffusers.pipelines.cogview3.pipeline_output.CogView3PipelineOutput]]

```python
diffusers.pipelines.cogview3.pipeline_output.CogView3PipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/cogview3/pipeline_output.py#L10)

**参数：**

images (`list[PIL.Image.Image]` 或 `np.ndarray`)：长度为 `batch_size` 的去噪 PIL 图像列表，或形状为 `(batch_size, height, width, num_channels)` 的 numpy 数组。PIL 图像或 numpy 数组表示扩散流水线生成的去噪图像。

CogView3 管道的输出类。

