Diffusers documentation

Cosmos

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Cosmos

NVIDIA 的 Cosmos 物理 AI 世界基础模型平台。

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

请务必参阅 调度器指南,了解如何探索调度器速度与质量之间的权衡,并查看 跨流水线复用组件 部分,了解如何高效地将相同组件加载到多个流水线中。

基本用法

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

class diffusers.Cosmos2_5_TransferPipeline

< >

( text_encoder: Qwen2_5_VLForConditionalGenerationtokenizer: AutoTokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: UniPCMultistepSchedulercontrolnet: CosmosControlNetModelsafety_checker: typing.Optional[diffusers.pipelines.cosmos.pipeline_cosmos2_5_transfer.CosmosSafetyChecker] = None )

参数

  • text_encoder (Qwen2_5_VLForConditionalGeneration) — 冻结的文本编码器。Cosmos Transfer2.5 使用 Qwen2.5 VL 编码器。
  • tokenizer (AutoTokenizer) — 与 Qwen2.5 VL 编码器关联的分词器。
  • transformer (CosmosTransformer3DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer。
  • scheduler (UniPCMultistepScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLWan) — 变分自编码器(VAE)模型,用于将视频编码为潜在表示,以及从潜在表示解码为视频。
  • controlnet (CosmosControlNetModel) — 用于根据控制输入对生成过程进行条件约束的 ControlNet。

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

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__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.0prompt: typing.Union[str, typing.List[str], NoneType] = Nonenegative_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 = 704width: typing.Optional[int] = Nonenum_frames: typing.Optional[int] = Nonenum_frames_per_chunk: int = 93num_inference_steps: int = 36guidance_scale: float = 3.0num_videos_per_prompt: int = 1generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: typing.Optional[str] = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']max_sequence_length: int = 512conditional_frame_timestep: float = 0.1num_ar_conditional_frames: typing.Optional[int] = 1num_ar_latent_conditional_frames: typing.Optional[int] = None ) → ~CosmosPipelineOutput or tuple

参数

  • 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, 可选) — 生成图像的宽度(以像素为单位)。如果未提供,将根据输入图像的宽高比和提供的height值来确定。
  • 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 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 List[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • 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.

    此参数仅在执行自回归推理时使用,即当 controls 中的帧数大于 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 帧将作为条件,用于后续的各个去噪推理循环。

示例:

>>> 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

< >

( prompt: typing.Union[str, typing.List[str]]negative_prompt: typing.Union[str, typing.List[str], NoneType] = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 List[str],可选) — 要编码的提示
  • negative_prompt (str 或 List[str],可选) — 用于引导图像生成的负面提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时(即 guidance_scale 小于 1 时)将被忽略。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

class diffusers.Cosmos2_5_PredictBasePipeline

< >

( text_encoder: Qwen2_5_VLForConditionalGenerationtokenizer: AutoTokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: UniPCMultistepSchedulersafety_checker: CosmosSafetyChecker = None )

参数

  • text_encoder (Qwen2_5_VLForConditionalGeneration) — 冻结的文本编码器。Cosmos Predict2.5 使用 Qwen2.5 VL 编码器。
  • tokenizer (AutoTokenizer) — 与 Qwen2.5 VL 编码器关联的分词器。
  • transformer (CosmosTransformer3DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer。
  • scheduler (UniPCMultistepScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLWan) — 变分自编码器(VAE)模型,用于将视频编码为潜在表示,以及从潜在表示解码为视频。

Cosmos Predict2.5 基础模型的 Pipeline。

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonevideo: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneprompt: str | list[str] | None = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 93num_inference_steps: int = 36guidance_scale: float = 7.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int, NoneType], diffusers.callbacks.PipelineCallback | diffusers.callbacks.MultiPipelineCallbacks]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512conditional_frame_timestep: float = 0.0001num_latent_conditional_frames: int = 2 ) → ~CosmosPipelineOutput or tuple

参数

  • 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 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • 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 图像的列表)。

示例:

