CogVideoX (original) (raw)

LoRA

CogVideoX is a large diffusion transformer model - available in 2B and 5B parameters - designed to generate longer and more consistent videos from text. This model uses a 3D causal variational autoencoder to more efficiently process video data by reducing sequence length (and associated training compute) and preventing flickering in generated videos. An “expert” transformer with adaptive LayerNorm improves alignment between text and video, and 3D full attention helps accurately capture motion and time in generated videos.

You can find all the original CogVideoX checkpoints under the CogVideoX collection.

Click on the CogVideoX models in the right sidebar for more examples of other video generation tasks.

The example below demonstrates how to generate a video optimized for memory or inference speed.

Refer to the Reduce memory usage guide for more details about the various memory saving techniques.

The quantized CogVideoX 5B model below requires ~16GB of VRAM.

import torch from diffusers import CogVideoXPipeline, AutoModel from diffusers.quantizers import PipelineQuantizationConfig from diffusers.hooks import apply_group_offloading from diffusers.utils import export_to_video

pipeline_quant_config = PipelineQuantizationConfig( quant_backend="torchao", quant_kwargs={"quant_type": "int8wo"}, components_to_quantize=["transformer"] )

transformer = AutoModel.from_pretrained( "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16 ) transformer.enable_layerwise_casting( storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16 )

pipeline = CogVideoXPipeline.from_pretrained( "THUDM/CogVideoX-5b", transformer=transformer, quantization_config=pipeline_quant_config, torch_dtype=torch.bfloat16 ) pipeline.to("cuda")

pipeline.enable_model_cpu_offload()

prompt = """ A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting. """

video = pipeline( prompt=prompt, guidance_scale=6, num_inference_steps=50 ).frames[0] export_to_video(video, "output.mp4", fps=8)

Notes

CogVideoXPipeline

class diffusers.CogVideoXPipeline

< source >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )

Parameters

Pipeline for text-to-video generation using CogVideoX.

This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)

__call__

< source >

( prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_frames: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None guidance_scale: float = 6 use_dynamic_cfg: bool = False num_videos_per_prompt: int = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

Parameters

CogVideoXPipelineOutput if return_dict is True, otherwise atuple. When returning a tuple, the first element is a list with the generated images.

Function invoked when calling the pipeline for generation.

Examples:

import torch from diffusers import CogVideoXPipeline from diffusers.utils import export_to_video

pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16).to("cuda") prompt = ( ... "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. " ... "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other " ... "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, " ... "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. " ... "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical " ... "atmosphere of this unique musical performance." ... ) video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0] export_to_video(video, "output.mp4", fps=8)

encode_prompt

< source >

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

Parameters

Encodes the prompt into text encoder hidden states.

Enables fused QKV projections.

Disable QKV projection fusion if enabled.

CogVideoXImageToVideoPipeline

class diffusers.CogVideoXImageToVideoPipeline

< source >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )

Parameters

Pipeline for image-to-video generation using CogVideoX.

This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)

__call__

< source >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_frames: int = 49 num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None guidance_scale: float = 6 use_dynamic_cfg: bool = False num_videos_per_prompt: int = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

Parameters

CogVideoXPipelineOutput if return_dict is True, otherwise atuple. When returning a tuple, the first element is a list with the generated images.

Function invoked when calling the pipeline for generation.

Examples:

import torch from diffusers import CogVideoXImageToVideoPipeline from diffusers.utils import export_to_video, load_image

pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V", torch_dtype=torch.bfloat16) pipe.to("cuda")

prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot." image = load_image( ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg" ... ) video = pipe(image, prompt, use_dynamic_cfg=True) export_to_video(video.frames[0], "output.mp4", fps=8)

encode_prompt

< source >

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

Parameters

Encodes the prompt into text encoder hidden states.

Enables fused QKV projections.

Disable QKV projection fusion if enabled.

CogVideoXVideoToVideoPipeline

class diffusers.CogVideoXVideoToVideoPipeline

< source >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )

Parameters

Pipeline for video-to-video generation using CogVideoX.

This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)

__call__

< source >

( video: typing.List[PIL.Image.Image] = None prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None strength: float = 0.8 guidance_scale: float = 6 use_dynamic_cfg: bool = False num_videos_per_prompt: int = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

Parameters

CogVideoXPipelineOutput if return_dict is True, otherwise atuple. When returning a tuple, the first element is a list with the generated images.

Function invoked when calling the pipeline for generation.

Examples:

import torch from diffusers import CogVideoXDPMScheduler, CogVideoXVideoToVideoPipeline from diffusers.utils import export_to_video, load_video

pipe = CogVideoXVideoToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16) pipe.to("cuda") pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config)

input_video = load_video( ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4" ... ) prompt = ( ... "An astronaut stands triumphantly at the peak of a towering mountain. Panorama of rugged peaks and " ... "valleys. Very futuristic vibe and animated aesthetic. Highlights of purple and golden colors in " ... "the scene. The sky is looks like an animated/cartoonish dream of galaxies, nebulae, stars, planets, " ... "moons, but the remainder of the scene is mostly realistic." ... )

video = pipe( ... video=input_video, prompt=prompt, strength=0.8, guidance_scale=6, num_inference_steps=50 ... ).frames[0] export_to_video(video, "output.mp4", fps=8)

encode_prompt

< source >

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

Parameters

Encodes the prompt into text encoder hidden states.

Enables fused QKV projections.

Disable QKV projection fusion if enabled.

CogVideoXFunControlPipeline

class diffusers.CogVideoXFunControlPipeline

< source >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: KarrasDiffusionSchedulers )

Parameters

Pipeline for controlled text-to-video generation using CogVideoX Fun.

This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)

__call__

< source >

( prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None control_video: typing.Optional[typing.List[PIL.Image.Image]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None guidance_scale: float = 6 use_dynamic_cfg: bool = False num_videos_per_prompt: int = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None control_video_latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

Parameters

CogVideoXPipelineOutput if return_dict is True, otherwise atuple. When returning a tuple, the first element is a list with the generated images.

Function invoked when calling the pipeline for generation.

Examples:

import torch from diffusers import CogVideoXFunControlPipeline, DDIMScheduler from diffusers.utils import export_to_video, load_video

pipe = CogVideoXFunControlPipeline.from_pretrained( ... "alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose", torch_dtype=torch.bfloat16 ... ) pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) pipe.to("cuda")

control_video = load_video( ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4" ... ) prompt = ( ... "An astronaut stands triumphantly at the peak of a towering mountain. Panorama of rugged peaks and " ... "valleys. Very futuristic vibe and animated aesthetic. Highlights of purple and golden colors in " ... "the scene. The sky is looks like an animated/cartoonish dream of galaxies, nebulae, stars, planets, " ... "moons, but the remainder of the scene is mostly realistic." ... )

video = pipe(prompt=prompt, control_video=control_video).frames[0] export_to_video(video, "output.mp4", fps=8)

encode_prompt

< source >

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

Parameters

Encodes the prompt into text encoder hidden states.

Enables fused QKV projections.

Disable QKV projection fusion if enabled.

CogVideoXPipelineOutput

class diffusers.pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput

< source >

( frames: Tensor )

Parameters

Output class for CogVideo pipelines.

< > Update on GitHub