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의 Physical AI용 Cosmos World Foundation Model Platform.

Physical AI는 먼저 디지털로 학습되어야 합니다. 이는 자기 자신의 디지털 트윈인 정책 모델과, 세계의 디지털 트윈인 세계 모델을 필요로 합니다. 본 논문에서는 개발자가 자신의 Physical AI 설정에 맞는 맞춤형 세계 모델을 구축할 수 있도록 돕는 Cosmos World Foundation Model Platform을 소개합니다. 우리는 세계 foundation model을 하위 애플리케이션을 위한 맞춤형 세계 모델로 fine-tune할 수 있는 범용 세계 모델로 포지셔닝합니다. 우리의 플랫폼은 비디오 큐레이션 파이프라인, 사전 학습된 세계 foundation model, 사전 학습된 세계 foundation model의 post-training 예시, 비디오 토크나이저를 포함합니다. Physical AI 빌더들이 우리 사회의 가장 중요한 문제들을 해결할 수 있도록, 우리는 https://github.com/NVIDIA/Cosmos를 통해 허용적인 라이선스로 플랫폼을 오픈소스화하고 모델을 오픈웨이트로 제공합니다.

Scheduler의 가이드를 확인하여 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법을 배우고, 파이프라인 간 구성 요소 재사용 섹션을 확인하여 동일한 구성 요소를 여러 파이프라인에 효율적으로 로드하는 방법을 배워보세요.

기본 사용법

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

< >

( 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와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLWan) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
  • controlnet (CosmosControlNetModel) — 컨트롤 입력으로 생성을 조건화하는 데 사용되는 ControlNet입니다.

Cosmos Transfer2.5용 파이프라인으로, 오토레거시 추론을 지원합니다.

이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

__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 출력에 적용할 스케일 팩터입니다. 단일 float 값은 모든 control block에 브로드캐스트됩니다.
  • 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) — 자동 회귀(auto-regressive) 청크당 생성되는 프레임 수입니다. 전체 프레임 수가 이 값을 초과하면 슬라이딩 윈도우(sliding-window) 방식을 사용하여 생성이 여러 청크로 나뉩니다.
  • 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, 선택 사항) — 가우시안 분포에서 샘플링하여 사전 생성된 노이즈 latents입니다. 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 활용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서를 생성합니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 생성된 이미지의 출력 형식입니다. PIL.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — CosmosPipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 선택 사항) — 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 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) — 프롬프트의 최대 토큰 수입니다. 프롬프트가 이 길이를 초과하면 잘리고, 이 길이보다 짧으면 패딩됩니다.
  • 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보다 큰 경우에만 사용됩니다. None.

    controls의 프레임 수가 num_frames_per_chunk보다 클 때, 즉 auto-regressive 추론이 수행될 때만 사용됩니다.

  • num_ar_latent_conditional_frames (int, 선택 사항) — 자기 회귀 추론에서 후속 추론 루프에 조건으로 사용할 잠재 프레임의 수, 즉 두 번째 청크부터 적용됩니다. num_ar_conditional_frames 이 값이 None인 경우에만 사용됩니다. 이는 자기 회귀 추론이 수행될 때, 즉 controls의 프레임 수가 num_frames_per_chunk보다 큰 경우에만 사용됩니다. None.

    controls의 프레임 수가 num_frames_per_chunk보다 클 때, 즉 auto-regressive 추론이 수행될 때만 사용됩니다.

반환값

~CosmosPipelineOutput 또는 tuple

return_dict가 True인 경우 CosmosPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 “not-safe-for-work”(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 bool 목록인 tuple이 반환됩니다.

controls는 ControlNet을 통해 조건화를 제어합니다. Controls는 미리 처리된 것으로 가정하며, 예를 들어 edge maps는 사전 계산됩니다.

num_frames를 설정하면 출력할 프레임의 총 수를 제한합니다. 제공되지 않거나 None(기본값)으로 지정된 경우, 출력 프레임 수는 입력 controls와 일치합니다.

Auto-regressive 추론이 지원되며, 따라서 각 denoising 루프마다 num_frames_per_chunk 프레임의 슬라이딩 윈도우가 사용됩니다. 또한, auto-regressive 추론이 수행될 때 이전 num_ar_latent_conditional_frames 또는 num_ar_conditional_frames가 이후의 denoising 추론 루프를 조건화하는 데 사용됩니다.

예:

>>> 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

Cosmos2_5_PredictBasePipeline

클래스 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와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLWan) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.

Cosmos Predict2.5 기본 모델용 파이프라인.

이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

__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, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서를 생성합니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 생성된 이미지의 출력 형식입니다. PIL.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — CosmosPipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 선택 사항) — 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 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) — 프롬프트의 최대 토큰 수입니다. 프롬프트가 이 길이를 초과하면 잘리고, 이 길이보다 짧으면 패딩됩니다.
  • num_latent_conditional_frames (int, 기본값 2) — Video2World 조건화에 사용할 잠재 조건 프레임의 수입니다. 입력 비디오에서 추출되는 픽셀 프레임의 수는 4 * (num_latent_conditional_frames - 1) + 1로 계산됩니다. Image2World와 유사한 동작(단일 프레임 조건화)을 원하면 1로 설정하십시오.
  • conditional_frame_timestep (float, 선택 사항, 기본값 0.0001) — 디노이징 과정에서 조건부 프레임에 사용되는 타임스텝 값입니다.

반환값

~CosmosPipelineOutput 또는 tuple

