# Stable Cascade

该模型基于 [Würstchen](https://openreview.net/forum?id=gU58d5QeGv) 架构构建，与 Stable Diffusion 等其他模型的主要区别在于，它在小得多的潜在空间中运行。这为什么重要？潜在空间越小，推理速度就越 **快**，训练成本也就越 **低**。潜在空间有多小？Stable Diffusion 使用 8 的压缩因子，这意味着 1024x1024 的图像会被编码为 128x128。Stable Cascade 实现了 42 的压缩因子，这意味着可以将 1024x1024 的图像编码为 24x24，同时保持清晰的图像重建。随后，文本条件模型在这个高度压缩的潜在空间中进行训练。该架构的早期版本相比 Stable Diffusion 1.5 实现了 16 倍的成本降低。

因此，这类模型非常适合对效率要求较高的应用场景。此外，所有已知的扩展方法，例如 finetuning、LoRA、ControlNet、IP-Adapter、LCM 等，都可以使用该方法实现。

原始代码库可在 [Stability-AI/StableCascade](https://github.com/Stability-AI/StableCascade) 中找到。

## 模型概览
Stable Cascade 由三个模型组成：Stage A、Stage B 和 Stage C，它们构成一个级联流程以生成图像，因此得名“Stable Cascade”。

Stage A & B 用于压缩图像，其作用类似于 Stable Diffusion 中 VAE 的功能。不过，采用这种架构可以实现更高的图像压缩率。Stable Diffusion 模型使用的空间压缩因子为 8，即将分辨率为 1024 x 1024 的图像编码为 128 x 128；而 Stable Cascade 实现了 42 的压缩因子，能够将 1024 x 1024 的图像编码为 24 x 24，同时仍能准确解码图像。这带来了训练和推理成本大幅降低的显著优势。此外，Stage C 负责根据文本提示生成 24 x 24 的小型潜在表示。

Stage C 模型在较小的 24 x 24 潜在变量上运行，并根据文本提示对潜在变量进行去噪。该模型也是 Cascade 流水线中最大的组件，旨在与 `StableCascadePriorPipeline` 配合使用。

Stage B 和 Stage A 模型与 `StableCascadeDecoderPipeline` 配合使用，负责根据 24 x 24 的小型潜在变量生成最终图像。

> [!WARNING]
> Stable Cascade 模型对可使用的数据类型存在一些限制。`StableCascadePriorPipeline` 的官方检查点不支持 `torch.float16` 数据类型。请改用 `torch.bfloat16`。
>
> 要在 `StableCascadeDecoderPipeline` 中使用 `torch.bfloat16` 数据类型，需要安装 PyTorch 2.2.0 或更高版本。这也意味着，由于 `StableCascadeCombinedPipeline` 内部会调用 `StableCascadeDecoderPipeline`，因此使用 `StableCascadeCombinedPipeline` 配合 `torch.bfloat16` 同样需要 PyTorch 2.2.0 或更高版本。
>
> 如果无法在您的环境中安装 PyTorch 2.2.0 或更高版本，可以单独使用 `StableCascadeDecoderPipeline` 并采用 `torch.float16` 数据类型。您可以下载该 pipeline 的全精度或 `bf16` 变体权重，然后将权重转换为 `torch.float16`。

## 使用示例

```python
import torch
from diffusers import StableCascadeDecoderPipeline, StableCascadePriorPipeline

prompt = "an image of a shiba inu, donning a spacesuit and helmet"
negative_prompt = ""

prior = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", variant="bf16", dtype=torch.bfloat16)
decoder = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", variant="bf16", dtype=torch.float16)

prior.enable_model_cpu_offload()
prior_output = prior(
    prompt=prompt,
    height=1024,
    width=1024,
    negative_prompt=negative_prompt,
    guidance_scale=4.0,
    num_images_per_prompt=1,
    num_inference_steps=20
)

decoder.enable_model_cpu_offload()
decoder_output = decoder(
    image_embeddings=prior_output.image_embeddings.to(torch.float16),
    prompt=prompt,
    negative_prompt=negative_prompt,
    guidance_scale=0.0,
    output_type="pil",
    num_inference_steps=10
).images[0]
decoder_output.save("cascade.png")
```

## 使用 Stage B 和 Stage C 模型的轻量版本

```python
import torch
from diffusers import (
    StableCascadeDecoderPipeline,
    StableCascadePriorPipeline,
    StableCascadeUNet,
)

prompt = "an image of a shiba inu, donning a spacesuit and helmet"
negative_prompt = ""

prior_unet = StableCascadeUNet.from_pretrained("stabilityai/stable-cascade-prior", subfolder="prior_lite")
decoder_unet = StableCascadeUNet.from_pretrained("stabilityai/stable-cascade", subfolder="decoder_lite")

prior = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", prior=prior_unet)
decoder = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", decoder=decoder_unet)

prior.enable_model_cpu_offload()
prior_output = prior(
    prompt=prompt,
    height=1024,
    width=1024,
    negative_prompt=negative_prompt,
    guidance_scale=4.0,
    num_images_per_prompt=1,
    num_inference_steps=20
)

decoder.enable_model_cpu_offload()
decoder_output = decoder(
    image_embeddings=prior_output.image_embeddings,
    prompt=prompt,
    negative_prompt=negative_prompt,
    guidance_scale=0.0,
    output_type="pil",
    num_inference_steps=10
).images[0]
decoder_output.save("cascade.png")
```

## 使用 `from_single_file` 加载原始检查点

StableCascadeUNet 中的 `from_single_file` 方法支持加载原始格式的 checkpoint。

```python
import torch
from diffusers import (
    StableCascadeDecoderPipeline,
    StableCascadePriorPipeline,
    StableCascadeUNet,
)

prompt = "an image of a shiba inu, donning a spacesuit and helmet"
negative_prompt = ""

prior_unet = StableCascadeUNet.from_single_file(
    "https://huggingface.co/stabilityai/stable-cascade/resolve/main/stage_c_bf16.safetensors",
    dtype=torch.bfloat16
)
decoder_unet = StableCascadeUNet.from_single_file(
    "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_bf16.safetensors",
    dtype=torch.bfloat16
)

prior = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", prior=prior_unet, dtype=torch.bfloat16)
decoder = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", decoder=decoder_unet, dtype=torch.bfloat16)

prior.enable_model_cpu_offload()
prior_output = prior(
    prompt=prompt,
    height=1024,
    width=1024,
    negative_prompt=negative_prompt,
    guidance_scale=4.0,
    num_images_per_prompt=1,
    num_inference_steps=20
)

decoder.enable_model_cpu_offload()
decoder_output = decoder(
    image_embeddings=prior_output.image_embeddings,
    prompt=prompt,
    negative_prompt=negative_prompt,
    guidance_scale=0.0,
    output_type="pil",
    num_inference_steps=10
).images[0]
decoder_output.save("cascade-single-file.png")
```

## 用途

### 直接使用

该模型目前仅用于研究目的。可能的研究领域和任务包括

- 关于生成模型的研究。
- 安全部署那些有可能生成有害内容的模型。
- 探索和理解生成模型的局限性及偏差。
- 艺术作品的生成以及在设计和艺术创作过程中的应用。
- 在教育和创意工具中的应用。

以下描述了被排除的用途。

### 超出范围的使用

该模型并非以生成关于人物或事件的真实或准确内容为目标进行训练，因此使用此模型生成此类内容超出了该模型的能力范围。不得以任何违反 Stability AI [可接受使用政策](https://stability.ai/use-policy) 的方式使用该模型。

## 局限性与偏见

### 局限性
- 人脸和人物可能无法正确生成。
- 该模型的自编码部分是有损的。

## StableCascadeCombinedPipeline[[diffusers.StableCascadeCombinedPipeline]]

#### diffusers.StableCascadeCombinedPipeline[[diffusers.StableCascadeCombinedPipeline]]

```python
diffusers.StableCascadeCombinedPipeline(tokenizer: CLIPTokenizer, text_encoder: CLIPTextModelWithProjection, decoder: StableCascadeUNet, scheduler: DDPMWuerstchenScheduler, vqgan: PaellaVQModel, prior_prior: StableCascadeUNet, prior_text_encoder: CLIPTextModelWithProjection, prior_tokenizer: CLIPTokenizer, prior_scheduler: DDPMWuerstchenScheduler, prior_feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, prior_image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py#L46)

**参数：**

tokenizer (`CLIPTokenizer`)：用于文本输入的解码器分词器。

text_encoder (`CLIPTextModelWithProjection`)：用于文本输入的解码器文本编码器。

decoder (`StableCascadeUNet`)：用于解码器图像生成管线的解码器模型。

scheduler (`DDPMWuerstchenScheduler`)：用于解码器图像生成流水线的调度器。

vqgan (`PaellaVQModel`)：用于解码器图像生成流程的 VQGAN 模型。

prior_prior (`StableCascadeUNet`)：用于先验管线的先验模型。

prior_text_encoder (`CLIPTextModelWithProjection`)：用于文本输入的先前文本编码器。

prior_tokenizer (`CLIPTokenizer`)：用于文本输入的先前分词器。

prior_scheduler (`DDPMWuerstchenScheduler`)：用于先验流水线的调度器。

prior_feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor))：用于从生成的图像中提取特征，并将其作为 `image_encoder` 输入的模型。

prior_image_encoder (`CLIPVisionModelWithProjection`)：冻结的 CLIP 图像编码器（[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)）。

使用 Stable Cascade 进行文本到图像生成的组合 Pipeline。

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

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

```python
__call__(prompt: str | list[str] | None = None, images: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]] = None, height: int = 512, width: int = 512, prior_num_inference_steps: int = 60, prior_guidance_scale: float = 4.0, num_inference_steps: int = 12, decoder_guidance_scale: float = 0.0, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_pooled: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_pooled: typing.Optional[torch.Tensor] = None, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, prior_callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, prior_callback_on_step_end_tensor_inputs: list[str] = ['latents'], callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py#L159)

**参数：**

prompt (`str` 或 `list[str]`)：用于引导先验模型和解码器进行图像生成的提示词或提示词列表。

images (`torch.Tensor`、`PIL.Image.Image`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、*可选*)：用于引导先验图像生成的图像。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。当未使用引导时（即 `guidance_scale` 小于 `1` 时）将被忽略。

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

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

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

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

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

height (`int`，*可选*，默认值为 512)：生成图像的高度（以像素为单位）。

width (`int`，*可选*，默认值为 512)：生成图像的宽度（以像素为单位）。

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

prior_num_inference_steps (`int | dict[float, int]`，*可选*，默认值为 60)：先前去噪步骤的数量。更多的去噪步骤通常能带来更高质量的图像，但代价是推理速度变慢。如需更具体的时间步间隔，可以传入自定义的 `prior_timesteps`

num_inference_steps (`int`，*可选*，默认值为 12)：解码器去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。如需更具体的时间步间隔，可以传入自定义的 `timesteps`

decoder_guidance_scale (`float`，*可选*，默认值为 0.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` 紧密关联的图像，但通常以牺牲图像质量为代价。

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

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

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选值：`"pil"`（`PIL.Image.Image`）、`"np"`（`np.array`）或 `"pt"`（`torch.Tensor`）。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [ImagePipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) 而不是普通元组。

prior_callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`prior_callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。

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

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` 属性中列出的变量。

**返回值：**

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

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

示例：
```py
>>> import torch
>>> from diffusers import StableCascadeCombinedPipeline

>>> pipe = StableCascadeCombinedPipeline.from_pretrained(
...     "stabilityai/stable-cascade", variant="bf16", torch_dtype=torch.bfloat16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
>>> images = pipe(prompt=prompt)
```

#### enable_model_cpu_offload[[diffusers.StableCascadeCombinedPipeline.enable_model_cpu_offload]]

```python
enable_model_cpu_offload(gpu_id: int | None = None, device: typing.Union[torch.device, str] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py#L131)

使用 accelerate 将所有模型卸载到 CPU，在性能影响较小的情况下降低内存占用。与 `enable_sequential_cpu_offload` 相比，该方法在调用某个模型的 `forward` 方法时，将整个模型一次性移至 GPU，并且该模型会一直保留在 GPU 上，直到下一个模型开始运行。与 `enable_sequential_cpu_offload` 相比，此方法的内存节省幅度较小，但由于 `unet` 的迭代执行，其性能要出色得多。

#### enable_sequential_cpu_offload[[diffusers.StableCascadeCombinedPipeline.enable_sequential_cpu_offload]]

```python
enable_sequential_cpu_offload(gpu_id: int | None = None, device: typing.Union[torch.device, str] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py#L141)

使用 🤗 Accelerate 将所有模型（`unet`、`text_encoder`、`vae` 和 `safety checker` 的状态字典）卸载到 CPU，从而显著降低内存占用。模型会被移至 `torch.device('meta')`，仅当调用其特定子模块的 `forward` 方法时才会加载到 GPU 上。卸载操作以子模块为单位进行。与使用 `enable_model_cpu_offload` 相比，内存节省更多，但性能较低。

## StableCascadePriorPipeline[[diffusers.StableCascadePriorPipeline]]

#### diffusers.StableCascadePriorPipeline[[diffusers.StableCascadePriorPipeline]]

```python
diffusers.StableCascadePriorPipeline(tokenizer: CLIPTokenizer, text_encoder: CLIPTextModelWithProjection, prior: StableCascadeUNet, scheduler: DDPMWuerstchenScheduler, resolution_multiple: float = 42.67, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py#L80)

**参数：**

prior (`StableCascadeUNet`)：Stable Cascade 先验模型，用于从文本和/或图像嵌入中近似图像嵌入。

text_encoder (`CLIPTextModelWithProjection`)：冻结的文本编码器（[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)）。

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor))：用于从生成的图像中提取特征，并将其作为 `image_encoder` 输入的模型。

image_encoder (`CLIPVisionModelWithProjection`)：冻结的 CLIP 图像编码器（[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)）。

tokenizer (`CLIPTokenizer`)：[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

scheduler (`DDPMWuerstchenScheduler`)：一种调度器，需与 `prior` 配合使用以生成图像嵌入。

resolution_multiple ('float', *可选*，默认值为 42.67)：生成多张图片时的默认分辨率。

用于生成 Stable Cascade 图像先验的 Pipeline。

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

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

```python
__call__(prompt: str | list[str] | None = None, images: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]] = None, height: int = 1024, width: int = 1024, num_inference_steps: int = 20, timesteps: list[float] = None, guidance_scale: float = 4.0, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_pooled: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_pooled: typing.Optional[torch.Tensor] = None, image_embeds: typing.Optional[torch.Tensor] = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pt', return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py#L375)

**参数：**

prompt (`str` 或 `list[str]`)：用于引导图像生成的提示词或提示词列表。

images (`torch.Tensor`、`PIL.Image.Image`、`list[torch.Tensor]` 或 `list[PIL.Image.Image]`，*可选*)：用于条件化先验生成的参考图像。提供时，将从图像中派生图像嵌入，并与文本提示词结合。

height (`int`，*可选*，默认值为 1024)：生成图像的高度（以像素为单位）。

width (`int`，*可选*，默认为 1024)：生成图像的宽度（以像素为单位）。

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

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

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

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。当不使用引导时（即 `decoder_guidance_scale` 小于 `1` 时）将被忽略。

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

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

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

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

image_embeds (`torch.Tensor`, *可选*) : 预生成的图像嵌入。可用于轻松调整图像输入，*例如* 提示词加权。如果未提供，则会在存在 `image` 输入参数时，从该参数生成图像嵌入。

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

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

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

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选值：`"pil"`（`PIL.Image.Image`）、`"np"`（`np.array`）或 `"pt"`（`torch.Tensor`）。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [ImagePipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) 而不是普通元组。

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` 属性中列出的变量。

**返回值：**

`StableCascadePriorPipelineOutput` 或 `tuple` `StableCascadePriorPipelineOutput`（当 `return_dict` 为 True 时），否则为 `tuple`。当返回元组时，第一个元素是一个包含生成图像嵌入的列表。

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

示例：
```py
>>> import torch
>>> from diffusers import StableCascadePriorPipeline

>>> prior_pipe = StableCascadePriorPipeline.from_pretrained(
...     "stabilityai/stable-cascade-prior", torch_dtype=torch.bfloat16
... ).to("cuda")

>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
>>> prior_output = pipe(prompt)
```

## StableCascadePriorPipelineOutput[[diffusers.pipelines.stable_cascade.pipeline_stable_cascade_prior.StableCascadePriorPipelineOutput]]

#### diffusers.pipelines.stable_cascade.pipeline_stable_cascade_prior.StableCascadePriorPipelineOutput[[diffusers.pipelines.stable_cascade.pipeline_stable_cascade_prior.StableCascadePriorPipelineOutput]]

```python
diffusers.pipelines.stable_cascade.pipeline_stable_cascade_prior.StableCascadePriorPipelineOutput(image_embeddings: typing.Union[torch.Tensor, numpy.ndarray], prompt_embeds: typing.Union[torch.Tensor, numpy.ndarray], prompt_embeds_pooled: typing.Union[torch.Tensor, numpy.ndarray], negative_prompt_embeds: typing.Union[torch.Tensor, numpy.ndarray], negative_prompt_embeds_pooled: typing.Union[torch.Tensor, numpy.ndarray])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py#L60)

**参数：**

image_embeddings (`torch.Tensor` 或 `np.ndarray`)：用于文本提示的先前图像嵌入

prompt_embeds (`torch.Tensor`) : 提示词的文本嵌入。

negative_prompt_embeds (`torch.Tensor`) : 负向提示词的文本嵌入。

WuerstchenPriorPipeline 的输出类。

## StableCascadeDecoderPipeline[[diffusers.StableCascadeDecoderPipeline]]

#### diffusers.StableCascadeDecoderPipeline[[diffusers.StableCascadeDecoderPipeline]]

```python
diffusers.StableCascadeDecoderPipeline(decoder: StableCascadeUNet, tokenizer: CLIPTokenizer, text_encoder: CLIPTextModelWithProjection, scheduler: DDPMWuerstchenScheduler, vqgan: PaellaVQModel, latent_dim_scale: float = 10.67)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py#L60)

**参数：**

tokenizer (`CLIPTokenizer`)：CLIP 分词器。

text_encoder (`CLIPTextModelWithProjection`)：CLIP 文本编码器。

decoder (`StableCascadeUNet`)：Stable Cascade 解码器 unet。

vqgan (`PaellaVQModel`)：VQGAN 模型。

scheduler (`DDPMWuerstchenScheduler`)：一种调度器，需与 `prior` 配合使用以生成图像嵌入。

latent_dim_scale (float, `optional`, 默认值为 10.67) : 用于根据图像嵌入确定 VQ 潜在空间大小的乘数。如果图像嵌入的高度为 24，宽度为 24，则 VQ 潜在形状需要为 height=int(24*10.67)=256 且 width=int(24*10.67)=256，以匹配训练条件。

用于从 Stable Cascade 模型生成图像的 Pipeline。

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

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

```python
__call__(image_embeddings: typing.Union[torch.Tensor, list[torch.Tensor]], prompt: str | list[str] = None, num_inference_steps: int = 10, guidance_scale: float = 0.0, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_pooled: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_pooled: typing.Optional[torch.Tensor] = None, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py#L306)

**参数：**

image_embeddings (`torch.Tensor` 或 `list[torch.Tensor]`)：图像嵌入，可从图像中提取，也可由 Prior Model 生成。

prompt (`str` 或 `list[str]`)：用于引导图像生成的提示词或提示词列表。

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

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

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。当不使用引导时（即 `decoder_guidance_scale` 小于 `1` 时）将被忽略。

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

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

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

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

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

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

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

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选值：`"pil"`（`PIL.Image.Image`）、`"np"`（`np.array`）或 `"pt"`（`torch.Tensor`）。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [ImagePipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) 而不是普通元组。

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` 属性中列出的变量。

**返回值：**

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

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

示例：
```py
>>> import torch
>>> from diffusers import StableCascadePriorPipeline, StableCascadeDecoderPipeline

>>> prior_pipe = StableCascadePriorPipeline.from_pretrained(
...     "stabilityai/stable-cascade-prior", torch_dtype=torch.bfloat16
... ).to("cuda")
>>> gen_pipe = StableCascadeDecoderPipeline.from_pretrain(
...     "stabilityai/stable-cascade", torch_dtype=torch.float16
... ).to("cuda")

>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
>>> prior_output = pipe(prompt)
>>> images = gen_pipe(prior_output.image_embeddings, prompt=prompt)
```