>>> 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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

class diffusers.CosmosTextToWorldPipeline

< >

( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLCosmosscheduler: EDMEulerSchedulersafety_checker: CosmosSafetyChecker = None )

参数

  • text_encoder (T5EncoderModel) — 冻结的文本编码器。Cosmos 使用 T5,具体为 t5-11b 变体。
  • tokenizer (T5TokenizerFast) — T5TokenizerFast 类的分词器,属于 T5Tokenizer。
  • transformer (CosmosTransformer3DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLCosmos) — 变分自编码器(VAE)模型,用于将视频编码为潜在表示,以及从潜在表示解码为视频。

使用 Cosmos Predict1 进行文本到世界生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 121num_inference_steps: int = 36guidance_scale: float = 7.0fps: int = 30num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ~CosmosPipelineOutput or tuple

参数

  • 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 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。
  • fps (int,默认为 30) — 生成视频的每秒帧数。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • 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 的调用函数。

示例:

>>> 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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

class diffusers.CosmosVideoToWorldPipeline

< >

( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLCosmosscheduler: EDMEulerSchedulersafety_checker: CosmosSafetyChecker = None )

参数

  • text_encoder (T5EncoderModel) — 冻结的文本编码器。Cosmos 使用 T5,具体为 t5-11b 变体。
  • tokenizer (T5TokenizerFast) — T5TokenizerFast 类的分词器,属于 T5Tokenizer。
  • transformer (CosmosTransformer3DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLCosmos) — 变分自编码器(VAE)模型,用于将视频编码为潜在表示,以及从潜在表示解码为视频。

使用 Cosmos Predict-1 进行图像到世界和视频到世界生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonevideo: list = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 121num_inference_steps: int = 36guidance_scale: float = 7.0input_frames_guidance: bool = Falseaugment_sigma: float = 0.001fps: int = 30num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ~CosmosPipelineOutput or tuple

参数

  • 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 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 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。
  • 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 的调用函数。

示例:

图像条件:

>>> 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)

视频条件:

>>> 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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

class diffusers.Cosmos2TextToImagePipeline

< >

( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulersafety_checker: CosmosSafetyChecker = None )

参数

  • text_encoder (T5EncoderModel) — 冻结的文本编码器。Cosmos 使用 T5,具体为 t5-11b 变体。
  • tokenizer (T5TokenizerFast) — T5TokenizerFast 类的分词器,属于 T5Tokenizer。
  • transformer (CosmosTransformer3DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLWan) — 变分自编码器(VAE)模型,用于将视频编码为潜在表示,以及从潜在表示解码为视频。

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

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 768width: int = 1360num_inference_steps: int = 35guidance_scale: float = 7.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ~CosmosImagePipelineOutput or tuple

参数

  • 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 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • 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 的调用函数。

示例:

>>> 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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

class diffusers.Cosmos2VideoToWorldPipeline

< >

( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulersafety_checker: CosmosSafetyChecker = None )

参数

  • text_encoder (T5EncoderModel) — 冻结的文本编码器。Cosmos 使用 T5,具体为 t5-11b 变体。
  • tokenizer (T5TokenizerFast) — T5TokenizerFast 类的分词器,属于 T5Tokenizer。
  • transformer (CosmosTransformer3DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLWan) — 变分自编码器(VAE)模型,用于将视频编码为潜在表示,以及从潜在表示解码为视频。

使用 Cosmos Predict2 进行视频到世界生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonevideo: list = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 93num_inference_steps: int = 35guidance_scale: float = 7.0fps: int = 16num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512sigma_conditioning: float = 0.0001 ) → ~CosmosPipelineOutput or tuple

参数

  • 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 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。
  • fps (int,默认为 16) — 生成视频的每秒帧数。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • 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 的调用函数。

示例:

>>> 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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

class diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput

< >

( frames: Tensor )

参数

  • 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

class diffusers.pipelines.cosmos.pipeline_output.CosmosImagePipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarray )

参数

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

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

Update on GitHub