Diffusers 文档
CogVideoX
并获得增强的文档体验
开始使用
CogVideoX
CogVideoX是一个大型扩散Transformer模型,拥有2B和5B参数,旨在从文本生成更长、更一致的视频。该模型使用3D因果变分自编码器更高效地处理视频数据,通过减少序列长度(以及相关的训练计算)并防止生成视频中的闪烁。一个带有自适应LayerNorm的“专家”Transformer改进了文本与视频之间的对齐,而3D全注意力有助于准确捕捉生成视频中的运动和时间。
您可以在CogVideoX集合中找到所有原始的CogVideoX检查点。
点击右侧边栏中的CogVideoX模型,查看其他视频生成任务的更多示例。
以下示例演示了如何生成针对内存或推理速度进行优化的视频。
有关各种内存节省技术的更多详细信息,请参阅减少内存使用指南。
下方量化的CogVideoX 5B模型需要约16GB的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
# quantize weights to int8 with torchao
pipeline_quant_config = PipelineQuantizationConfig(
quant_backend="torchao",
quant_kwargs={"quant_type": "int8wo"},
components_to_quantize=["transformer"]
)
# fp8 layerwise weight-casting
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")
# model-offloading
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)
注意事项
CogVideoX支持使用load_lora_weights()加载LoRA。
显示示例代码
import torch from diffusers import CogVideoXPipeline from diffusers.hooks import apply_group_offloading from diffusers.utils import export_to_video pipeline = CogVideoXPipeline.from_pretrained( "THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16 ) pipeline.to("cuda") # load LoRA weights pipeline.load_lora_weights("finetrainers/CogVideoX-1.5-crush-smol-v0", adapter_name="crush-lora") pipeline.set_adapters("crush-lora", 0.9) # model-offloading pipeline.enable_model_cpu_offload() prompt = """ PIKA_CRUSH A large metal cylinder is seen pressing down on a pile of Oreo cookies, flattening them as if they were under a hydraulic press. """ negative_prompt = "inconsistent motion, blurry motion, worse quality, degenerate outputs, deformed outputs" video = pipeline( prompt=prompt, negative_prompt=negative_prompt, num_frames=81, height=480, width=768, num_inference_steps=50 ).frames[0] export_to_video(video, "output.mp4", fps=16)
文本到视频 (T2V) 检查点在1360x768分辨率下效果最佳,因为它是在此分辨率下预训练的。
图像到视频 (I2V) 检查点支持多种分辨率。宽度可以在768到1360之间变化,但高度必须是758。高度和宽度都必须能被16整除。
T2V和I2V检查点在81帧和161帧下效果最佳。建议以16fps导出生成的视频。
请参考下表查看启用各种内存节省技术时的内存使用情况。
方法 内存使用(已启用) 内存使用(已禁用) enable_model_cpu_offload 19GB 33GB enable_sequential_cpu_offload <4GB ~33GB(推理速度非常慢) enable_tiling 11GB(启用enable_model_cpu_offload) ---
CogVideoXPipeline
class diffusers.CogVideoXPipeline
< 源 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )
参数
- vae (AutoencoderKL) — 用于将视频编码和解码为潜在表示的变分自编码器(VAE)模型。
- text_encoder (
T5EncoderModel
) — 冻结文本编码器。CogVideoX使用T5;具体是t5-v1_1-xxl变体。 - tokenizer (
T5Tokenizer
) — T5Tokenizer类的分词器。 - transformer (CogVideoXTransformer3DModel) — 一个文本条件
CogVideoXTransformer3DModel
,用于对编码后的视频潜在表示进行去噪。 - scheduler (SchedulerMixin) — 与
transformer
结合使用,用于对编码后的视频潜在表示进行去噪的调度器。
用于使用CogVideoX进行文本到视频生成的管道。
此模型继承自DiffusionPipeline。请查阅超类文档,了解库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)。
__call__
< 源 >( 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 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传入prompt_embeds
。 - negative_prompt (
str
或List[str]
, 可选) — 用于不引导图像生成的提示或提示列表。如果未定义,则必须传入negative_prompt_embeds
。当不使用引导时(即,如果guidance_scale
小于1
时),则忽略。 - height (
int
, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的高度(像素)。默认设置为480以获得最佳效果。 - width (
int
, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的宽度(像素)。默认设置为720以获得最佳效果。 - num_frames (
int
, 默认为48
) — 生成的帧数。必须能被self.vae_scale_factor_temporal整除。生成的视频将包含1个额外帧,因为CogVideoX是基于 (num_seconds * fps + 1) 帧进行条件化的,其中num_seconds为6,fps为8。然而,由于视频可以以任何fps保存,唯一需要满足的条件是上述的可整除性。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步数。更多去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - timesteps (
List[int]
, 可选) — 用于去噪过程的自定义时间步长,适用于在set_timesteps
方法中支持timesteps
参数的调度器。如果未定义,将使用传入num_inference_steps
时的默认行为。必须按降序排列。 - guidance_scale (
float
, 可选, 默认为 7.0) — Classifier-Free Diffusion Guidance中定义的引导比例。guidance_scale
定义为Imagen Paper方程2中的w
。通过设置guidance_scale > 1
启用引导比例。更高的引导比例会鼓励生成与文本prompt
更紧密相关的图像,通常会以牺牲图像质量为代价。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示生成的视频数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个torch生成器,用于使生成确定化。 - latents (
torch.FloatTensor
, 可选) — 预生成的带噪声的潜在变量,从高斯分布中采样,用作图像生成的输入。可用于通过不同提示调整相同的生成。如果未提供,将通过使用提供的随机generator
采样生成潜在张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示加权。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示加权。如果未提供,负面提示嵌入将从negative_prompt
输入参数生成。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
而不是纯元组。 - attention_kwargs (
dict
, 可选) — 一个kwargs字典,如果指定,则作为self.processor
下定义的AttentionProcessor
的参数传入diffusers.models.attention_processor。 - callback_on_step_end (
Callable
, 可选) — 一个函数,在推理过程中每个去噪步骤结束时调用。该函数使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
中指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传入。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
, 默认为226
) — 编码提示中的最大序列长度。必须与self.transformer.config.max_text_seq_length
保持一致,否则可能导致结果不佳。
返回
CogVideoXPipelineOutput 或 tuple
如果return_dict
为True,则返回CogVideoXPipelineOutput,否则返回tuple
。当返回元组时,第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> import torch
>>> from diffusers import CogVideoXPipeline
>>> from diffusers.utils import export_to_video
>>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
>>> 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
< 源 >( 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 )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的提示。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示。如果未定义,则必须传入negative_prompt_embeds
。在不使用引导时(即,如果guidance_scale
小于1
时),将被忽略。 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用分类器自由引导。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示应生成的视频数量。生成嵌入的 torch 设备。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds
将从negative_prompt
输入参数生成。 - device — (
torch.device
, 可选): torch 设备 - dtype — (
torch.dtype
, 可选): torch 数据类型
将提示编码为文本编码器隐藏状态。
启用融合的 QKV 投影。
如果启用了 QKV 投影融合,则禁用它。
CogVideoXImageToVideoPipeline
class diffusers.CogVideoXImageToVideoPipeline
< 来源 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )
参数
- vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将视频编码和解码为潜在表示。
- text_encoder (
T5EncoderModel
) — 冻结文本编码器。CogVideoX 使用 T5;特别是 t5-v1_1-xxl 变体。 - tokenizer (
T5Tokenizer
) —T5Tokenizer
类的分词器。 - transformer (CogVideoXTransformer3DModel) — 用于对编码视频潜在表示进行去噪的文本条件
CogVideoXTransformer3DModel
。 - scheduler (SchedulerMixin) — 与
transformer
结合使用的调度器,用于对编码视频潜在表示进行去噪。
使用 CogVideoX 进行图像到视频生成的管道。
此模型继承自DiffusionPipeline。请查阅超类文档,了解库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)。
__call__
< 来源 >( 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 或 tuple
参数
- image (
PipelineImageInput
) — 用于调节生成的输入图像。必须是图像、图像列表或torch.Tensor
。 - prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示。如果未定义,则必须传入prompt_embeds
。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示。如果未定义,则必须传入negative_prompt_embeds
。在不使用引导时(即,如果guidance_scale
小于1
时),将被忽略。 - height (
int
, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的像素高度。为获得最佳结果,默认设置为 480。 - width (
int
, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的像素宽度。为获得最佳结果,默认设置为 720。 - num_frames (
int
, 默认为48
) — 要生成的帧数。必须可被 self.vae_scale_factor_temporal 整除。生成的视频将包含 1 个额外帧,因为 CogVideoX 使用 (num_seconds * fps + 1) 帧进行条件设置,其中 num_seconds 为 6,fps 为 8。但是,由于视频可以以任何 fps 保存,唯一需要满足的条件是上述可整除性。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步数。更多去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - timesteps (
List[int]
, 可选) — 用于去噪过程的自定义时间步长,适用于在其set_timesteps
方法中支持timesteps
参数的调度器。如果未定义,将使用传入num_inference_steps
时的默认行为。必须按降序排列。 - guidance_scale (
float
, 可选, 默认为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale
定义为 Imagen Paper 方程 2 中的w
。通过设置guidance_scale > 1
启用引导比例。更高的引导比例鼓励生成与文本prompt
紧密相关的图像,通常以牺牲图像质量为代价。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的视频数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch generator(s),用于使生成具有确定性。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声潜在表示,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,将使用提供的随机generator
采样生成一个潜在张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds
将从negative_prompt
输入参数生成。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
而不是普通元组。 - attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,将作为self.processor
中定义的AttentionProcessor
的参数传递到 diffusers.models.attention_processor。 - callback_on_step_end (
Callable
, 可选) — 在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
中指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
, 默认为226
) — 编码提示中的最大序列长度。必须与self.transformer.config.max_text_seq_length
保持一致,否则可能导致结果不佳。
返回
CogVideoXPipelineOutput 或 tuple
如果return_dict
为True,则返回CogVideoXPipelineOutput,否则返回tuple
。当返回元组时,第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> 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
< 来源 >( 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 )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的提示。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示。如果未定义,则必须传入negative_prompt_embeds
。在不使用引导时(即,如果guidance_scale
小于1
时),将被忽略。 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用分类器自由引导。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示应生成的视频数量。生成嵌入的 torch 设备。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds
将从negative_prompt
输入参数生成。 - device — (
torch.device
, 可选): torch 设备 - dtype — (
torch.dtype
, 可选): torch 数据类型
将提示编码为文本编码器隐藏状态。
启用融合的 QKV 投影。
如果启用了 QKV 投影融合,则禁用它。
CogVideoXVideoToVideoPipeline
class diffusers.CogVideoXVideoToVideoPipeline
< 来源 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )
参数
- vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将视频编码和解码为潜在表示。
- text_encoder (
T5EncoderModel
) — 冻结文本编码器。CogVideoX 使用 T5;特别是 t5-v1_1-xxl 变体。 - tokenizer (
T5Tokenizer
) —T5Tokenizer
类的分词器。 - transformer (CogVideoXTransformer3DModel) — 用于对编码视频潜在表示进行去噪的文本条件
CogVideoXTransformer3DModel
。 - scheduler (SchedulerMixin) — 与
transformer
结合使用的调度器,用于对编码视频潜在表示进行去噪。
使用 CogVideoX 进行视频到视频生成的管道。
此模型继承自DiffusionPipeline。请查阅超类文档,了解库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)。
__call__
< 来源 >( 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
参数
- video (
List[PIL.Image.Image]
) — 用于条件生成输入的视频。必须是视频的图像/帧列表。 - prompt (
str
或List[str]
,可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传入prompt_embeds
。 - negative_prompt (
str
或List[str]
,可选) — 用于不引导图像生成的提示或提示列表。如果未定义,则必须传入negative_prompt_embeds
。当不使用指导时(即guidance_scale
小于1
时),该参数将被忽略。 - height (
int
,可选,默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的高度(像素)。为了获得最佳结果,默认设置为 480。 - width (
int
,可选,默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的宽度(像素)。为了获得最佳结果,默认设置为 720。 - num_inference_steps (
int
,可选,默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - timesteps (
List[int]
,可选) — 用于去噪过程的自定义时间步长,适用于在其set_timesteps
方法中支持timesteps
参数的调度器。如果未定义,将使用传入num_inference_steps
时的默认行为。必须按降序排列。 - strength (
float
,可选,默认为 0.8) — 强度越高,原始视频与生成视频之间的差异越大。 - guidance_scale (
float
,可选,默认为 7.0) — 如 Classifier-Free Diffusion Guidance 中所定义的指导比例。guidance_scale
被定义为 Imagen Paper 中公式 2 的w
。通过设置guidance_scale > 1
启用指导比例。更高的指导比例会促使生成与文本prompt
更紧密相关的图像,但通常会牺牲图像质量。 - num_videos_per_prompt (
int
,可选,默认为 1) — 每个提示要生成的视频数量。 - generator (
torch.Generator
或List[torch.Generator]
,可选) — 一个或多个 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.FloatTensor
,可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,将使用提供的随机generator
采样生成潜在张量。 - prompt_embeds (
torch.FloatTensor
,可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.FloatTensor
,可选) — 预先生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds
将从negative_prompt
输入参数生成。 - output_type (
str
,可选,默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
,可选,默认为True
) — 是否返回~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
而不是普通元组。 - attention_kwargs (
dict
,可选) — 一个 kwargs 字典,如果指定,则会传递给 diffusers.models.attention_processor 中self.processor
下定义的AttentionProcessor
。 - callback_on_step_end (
Callable
,可选) — 在推理过程中每个去噪步骤结束时调用的函数。函数调用时包含以下参数:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
,可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
,默认为226
) — 编码提示中的最大序列长度。必须与self.transformer.config.max_text_seq_length
保持一致,否则可能导致结果不佳。
返回
CogVideoXPipelineOutput 或 tuple
如果return_dict
为True,则返回CogVideoXPipelineOutput,否则返回tuple
。当返回元组时,第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> import torch
>>> from diffusers import CogVideoXDPMScheduler, CogVideoXVideoToVideoPipeline
>>> from diffusers.utils import export_to_video, load_video
>>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
>>> 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
< 源文件 >( 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 )
参数
- prompt (
str
或List[str]
,可选) — 待编码的提示 - negative_prompt (
str
或List[str]
,可选) — 用于不引导图像生成的提示或提示列表。如果未定义,则必须传入negative_prompt_embeds
。当不使用指导时(即guidance_scale
小于1
时),该参数将被忽略。 - do_classifier_free_guidance (
bool
,可选,默认为True
) — 是否使用分类器自由指导。 - num_videos_per_prompt (
int
,可选,默认为 1) — 每个提示应生成的视频数量。用于放置结果嵌入的 torch 设备。 - prompt_embeds (
torch.Tensor
,可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
,可选) — 预先生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds
将从negative_prompt
输入参数生成。 - device — (
torch.device
,可选): torch 设备 - dtype — (
torch.dtype
,可选): torch 数据类型
将提示编码为文本编码器隐藏状态。
启用融合的 QKV 投影。
如果启用了 QKV 投影融合,则禁用它。
CogVideoXFunControlPipeline
class diffusers.CogVideoXFunControlPipeline
< 源文件 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: KarrasDiffusionSchedulers )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将视频编码和解码为潜在表示。
- text_encoder (
T5EncoderModel
) — 冻结的文本编码器。CogVideoX 使用 T5;具体来说是 t5-v1_1-xxl 变体。 - tokenizer (
T5Tokenizer
) — T5Tokenizer 类的分词器。 - transformer (CogVideoXTransformer3DModel) — 一个文本条件
CogVideoXTransformer3DModel
,用于对编码的视频潜在变量进行去噪。 - scheduler (SchedulerMixin) — 与
transformer
结合使用的调度器,用于对编码的视频潜在变量进行去噪。
用于使用 CogVideoX Fun 进行受控文本到视频生成的管道。
此模型继承自DiffusionPipeline。请查阅超类文档,了解库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)。
__call__
< 源文件 >( 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 或 tuple
参数
- prompt (
str
或List[str]
,可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传入prompt_embeds
。 - negative_prompt (
str
或List[str]
,可选) — 用于不引导图像生成的提示或提示列表。如果未定义,则必须传入negative_prompt_embeds
。当不使用指导时(即guidance_scale
小于1
时),该参数将被忽略。 - control_video (
List[PIL.Image.Image]
) — 用于条件生成的控制视频。必须是视频的图像/帧列表。如果未提供,则必须提供control_video_latents
。 - height (
int
,可选,默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的高度(像素)。为了获得最佳结果,默认设置为 480。 - width (
int
,可选,默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的宽度(像素)。为了获得最佳结果,默认设置为 720。 - num_inference_steps (
int
,可选,默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - timesteps (
List[int]
, 可选) — 用于去噪过程的自定义时间步,适用于其set_timesteps
方法支持timesteps
参数的调度器。如果未定义,将使用传递num_inference_steps
时的默认行为。必须按降序排列。 - guidance_scale (
float
, 可选, 默认为 6.0) — 如 Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale
定义为 Imagen Paper 方程 2 中的w
。通过设置guidance_scale > 1
启用引导比例。更高的引导比例鼓励生成与文本prompt
紧密相关的图像,通常以牺牲较低图像质量为代价。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的视频数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch 生成器,用于使生成确定化。 - latents (
torch.Tensor
, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作视频生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,将使用提供的随机generator
采样生成一个潜在变量张量。 - control_video_latents (
torch.Tensor
, 可选) — 预先生成的控制潜在变量,从高斯分布中采样,用作受控视频生成的输入。如果未提供,则必须提供control_video
。 - prompt_embeds (
torch.Tensor
, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,负面提示嵌入将从negative_prompt
输入参数生成。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。选择 PIL:PIL.Image.Image
或np.array
。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
而不是普通元组。 - attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的self.processor
的AttentionProcessor
。 - callback_on_step_end (
Callable
, 可选) — 在推理过程中每次去噪步骤结束时调用的函数。该函数以以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类的._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
, 默认为226
) — 编码提示中的最大序列长度。必须与self.transformer.config.max_text_seq_length
保持一致,否则可能导致结果不佳。
返回
CogVideoXPipelineOutput 或 tuple
如果return_dict
为True,则返回CogVideoXPipelineOutput,否则返回tuple
。当返回元组时,第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> 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
< 源代码 >( 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 )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的提示 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示或多个提示。如果未定义,则必须传递negative_prompt_embeds
。当不使用引导时(即,如果guidance_scale
小于1
时),此参数将被忽略。 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用无分类器引导。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示应生成的视频数量。要放置结果嵌入的 torch 设备 - prompt_embeds (
torch.Tensor
, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,负面提示嵌入将从negative_prompt
输入参数生成。 - device — (
torch.device
, 可选): torch 设备 - dtype — (
torch.dtype
, 可选): torch 数据类型
将提示编码为文本编码器隐藏状态。
启用融合的 QKV 投影。
如果启用了 QKV 投影融合,则禁用它。
CogVideoXPipelineOutput
class diffusers.pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput
< 源代码 >( frames: Tensor )
CogVideo 管道的输出类。