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

# Cosmos

NVIDIA 的 [Cosmos 物理 AI 世界基础模型平台](https://huggingface.co/papers/2501.03575)。

*物理 AI 需要先在数字环境中进行训练。它需要一个自身的数字孪生，即策略模型，以及一个世界的数字孪生，即世界模型。在本文中，我们提出了 Cosmos 世界基础模型平台，以帮助开发者为其物理 AI 系统构建定制化的世界模型。我们将世界基础模型定位为一种通用世界模型，可以针对下游应用微调为定制化的世界模型。我们的平台涵盖视频筛选流水线、预训练的世界基础模型、预训练世界基础模型的后训练示例以及视频分词器。为了帮助物理 AI 构建者解决我们社会中最关键的问题，我们以宽松的许可证开源了我们的平台，并以开放权重形式提供模型，可通过 https://github.com/NVIDIA/Cosmos 获取。*

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

## 基本用法

```python
import torch
from diffusers import Cosmos2_5_PredictBasePipeline
from diffusers.utils import export_to_video

model_id = "nvidia/Cosmos-Predict2.5-2B"
pipe = Cosmos2_5_PredictBasePipeline.from_pretrained(
    model_id, revision="diffusers/base/post-trained", dtype=torch.bfloat16
)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "As the red light shifts to green, the red bus at the intersection begins to move forward, its headlights cutting through the falling snow. The snowy tire tracks deepen as the vehicle inches ahead, casting fresh lines onto the slushy road. Around it, streetlights glow warmer, illuminating the drifting flakes and wet reflections on the asphalt. Other cars behind start to edge forward, their beams joining the scene. The stillness of the urban street transitions into motion as the quiet snowfall is punctuated by the slow advance of traffic through the frosty city corridor."
negative_prompt = "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality."

output = pipe(
    image=None,
    video=None,
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=93,
    generator=torch.Generator().manual_seed(1),
).frames[0]
export_to_video(output, "text2world.mp4", fps=16)
```

## Cosmos2_5_TransferPipeline[[diffusers.Cosmos2_5_TransferPipeline]]

#### diffusers.Cosmos2_5_TransferPipeline[[diffusers.Cosmos2_5_TransferPipeline]]

```python
diffusers.Cosmos2_5_TransferPipeline(text_encoder: Qwen2_5_VLForConditionalGeneration, tokenizer: AutoTokenizer, transformer: CosmosTransformer3DModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler, controlnet: CosmosControlNetModel, safety_checker: typing.Optional[diffusers.pipelines.cosmos.pipeline_cosmos2_5_transfer.CosmosSafetyChecker] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_transfer.py#L152)

**参数：**

text_encoder (`Qwen2_5_VLForConditionalGeneration`)：冻结的文本编码器。Cosmos Transfer2.5 使用 [Qwen2.5 VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) 编码器。

tokenizer (`AutoTokenizer`)：与 Qwen2.5 VL 编码器关联的 Tokenizer。

transformer ([CosmosTransformer3DModel](/docs/diffusers/main/zh/api/models/cosmos_transformer3d#diffusers.CosmosTransformer3DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer。

scheduler ([UniPCMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/unipc#diffusers.UniPCMultistepScheduler))：一种调度器，需与 `transformer` 配合使用，以对编码后的图像潜变量进行去噪。

vae ([AutoencoderKLWan](/docs/diffusers/main/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

controlnet (`CosmosControlNetModel`)：用于根据控制输入对生成过程进行条件约束的 ControlNet。

Cosmos Transfer2.5 的 Pipeline，支持自回归推理。

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

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

```python
__call__(controls: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]], controls_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0, prompt: typing.Union[str, typing.List[str], NoneType] = None, negative_prompt: typing.Union[str, typing.List[str]] = 'The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality.', height: int = 704, width: typing.Optional[int] = None, num_frames: typing.Optional[int] = None, num_frames_per_chunk: int = 93, num_inference_steps: int = 36, guidance_scale: float = 3.0, num_videos_per_prompt: int = 1, generator: typing.Union[torch.Generator, typing.List[torch.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_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], max_sequence_length: int = 512, conditional_frame_timestep: float = 0.1, num_ar_conditional_frames: typing.Optional[int] = 1, num_ar_latent_conditional_frames: typing.Optional[int] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_transfer.py#L569)

**参数：**

controls (`PipelineImageInput`、`List[PipelineImageInput]`)：ControlNet 使用的控制图像或视频输入。

controls_conditioning_scale (`float` 或 `List[float]`，*可选*，默认为 `1.0`)：ControlNet 输出的缩放因子。单个浮点数会广播到所有控制块。

prompt (`str` 或 `List[str]`，*可选*)：用于引导生成的提示词或提示词列表。除非提供了 `prompt_embeds`，否则此项为必填。

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

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

width (`int`, *可选*) : 生成图像的宽度（以像素为单位）。如果未提供，将根据输入的宽高比和提供的高度来确定。

num_frames (`int`, *可选*) : 输出帧数。默认为 `None`，表示输出与输入 `controls` 相同数量的帧。

num_frames_per_chunk (`int`，*可选*，默认值为 `93`)：每个自回归块生成的帧数。当总帧数超过此值时，生成过程将使用滑动窗口方法拆分为多个块。

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

guidance_scale (`float`，默认值为 `3.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` 来启用引导尺度。

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

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

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

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

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`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`，默认为 `512`)：提示词中的最大 token 数量。如果提示词超过此长度，将被截断；如果提示词短于此长度，将被填充。

conditional_frame_timestep (`float`，*可选*，默认值为 0.1)：在去噪过程中用于条件帧的时间步值。必须位于 `[0, 1]` 区间内。

num_ar_conditional_frames (`int`，*可选*，默认为 `1`)：在自回归推理中，用于后续推理循环的条件帧数，即从第二个块开始。仅当 `num_ar_latent_conditional_frames` 为 `None` 时使用。此参数仅在执行自回归推理时使用，即当控制信号中的帧数 > num_frames_per_chunk 时。

num_ar_latent_conditional_frames (`int`, *可选*) : 在自回归推理中，用于条件化后续推理循环的潜在帧数量，即从第二个块开始。仅当 `num_ar_conditional_frames` 为 `None` 时使用。 此参数仅在执行自回归推理时使用，即当 controls 中的帧数 > num_frames_per_chunk 时。

**返回：** `~CosmosPipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `CosmosPipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

`controls` 通过 ControlNet 驱动条件输入。假定控制信号已经过预处理，例如边缘图已预先计算。

设置 `num_frames` 将限制输出的总帧数；如果未提供或将其赋值为 None（默认值），则输出帧数将与输入 `controls` 的帧数一致。

支持自回归推理，因此在每个去噪循环中，使用一个包含 `num_frames_per_chunk` 帧的滑动窗口。此外，在执行自回归推理时，前 `num_ar_latent_conditional_frames` 或 `num_ar_conditional_frames` 帧将作为条件，用于后续的各个去噪推理循环。

示例：
```python
>>> import cv2
>>> import numpy as np
>>> from PIL import Image
>>> import torch
>>> from diffusers import Cosmos2_5_TransferPipeline, AutoModel
>>> from diffusers.utils import export_to_video, load_video

>>> model_id = "nvidia/Cosmos-Transfer2.5-2B"
>>> # Load a Transfer2.5 controlnet variant (edge, depth, seg, or blur)
>>> controlnet = AutoModel.from_pretrained(
...     model_id, revision="diffusers/controlnet/general/edge", torch_dtype=torch.bfloat16
... )
>>> pipe = Cosmos2_5_TransferPipeline.from_pretrained(
...     model_id, controlnet=controlnet, revision="diffusers/general", torch_dtype=torch.bfloat16
... )
>>> pipe = pipe.to("cuda")

>>> # Video2World with edge control: Generate video guided by edge maps extracted from input video.
>>> prompt = (
...     "The video is a demonstration of robotic manipulation, likely in a laboratory or testing environment. It"
...     "features two robotic arms interacting with a piece of blue fabric. The setting is a room with a beige"
...     "couch in the background, providing a neutral backdrop for the robotic activity. The robotic arms are"
...     "positioned on either side of the fabric, which is placed on a yellow cushion. The left robotic arm is"
...     "white with a black gripper, while the right arm is black with a more complex, articulated gripper. At the"
...     "beginning, the fabric is laid out on the cushion. The left robotic arm approaches the fabric, its gripper"
...     "opening and closing as it positions itself. The right arm remains stationary initially, poised to assist."
...     "As the video progresses, the left arm grips the fabric, lifting it slightly off the cushion. The right arm"
...     "then moves in, its gripper adjusting to grasp the opposite side of the fabric. Both arms work in"
...     "coordination, lifting and holding the fabric between them. The fabric is manipulated with precision,"
...     "showcasing the dexterity and control of the robotic arms. The camera remains static throughout, focusing"
...     "on the interaction between the robotic arms and the fabric, allowing viewers to observe the detailed"
...     "movements and coordination involved in the task."
... )
>>> negative_prompt = (
...     "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, "
...     "over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, "
...     "underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky "
...     "movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, "
...     "fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. "
...     "Overall, the video is of poor quality."
... )
>>> input_video = load_video(
...     "https://github.com/nvidia-cosmos/cosmos-transfer2.5/raw/refs/heads/main/assets/robot_example/robot_input.mp4"
... )
>>> num_frames = 93

>>> # Extract edge maps from the input video using Canny edge detection
>>> edge_maps = [
...     cv2.Canny(cv2.cvtColor(np.array(frame.convert("RGB")), cv2.COLOR_RGB2BGR), 100, 200)
...     for frame in input_video[:num_frames]
... ]
>>> edge_maps = np.stack(edge_maps)[None]  # (T, H, W) -> (1, T, H, W)
>>> controls = torch.from_numpy(edge_maps).expand(3, -1, -1, -1)  # (1, T, H, W) -> (3, T, H, W)
>>> controls = [Image.fromarray(x.numpy()) for x in controls.permute(1, 2, 3, 0)]
>>> export_to_video(controls, "edge_controlled_video_edge.mp4", fps=30)

>>> # Transfer inference with controls.
>>> video = pipe(
...     controls=controls,
...     controls_conditioning_scale=1.0,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     num_frames=num_frames,
... ).frames[0]
>>> export_to_video(video, "edge_controlled_video.mp4", fps=30)
```

#### encode_prompt[[diffusers.Cosmos2_5_TransferPipeline.encode_prompt]]

```python
encode_prompt(prompt: typing.Union[str, typing.List[str]], negative_prompt: typing.Union[str, typing.List[str], NoneType] = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 512, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_transfer.py#L296)

**参数：**

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

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

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

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

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

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

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

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

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

## Cosmos2_5_PredictBasePipeline[[diffusers.Cosmos2_5_PredictBasePipeline]]

#### diffusers.Cosmos2_5_PredictBasePipeline[[diffusers.Cosmos2_5_PredictBasePipeline]]

```python
diffusers.Cosmos2_5_PredictBasePipeline(text_encoder: Qwen2_5_VLForConditionalGeneration, tokenizer: AutoTokenizer, transformer: CosmosTransformer3DModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler, safety_checker: CosmosSafetyChecker = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_predict.py#L185)

**参数：**

text_encoder (`Qwen2_5_VLForConditionalGeneration`)：冻结的文本编码器。Cosmos Predict2.5 使用 [Qwen2.5 VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) 编码器。

tokenizer (`AutoTokenizer`)：与 Qwen2.5 VL 编码器关联的 Tokenizer。

transformer ([CosmosTransformer3DModel](/docs/diffusers/main/zh/api/models/cosmos_transformer3d#diffusers.CosmosTransformer3DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer。

scheduler ([UniPCMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/unipc#diffusers.UniPCMultistepScheduler))：一种调度器，需与 `transformer` 配合使用，以对编码后的图像潜变量进行去噪。

vae ([AutoencoderKLWan](/docs/diffusers/main/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

[Cosmos Predict2.5](https://github.com/nvidia-cosmos/cosmos-predict2.5) 基础模型的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

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

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, video: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = None, prompt: str | list[str] | None = None, negative_prompt: str | list[str] | None = None, height: int = 704, width: int = 1280, num_frames: int = 93, num_inference_steps: int = 36, guidance_scale: float = 7.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.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: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int, NoneType], diffusers.callbacks.PipelineCallback | diffusers.callbacks.MultiPipelineCallbacks]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 512, conditional_frame_timestep: float = 0.0001, num_latent_conditional_frames: int = 2)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_predict.py#L544)

**参数：**

image (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`、*可选*)：用于 Image2World 条件控制的可选单张图像。当提供 `video` 时，必须为 `None`。

video (`list[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, *可选*) : 用于 Video2World 条件控制的可选输入视频。当提供 `image` 时，必须为 `None`。

prompt (`str` 或 `list[str]`，*可选*)：用于引导生成的提示词或提示词列表。除非提供了 `prompt_embeds`，否则此项为必填。

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

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

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

num_frames (`int`，默认为 `93`)：输出帧数。生成世界（视频）时使用 `93`；设置为 `1` 以返回单帧。

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

guidance_scale (`float`，默认为 `7.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` 来启用引导尺度。

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

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

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

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

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`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`，默认为 `512`)：提示词中的最大 token 数量。如果提示词超过此长度，将被截断；如果提示词短于此长度，将被填充。

num_latent_conditional_frames (`int`，默认为 `2`) : 用于 Video2World 条件生成的潜在条件帧数量。从输入视频中提取的像素帧数量按 `4 * (num_latent_conditional_frames - 1) + 1` 计算。设置为 1 可实现类似 Image2World 的行为（单帧条件生成）。

conditional_frame_timestep (`float`，*可选*，默认值为 0.0001)：在去噪过程中用于条件帧的时间步值。

**返回：** `~CosmosPipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `CosmosPipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成任务的 pipeline 调用函数。支持以下三种模式：

- **Text2World**：提供了 `image=None`、`video=None` 和 `prompt`。生成一段世界片段。
- **Image2World**：提供了 `image`，`video=None`，并提供了 `prompt`。对单帧进行条件约束。
- **Video2World**：提供 `video`，`image=None`，并提供 `prompt`。对输入片段进行条件约束。

将 `num_frames=93`（默认值）设置为生成世界视频，或将 `num_frames=1` 设置为生成单个图像帧（即上文所述的“*2Image 模式”）。

输出遵循 `output_type`（例如，`"pil"` 会为每个提示词返回一个包含 `num_frames` 张 PIL 图像的列表）。

示例：
```python
>>> import torch
>>> from diffusers import Cosmos2_5_PredictBasePipeline
>>> from diffusers.utils import export_to_video, load_image, load_video

>>> model_id = "nvidia/Cosmos-Predict2.5-2B"
>>> pipe = Cosmos2_5_PredictBasePipeline.from_pretrained(
...     model_id, revision="diffusers/base/post-trained", torch_dtype=torch.bfloat16
... )
>>> pipe = pipe.to("cuda")

>>> # Common negative prompt reused across modes.
>>> negative_prompt = (
...     "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, "
...     "over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, "
...     "underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky "
...     "movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, "
...     "fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. "
...     "Overall, the video is of poor quality."
... )

>>> # Text2World: generate a 93-frame world video from text only.
>>> prompt = (
...     "As the red light shifts to green, the red bus at the intersection begins to move forward, its headlights "
...     "cutting through the falling snow. The snowy tire tracks deepen as the vehicle inches ahead, casting fresh "
...     "lines onto the slushy road. Around it, streetlights glow warmer, illuminating the drifting flakes and wet "
...     "reflections on the asphalt. Other cars behind start to edge forward, their beams joining the scene. "
...     "The stillness of the urban street transitions into motion as the quiet snowfall is punctuated by the slow "
...     "advance of traffic through the frosty city corridor."
... )
>>> video = pipe(
...     image=None,
...     video=None,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     num_frames=93,
...     generator=torch.Generator().manual_seed(1),
... ).frames[0]
>>> export_to_video(video, "text2world.mp4", fps=16)

>>> # Image2World: condition on a single image and generate a 93-frame world video.
>>> prompt = (
...     "A high-definition video captures the precision of robotic welding in an industrial setting. "
...     "The first frame showcases a robotic arm, equipped with a welding torch, positioned over a large metal structure. "
...     "The welding process is in full swing, with bright sparks and intense light illuminating the scene, creating a vivid "
...     "display of blue and white hues. A significant amount of smoke billows around the welding area, partially obscuring "
...     "the view but emphasizing the heat and activity. The background reveals parts of the workshop environment, including a "
...     "ventilation system and various pieces of machinery, indicating a busy and functional industrial workspace. As the video "
...     "progresses, the robotic arm maintains its steady position, continuing the welding process and moving to its left. "
...     "The welding torch consistently emits sparks and light, and the smoke continues to rise, diffusing slightly as it moves upward. "
...     "The metal surface beneath the torch shows ongoing signs of heating and melting. The scene retains its industrial ambiance, with "
...     "the welding sparks and smoke dominating the visual field, underscoring the ongoing nature of the welding operation."
... )
>>> image = load_image(
...     "https://media.githubusercontent.com/media/nvidia-cosmos/cosmos-predict2.5/refs/heads/main/assets/base/robot_welding.jpg"
... )
>>> video = pipe(
...     image=image,
...     video=None,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     num_frames=93,
...     generator=torch.Generator().manual_seed(1),
... ).frames[0]
>>> export_to_video(video, "image2world.mp4", fps=16)

>>> # Video2World: condition on an input clip and predict a 93-frame world video.
>>> prompt = (
...     "The video opens with an aerial view of a large-scale sand mining construction operation, showcasing extensive piles "
...     "of brown sand meticulously arranged in parallel rows. A central water channel, fed by a water pipe, flows through the "
...     "middle of these sand heaps, creating ripples and movement as it cascades down. The surrounding area features dense green "
...     "vegetation on the left, contrasting with the sandy terrain, while a body of water is visible in the background on the right. "
...     "As the video progresses, a piece of heavy machinery, likely a bulldozer, enters the frame from the right, moving slowly along "
...     "the edge of the sand piles. This machinery's presence indicates ongoing construction work in the operation. The final frame "
...     "captures the same scene, with the water continuing its flow and the bulldozer still in motion, maintaining the dynamic yet "
...     "steady pace of the construction activity."
... )
>>> input_video = load_video(
...     "https://github.com/nvidia-cosmos/cosmos-predict2.5/raw/refs/heads/main/assets/base/sand_mining.mp4"
... )
>>> video = pipe(
...     image=None,
...     video=input_video,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     num_frames=93,
...     generator=torch.Generator().manual_seed(1),
... ).frames[0]
>>> export_to_video(video, "video2world.mp4", fps=16)

>>> # To produce an image instead of a world (video) clip, set num_frames=1 and
>>> # save the first frame: pipe(..., num_frames=1).frames[0][0].
```

#### encode_prompt[[diffusers.Cosmos2_5_PredictBasePipeline.encode_prompt]]

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_predict.py#L324)

**参数：**

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

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

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

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

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

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

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

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

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

## CosmosTextToWorldPipeline[[diffusers.CosmosTextToWorldPipeline]]

#### diffusers.CosmosTextToWorldPipeline[[diffusers.CosmosTextToWorldPipeline]]

```python
diffusers.CosmosTextToWorldPipeline(text_encoder: T5EncoderModel, tokenizer: T5Tokenizer, transformer: CosmosTransformer3DModel, vae: AutoencoderKLCosmos, scheduler: EDMEulerScheduler, safety_checker: CosmosSafetyChecker = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py#L140)

**参数：**

text_encoder (`T5EncoderModel`)：冻结的文本编码器。Cosmos 使用 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel)，具体为 [t5-11b](https://huggingface.co/google-t5/t5-11b) 变体。

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

transformer ([CosmosTransformer3DModel](/docs/diffusers/main/zh/api/models/cosmos_transformer3d#diffusers.CosmosTransformer3DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer。

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

vae ([AutoencoderKLCosmos](/docs/diffusers/main/zh/api/models/autoencoderkl_cosmos#diffusers.AutoencoderKLCosmos))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，并从潜在表示解码回视频。

使用 [Cosmos Predict1](https://github.com/nvidia-cosmos/cosmos-predict1) 进行文本到世界生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 704, width: int = 1280, num_frames: int = 121, num_inference_steps: int = 36, guidance_scale: float = 7.0, fps: int = 30, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.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: str | None = '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 = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py#L401)

**参数：**

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

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

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

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

num_frames (`int`，默认为 `121`)：生成视频的帧数。

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

guidance_scale (`float`，默认为 `7.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` 来启用引导尺度。

fps (`int`，默认为 `30`)：生成视频的每秒帧数。

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

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

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

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

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`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`，默认为 `512`)：提示词中的最大 token 数量。如果提示词超过此长度，将被截断；如果提示词短于此长度，将被填充。

**返回：** `~CosmosPipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `CosmosPipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

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

示例：
```python
>>> import torch
>>> from diffusers import CosmosTextToWorldPipeline
>>> from diffusers.utils import export_to_video

>>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Text2World"
>>> pipe = CosmosTextToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A sleek, humanoid robot stands in a vast warehouse filled with neatly stacked cardboard boxes on industrial shelves. The robot's metallic body gleams under the bright, even lighting, highlighting its futuristic design and intricate joints. A glowing blue light emanates from its chest, adding a touch of advanced technology. The background is dominated by rows of boxes, suggesting a highly organized storage system. The floor is lined with wooden pallets, enhancing the industrial setting. The camera remains static, capturing the robot's poised stance amidst the orderly environment, with a shallow depth of field that keeps the focus on the robot while subtly blurring the background for a cinematic effect."

>>> output = pipe(prompt=prompt).frames[0]
>>> export_to_video(output, "output.mp4", fps=30)
```

#### encode_prompt[[diffusers.CosmosTextToWorldPipeline.encode_prompt]]

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py#L239)

**参数：**

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

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

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

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

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

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

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

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

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

## CosmosVideoToWorldPipeline[[diffusers.CosmosVideoToWorldPipeline]]

#### diffusers.CosmosVideoToWorldPipeline[[diffusers.CosmosVideoToWorldPipeline]]

```python
diffusers.CosmosVideoToWorldPipeline(text_encoder: T5EncoderModel, tokenizer: T5Tokenizer, transformer: CosmosTransformer3DModel, vae: AutoencoderKLCosmos, scheduler: EDMEulerScheduler, safety_checker: CosmosSafetyChecker = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py#L183)

**参数：**

text_encoder (`T5EncoderModel`)：冻结的文本编码器。Cosmos 使用 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel)，具体为 [t5-11b](https://huggingface.co/google-t5/t5-11b) 变体。

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

transformer ([CosmosTransformer3DModel](/docs/diffusers/main/zh/api/models/cosmos_transformer3d#diffusers.CosmosTransformer3DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer。

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

vae ([AutoencoderKLCosmos](/docs/diffusers/main/zh/api/models/autoencoderkl_cosmos#diffusers.AutoencoderKLCosmos))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，并从潜在表示解码回视频。

使用 [Cosmos Predict-1](https://github.com/nvidia-cosmos/cosmos-predict1) 进行图像到世界和视频到世界生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

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

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, video: list = None, prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 704, width: int = 1280, num_frames: int = 121, num_inference_steps: int = 36, guidance_scale: float = 7.0, input_frames_guidance: bool = False, augment_sigma: float = 0.001, fps: int = 30, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.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: str | None = '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 = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py#L513)

**参数：**

image (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`、*可选*)：用于视频生成的条件输入图像。

video (`list[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, *可选*) : 用作视频生成条件输入的视频。

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

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

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

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

num_frames (`int`，默认为 `121`)：生成视频的帧数。

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

guidance_scale (`float`，默认为 `7.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` 来启用引导尺度。

input_frames_guidance (`bool`，*可选*，默认为 `False`)：是否对条件输入帧应用引导。

augment_sigma (`float`，*可选*，默认值为 0.001)：在去噪过程中用于增强条件潜变量的 Sigma 值。

fps (`int`，默认为 `30`)：生成视频的每秒帧数。

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

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

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

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

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`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`，默认为 `512`)：提示词中的最大 token 数量。如果提示词超过此长度，将被截断；如果提示词短于此长度，将被填充。

**返回：** `~CosmosPipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `CosmosPipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

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

示例：

图像条件：

```python
>>> import torch
>>> from diffusers import CosmosVideoToWorldPipeline
>>> from diffusers.utils import export_to_video, load_image

>>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
>>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "The video depicts a long, straight highway stretching into the distance, flanked by metal guardrails. The road is divided into multiple lanes, with a few vehicles visible in the far distance. The surrounding landscape features dry, grassy fields on one side and rolling hills on the other. The sky is mostly clear with a few scattered clouds, suggesting a bright, sunny day."
>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input.jpg"
... )

>>> video = pipe(image=image, prompt=prompt).frames[0]
>>> export_to_video(video, "output.mp4", fps=30)
```

视频条件：

```python
>>> import torch
>>> from diffusers import CosmosVideoToWorldPipeline
>>> from diffusers.utils import export_to_video, load_video

>>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
>>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.transformer = torch.compile(pipe.transformer)
>>> pipe.to("cuda")

>>> prompt = "The video depicts a winding mountain road covered in snow, with a single vehicle traveling along it. The road is flanked by steep, rocky cliffs and sparse vegetation. The landscape is characterized by rugged terrain and a river visible in the distance. The scene captures the solitude and beauty of a winter drive through a mountainous region."
>>> video = load_video(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4"
... )[
...     :21
... ]  # This example uses only the first 21 frames

>>> video = pipe(video=video, prompt=prompt).frames[0]
>>> export_to_video(video, "output.mp4", fps=30)
```

#### encode_prompt[[diffusers.CosmosVideoToWorldPipeline.encode_prompt]]

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py#L285)

**参数：**

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

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

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

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

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

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

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

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

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

## Cosmos2TextToImagePipeline[[diffusers.Cosmos2TextToImagePipeline]]

#### diffusers.Cosmos2TextToImagePipeline[[diffusers.Cosmos2TextToImagePipeline]]

```python
diffusers.Cosmos2TextToImagePipeline(text_encoder: T5EncoderModel, tokenizer: T5Tokenizer, transformer: CosmosTransformer3DModel, vae: AutoencoderKLWan, scheduler: FlowMatchEulerDiscreteScheduler, safety_checker: CosmosSafetyChecker = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py#L143)

**参数：**

text_encoder (`T5EncoderModel`)：冻结的文本编码器。Cosmos 使用 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel)，具体为 [t5-11b](https://huggingface.co/google-t5/t5-11b) 变体。

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

transformer ([CosmosTransformer3DModel](/docs/diffusers/main/zh/api/models/cosmos_transformer3d#diffusers.CosmosTransformer3DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer。

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

vae ([AutoencoderKLWan](/docs/diffusers/main/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

使用 [Cosmos Predict2](https://github.com/nvidia-cosmos/cosmos-predict2) 进行文本到图像生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 768, width: int = 1360, num_inference_steps: int = 35, guidance_scale: float = 7.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.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: str | None = '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 = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py#L417)

**参数：**

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

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

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

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

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

guidance_scale (`float`，默认为 `7.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` 来启用引导尺度。

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

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

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

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

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`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`，默认为 `512`)：提示词中的最大 token 数量。如果提示词超过此长度，将被截断；如果提示词短于此长度，将被填充。

**返回：** `~CosmosImagePipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `CosmosImagePipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

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

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

>>> # Available checkpoints: nvidia/Cosmos-Predict2-2B-Text2Image, nvidia/Cosmos-Predict2-14B-Text2Image
>>> model_id = "nvidia/Cosmos-Predict2-2B-Text2Image"
>>> pipe = Cosmos2TextToImagePipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess."
>>> negative_prompt = "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality."

>>> output = pipe(
...     prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator().manual_seed(1)
... ).images[0]
>>> output.save("output.png")
```

#### encode_prompt[[diffusers.Cosmos2TextToImagePipeline.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 = 512, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py#L254)

**参数：**

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` 输入参数生成。

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

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

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

## Cosmos2VideoToWorldPipeline[[diffusers.Cosmos2VideoToWorldPipeline]]

#### diffusers.Cosmos2VideoToWorldPipeline[[diffusers.Cosmos2VideoToWorldPipeline]]

```python
diffusers.Cosmos2VideoToWorldPipeline(text_encoder: T5EncoderModel, tokenizer: T5Tokenizer, transformer: CosmosTransformer3DModel, vae: AutoencoderKLWan, scheduler: FlowMatchEulerDiscreteScheduler, safety_checker: CosmosSafetyChecker = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py#L162)

**参数：**

text_encoder (`T5EncoderModel`)：冻结的文本编码器。Cosmos 使用 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel)，具体为 [t5-11b](https://huggingface.co/google-t5/t5-11b) 变体。

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

transformer ([CosmosTransformer3DModel](/docs/diffusers/main/zh/api/models/cosmos_transformer3d#diffusers.CosmosTransformer3DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer。

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

vae ([AutoencoderKLWan](/docs/diffusers/main/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

使用 [Cosmos Predict2](https://github.com/nvidia-cosmos/cosmos-predict2) 进行视频到世界生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

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

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, video: list = None, prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 704, width: int = 1280, num_frames: int = 93, num_inference_steps: int = 35, guidance_scale: float = 7.0, fps: int = 16, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.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: str | None = '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 = ['latents'], max_sequence_length: int = 512, sigma_conditioning: float = 0.0001)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py#L485)

**参数：**

image (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`、*可选*)：用于视频生成的条件输入图像。

video (`list[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, *可选*) : 用作视频生成条件输入的视频。

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

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

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

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

num_frames (`int`，默认为 `93`)：生成视频的帧数。

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

guidance_scale (`float`，默认为 `7.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` 来启用引导尺度。

fps (`int`，默认为 `16`)：生成视频的每秒帧数。

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

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

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

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

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`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`，默认为 `512`)：提示词中的最大 token 数量。如果提示词超过此长度，将被截断；如果提示词短于此长度，将被填充。

sigma_conditioning (`float`，默认为 `0.0001`)：用于缩放条件潜变量的 sigma 值。理想情况下，不应更改此值，或应将其设置为接近零的小值。

**返回：** `~CosmosPipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `CosmosPipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

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

示例：
```python
>>> import torch
>>> from diffusers import Cosmos2VideoToWorldPipeline
>>> from diffusers.utils import export_to_video, load_image

>>> # Available checkpoints: nvidia/Cosmos-Predict2-2B-Video2World, nvidia/Cosmos-Predict2-14B-Video2World
>>> model_id = "nvidia/Cosmos-Predict2-2B-Video2World"
>>> pipe = Cosmos2VideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess."
>>> negative_prompt = "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality."
>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yellow-scrubber.png"
... )

>>> video = pipe(
...     image=image, prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator().manual_seed(1)
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=16)
```

#### encode_prompt[[diffusers.Cosmos2VideoToWorldPipeline.encode_prompt]]

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py#L273)

**参数：**

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

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

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

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

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

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

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

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

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

## CosmosPipelineOutput[[diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput]]

#### diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput[[diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput]]

```python
diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput(frames: Tensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_output.py#L14)

**参数：**

frames (`torch.Tensor`、`np.ndarray` 或 list[list[PIL.Image.Image]]) : 视频输出列表 - 它可以是一个长度为 `batch_size,` 的嵌套列表，其中每个子列表包含长度为 `num_frames.` 的去噪 PIL 图像序列。它也可以是一个形状为 `(batch_size, num_frames, channels, height, width)` 的 NumPy 数组或 Torch 张量。

Cosmos any-to-world/video 流水线的输出类。

## CosmosImagePipelineOutput[[diffusers.pipelines.cosmos.pipeline_output.CosmosImagePipelineOutput]]

#### diffusers.pipelines.cosmos.pipeline_output.CosmosImagePipelineOutput[[diffusers.pipelines.cosmos.pipeline_output.CosmosImagePipelineOutput]]

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cosmos/pipeline_output.py#L29)

**参数：**

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

Cosmos 任意到图像（any-to-image）流水线的输出类。