return_dict가 True인 경우 CosmosPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 “not-safe-for-work”(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 bool 목록인 tuple이 반환됩니다.

생성을 위한 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

CosmosTextToWorldPipeline

클래스 diffusers.CosmosTextToWorldPipeline

< >

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

매개변수

  • text_encoder (T5EncoderModel) — 동결된 텍스트 인코더입니다. Cosmos는 T5를 사용하며, 구체적으로는 t5-11b 변형을 사용합니다.
  • tokenizer (T5TokenizerFast) — T5Tokenizer 클래스의 토크나이저.
  • transformer (CosmosTransformer3DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer입니다.
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLCosmos) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.

Cosmos Predict1를 사용한 텍스트-월드 생성 파이프라인.

이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

__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, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서를 생성합니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 생성된 이미지의 출력 형식입니다. PIL.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — CosmosPipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 선택 사항) — 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 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) — 프롬프트의 최대 토큰 수입니다. 프롬프트가 이 길이를 초과하면 잘리고, 이 길이보다 짧으면 패딩됩니다.

반환값

~CosmosPipelineOutput 또는 tuple

return_dict가 True인 경우 CosmosPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 “not-safe-for-work”(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 bool 목록인 tuple이 반환됩니다.

생성을 위한 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

CosmosVideoToWorldPipeline

클래스 diffusers.CosmosVideoToWorldPipeline

< >

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

매개변수

  • text_encoder (T5EncoderModel) — 동결된 텍스트 인코더입니다. Cosmos는 T5를 사용하며, 구체적으로는 t5-11b 변형을 사용합니다.
  • tokenizer (T5TokenizerFast) — T5Tokenizer 클래스의 토크나이저.
  • transformer (CosmosTransformer3DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer입니다.
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLCosmos) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.

Cosmos Predict-1를 사용한 이미지-월드 및 비디오-월드 생성을 위한 파이프라인

이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

__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) — 디노이징 과정에서 조건부 레이턴트를 증강하는 데 사용되는 시그마 값입니다.
  • fps (int, 기본값 30) — 생성된 비디오의 초당 프레임 수입니다.
  • num_videos_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch.Generator.
  • latents (torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서를 생성합니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 생성된 이미지의 출력 형식입니다. PIL.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — CosmosPipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 선택 사항) — 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 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) — 프롬프트의 최대 토큰 수입니다. 프롬프트가 이 길이를 초과하면 잘리고, 이 길이보다 짧으면 패딩됩니다.

반환값

~CosmosPipelineOutput 또는 tuple

return_dict가 True인 경우 CosmosPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 “not-safe-for-work”(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 bool 목록인 tuple이 반환됩니다.

생성을 위한 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

Cosmos2TextToImagePipeline

클래스 diffusers.Cosmos2TextToImagePipeline

< >

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

매개변수

  • text_encoder (T5EncoderModel) — 동결된 텍스트 인코더입니다. Cosmos는 T5를 사용하며, 구체적으로는 t5-11b 변형을 사용합니다.
  • tokenizer (T5TokenizerFast) — T5Tokenizer 클래스의 토크나이저.
  • transformer (CosmosTransformer3DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer입니다.
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLWan) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.

Cosmos Predict2를 사용한 텍스트-이미지 생성 파이프라인.

이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

__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, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서를 생성합니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 생성된 이미지의 출력 형식입니다. PIL.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — CosmosImagePipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 선택 사항) — 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 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) — 프롬프트의 최대 토큰 수입니다. 프롬프트가 이 길이를 초과하면 잘리고, 이 길이보다 짧으면 패딩됩니다.

반환값

~CosmosImagePipelineOutput 또는 tuple

return_dict가 True인 경우 CosmosImagePipelineOutput가 반환되고, 그렇지 않으면 tuple이 반환됩니다. 이 튜플의 첫 번째 요소는 생성된 이미지 목록이고, 두 번째 요소는 각 생성된 이미지에 “not-safe-for-work”(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 bool 목록입니다.

생성을 위한 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

Cosmos2VideoToWorldPipeline

클래스 diffusers.Cosmos2VideoToWorldPipeline

< >

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

매개변수

  • text_encoder (T5EncoderModel) — 동결된 텍스트 인코더입니다. Cosmos는 T5를 사용하며, 구체적으로는 t5-11b 변형을 사용합니다.
  • tokenizer (T5TokenizerFast) — T5Tokenizer 클래스의 토크나이저.
  • transformer (CosmosTransformer3DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer입니다.
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLWan) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.

Cosmos Predict2를 사용한 비디오-월드 생성을 위한 Pipeline

이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

__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, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서를 생성합니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 생성된 이미지의 출력 형식입니다. PIL.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — CosmosPipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 선택 사항) — 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 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) — 프롬프트의 최대 토큰 수입니다. 프롬프트가 이 길이를 초과하면 잘리고, 이 길이보다 짧으면 패딩됩니다.
  • sigma_conditioning (float, 기본값 0.0001) — 조건부 잠재 변수를 스케일링하는 데 사용되는 시그마 값입니다. 이상적으로는 변경하지 않거나, 0에 가까운 작은 값으로 설정해야 합니다.

반환값

~CosmosPipelineOutput 또는 tuple

return_dict가 True인 경우 CosmosPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 “not-safe-for-work”(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 bool 목록인 tuple이 반환됩니다.

생성을 위한 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

CosmosPipelineOutput

클래스 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/비디오 파이프라인의 출력 클래스입니다.

CosmosImagePipelineOutput

클래스 diffusers.pipelines.cosmos.pipeline_output.CosmosImagePipelineOutput

< >

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

매개변수

  • images (list[PIL.Image.Image] 또는 np.ndarray) — batch_size 길이의 denoised PIL 이미지 목록 또는 (batch_size, height, width, num_channels) 형태의 numpy 배열. PIL 이미지 또는 numpy 배열은 diffusion 파이프라인의 denoised 이미지를 나타냅니다.

Cosmos any-to-image 파이프라인의 출력 클래스입니다.

Update on GitHub