Diffusers 文档

Text2Video-Zero

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Text2Video-Zero

Text2Video-Zero: Text-to-Image Diffusion Models are Zero-Shot Video Generators 是由 Levon Khachatryan, Andranik Movsisyan, Vahram Tadevosyan, Roberto Henschel, Zhangyang Wang, Shant Navasardyan, Humphrey Shi 撰写。

Text2Video-Zero 支持使用以下任一方式进行零样本视频生成

  1. 文本提示
  2. 结合姿势或边缘引导的提示
  3. 视频 Instruct-Pix2Pix (指令引导的视频编辑)

结果在时间上是一致的,并紧密遵循引导和文本提示。

teaser-img

论文摘要如下

最近的文本到视频生成方法依赖于计算量大的训练,并需要大规模的视频数据集。在本文中,我们介绍了一个新的零样本文本到视频生成任务,并提出了一种低成本的方法(无需任何训练或优化),通过利用现有文本到图像合成方法(例如,Stable Diffusion)的能力,使其适用于视频领域。我们的主要修改包括:(i)使用运动动力学丰富生成的帧的潜在代码,以保持全局场景和背景时间的一致性;以及(ii)使用每个帧对第一帧的新跨帧注意力重新编程帧级自注意力,以保留前景对象的上下文、外观和身份。实验表明,这带来了低开销,但高质量且非常一致的视频生成。此外,我们的方法不仅限于文本到视频合成,还适用于其他任务,例如条件和内容专业化视频生成,以及视频 Instruct-Pix2Pix,即指令引导的视频编辑。正如实验所示,尽管我们的方法没有在额外的视频数据上进行训练,但其性能与最近的方法相当,有时甚至更好。

您可以在项目页面论文原始代码库中找到关于 Text2Video-Zero 的更多信息。

使用示例

文本到视频

要从提示词生成视频,请运行以下 Python 代码

import torch
from diffusers import TextToVideoZeroPipeline
import imageio

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = TextToVideoZeroPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

prompt = "A panda is playing guitar on times square"
result = pipe(prompt=prompt).images
result = [(r * 255).astype("uint8") for r in result]
imageio.mimsave("video.mp4", result, fps=4)

您可以在 pipeline 调用中更改这些参数

  • 运动场强度(参见论文,第 3.3.1 节)
    • motion_field_strength_xmotion_field_strength_y。默认值:motion_field_strength_x=12motion_field_strength_y=12
  • TT'(参见论文,第 3.3.1 节)
    • t0t1 的取值范围为 {0, ..., num_inference_steps}。默认值:t0=45t1=48
  • 视频长度
    • video_length,要生成的视频帧数。默认值:video_length=8

我们还可以通过分块处理的方式生成更长的视频

import torch
from diffusers import TextToVideoZeroPipeline
import numpy as np

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = TextToVideoZeroPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
seed = 0
video_length = 24  #24 ÷ 4fps = 6 seconds
chunk_size = 8
prompt = "A panda is playing guitar on times square"

# Generate the video chunk-by-chunk
result = []
chunk_ids = np.arange(0, video_length, chunk_size - 1)
generator = torch.Generator(device="cuda")
for i in range(len(chunk_ids)):
    print(f"Processing chunk {i + 1} / {len(chunk_ids)}")
    ch_start = chunk_ids[i]
    ch_end = video_length if i == len(chunk_ids) - 1 else chunk_ids[i + 1]
    # Attach the first frame for Cross Frame Attention
    frame_ids = [0] + list(range(ch_start, ch_end))
    # Fix the seed for the temporal consistency
    generator.manual_seed(seed)
    output = pipe(prompt=prompt, video_length=len(frame_ids), generator=generator, frame_ids=frame_ids)
    result.append(output.images[1:])

# Concatenate chunks and save
result = np.concatenate(result)
result = [(r * 255).astype("uint8") for r in result]
imageio.mimsave("video.mp4", result, fps=4)
  • SDXL 支持

    为了在使用提示词生成视频时使用 SDXL 模型,请使用 TextToVideoZeroSDXLPipeline pipeline
import torch
from diffusers import TextToVideoZeroSDXLPipeline

model_id = "stabilityai/stable-diffusion-xl-base-1.0"
pipe = TextToVideoZeroSDXLPipeline.from_pretrained(
    model_id, torch_dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")

带有姿势控制的文本到视频

要从带有额外姿势控制的提示词生成视频

  1. 下载演示视频

    from huggingface_hub import hf_hub_download
    
    filename = "__assets__/poses_skeleton_gifs/dance1_corr.mp4"
    repo_id = "PAIR/Text2Video-Zero"
    video_path = hf_hub_download(repo_type="space", repo_id=repo_id, filename=filename)
  1. 读取包含提取的姿势图像的视频

    from PIL import Image
    import imageio
    
    reader = imageio.get_reader(video_path, "ffmpeg")
    frame_count = 8
    pose_images = [Image.fromarray(reader.get_data(i)) for i in range(frame_count)]

    要从实际视频中提取姿势,请阅读 ControlNet 文档

  2. 使用我们的自定义注意力处理器运行 StableDiffusionControlNetPipeline

    import torch
    from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
    from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero import CrossFrameAttnProcessor
    
    model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
    controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-openpose", torch_dtype=torch.float16)
    pipe = StableDiffusionControlNetPipeline.from_pretrained(
        model_id, controlnet=controlnet, torch_dtype=torch.float16
    ).to("cuda")
    
    # Set the attention processor
    pipe.unet.set_attn_processor(CrossFrameAttnProcessor(batch_size=2))
    pipe.controlnet.set_attn_processor(CrossFrameAttnProcessor(batch_size=2))
    
    # fix latents for all frames
    latents = torch.randn((1, 4, 64, 64), device="cuda", dtype=torch.float16).repeat(len(pose_images), 1, 1, 1)
    
    prompt = "Darth Vader dancing in a desert"
    result = pipe(prompt=[prompt] * len(pose_images), image=pose_images, latents=latents).images
    imageio.mimsave("video.mp4", result, fps=4)
  • SDXL 支持

    由于我们的注意力处理器也适用于 SDXL,因此可以利用它来使用由 SDXL 驱动的 ControlNet 模型从提示词生成视频

    import torch
    from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel
    from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero import CrossFrameAttnProcessor
    
    controlnet_model_id = 'thibaud/controlnet-openpose-sdxl-1.0'
    model_id = 'stabilityai/stable-diffusion-xl-base-1.0'
    
    controlnet = ControlNetModel.from_pretrained(controlnet_model_id, torch_dtype=torch.float16)
    pipe = StableDiffusionControlNetPipeline.from_pretrained(
    	model_id, controlnet=controlnet, torch_dtype=torch.float16
    ).to('cuda')
    
    # Set the attention processor
    pipe.unet.set_attn_processor(CrossFrameAttnProcessor(batch_size=2))
    pipe.controlnet.set_attn_processor(CrossFrameAttnProcessor(batch_size=2))
    
    # fix latents for all frames
    latents = torch.randn((1, 4, 128, 128), device="cuda", dtype=torch.float16).repeat(len(pose_images), 1, 1, 1)
    
    prompt = "Darth Vader dancing in a desert"
    result = pipe(prompt=[prompt] * len(pose_images), image=pose_images, latents=latents).images
    imageio.mimsave("video.mp4", result, fps=4)

带有边缘控制的文本到视频

要从带有额外 Canny 边缘控制的提示词生成视频,请按照上述姿势引导生成的相同步骤,使用 Canny 边缘 ControlNet 模型

视频 Instruct-Pix2Pix

要执行文本引导的视频编辑(使用 InstructPix2Pix

  1. 下载演示视频

    from huggingface_hub import hf_hub_download
    
    filename = "__assets__/pix2pix video/camel.mp4"
    repo_id = "PAIR/Text2Video-Zero"
    video_path = hf_hub_download(repo_type="space", repo_id=repo_id, filename=filename)
  2. 从路径读取视频

    from PIL import Image
    import imageio
    
    reader = imageio.get_reader(video_path, "ffmpeg")
    frame_count = 8
    video = [Image.fromarray(reader.get_data(i)) for i in range(frame_count)]
  3. 使用我们的自定义注意力处理器运行 StableDiffusionInstructPix2PixPipeline

    import torch
    from diffusers import StableDiffusionInstructPix2PixPipeline
    from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero import CrossFrameAttnProcessor
    
    model_id = "timbrooks/instruct-pix2pix"
    pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
    pipe.unet.set_attn_processor(CrossFrameAttnProcessor(batch_size=3))
    
    prompt = "make it Van Gogh Starry Night style"
    result = pipe(prompt=[prompt] * len(video), image=video).images
    imageio.mimsave("edited_video.mp4", result, fps=4)

DreamBooth 专门化

文本到视频带有姿势控制的文本到视频带有边缘控制的文本到视频方法可以使用自定义的 DreamBooth 模型运行,如下所示,用于 Canny 边缘 ControlNet 模型Avatar 风格 DreamBooth 模型

  1. 下载演示视频

    from huggingface_hub import hf_hub_download
    
    filename = "__assets__/canny_videos_mp4/girl_turning.mp4"
    repo_id = "PAIR/Text2Video-Zero"
    video_path = hf_hub_download(repo_type="space", repo_id=repo_id, filename=filename)
  2. 从路径读取视频

    from PIL import Image
    import imageio
    
    reader = imageio.get_reader(video_path, "ffmpeg")
    frame_count = 8
    canny_edges = [Image.fromarray(reader.get_data(i)) for i in range(frame_count)]
  3. 使用自定义训练的 DreamBooth 模型运行 StableDiffusionControlNetPipeline

    import torch
    from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
    from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero import CrossFrameAttnProcessor
    
    # set model id to custom model
    model_id = "PAIR/text2video-zero-controlnet-canny-avatar"
    controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
    pipe = StableDiffusionControlNetPipeline.from_pretrained(
        model_id, controlnet=controlnet, torch_dtype=torch.float16
    ).to("cuda")
    
    # Set the attention processor
    pipe.unet.set_attn_processor(CrossFrameAttnProcessor(batch_size=2))
    pipe.controlnet.set_attn_processor(CrossFrameAttnProcessor(batch_size=2))
    
    # fix latents for all frames
    latents = torch.randn((1, 4, 64, 64), device="cuda", dtype=torch.float16).repeat(len(canny_edges), 1, 1, 1)
    
    prompt = "oil painting of a beautiful girl avatar style"
    result = pipe(prompt=[prompt] * len(canny_edges), image=canny_edges, latents=latents).images
    imageio.mimsave("video.mp4", result, fps=4)

您可以使用此链接过滤掉一些可用的 DreamBooth 训练模型。

请务必查看调度器指南,了解如何探索调度器速度和质量之间的权衡,并查看跨管道重用组件部分,了解如何有效地将相同的组件加载到多个管道中。

TextToVideoZeroPipeline

class diffusers.TextToVideoZeroPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于去噪编码视频潜在空间的 UNet3DConditionModel
  • scheduler (SchedulerMixin) — 调度器,与 unet 结合使用以去噪编码的图像潜在空间。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于评估生成的图像是否可能被认为具有攻击性或有害。有关模型潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — CLIPImageProcessor,用于从生成的图像中提取特征;用作 safety_checker 的输入。

使用 Stable Diffusion 进行零样本文本到视频生成的 Pipeline。

此模型继承自 DiffusionPipeline。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] video_length: typing.Optional[int] = 8 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: typing.Optional[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 motion_field_strength_x: float = 12 motion_field_strength_y: float = 12 output_type: typing.Optional[str] = 'tensor' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: typing.Optional[int] = 1 t0: int = 44 t1: int = 47 frame_ids: typing.Optional[typing.List[int]] = None ) TextToVideoPipelineOutput

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,则需要传递 prompt_embeds
  • video_length (int, 可选,默认为 8) — 生成的视频帧数。
  • height (int, 可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。
  • width (int, 可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。
  • num_inference_steps (int, 可选,默认为 50) — 去噪步骤的数量。更多去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。
  • guidance_scale (float, 可选,默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时,guidance scale 启用。
  • negative_prompt (strList[str], 可选) — 用于引导视频生成中不应包含的内容的提示词。如果未定义,则需要改为传递 negative_prompt_embeds。当不使用 guidance(guidance_scale < 1)时忽略。
  • num_videos_per_prompt (int, 可选,默认为 1) — 每个提示词要生成的视频数量。
  • eta (float, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预生成的高斯分布噪声潜变量,用作视频生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则会通过使用提供的随机 generator 进行采样来生成潜变量张量。
  • output_type (str, 可选, 默认为 "np") — 生成视频的输出格式。在 "latent""np" 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 TextToVideoPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个在推理期间每 callback_steps 步调用一次的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每一步都调用回调。
  • motion_field_strength_x (float, 可选, 默认为 12) — 生成视频中沿 x 轴的运动强度。参见 论文,第 3.3.1 节。
  • motion_field_strength_y (float, 可选, 默认为 12) — 生成视频中沿 y 轴的运动强度。参见 论文,第 3.3.1 节。
  • t0 (int, 可选, 默认为 44) — 时间步 t0。应在 [0, num_inference_steps - 1] 范围内。参见 论文,第 3.3.1 节。
  • t1 (int, 可选, 默认为 47) — 时间步 t1。应在 [t0 + 1, num_inference_steps - 1] 范围内。参见 论文,第 3.3.1 节。
  • frame_ids (List[int], 可选) — 正在生成的帧的索引。这在逐块生成较长视频时使用。

返回

TextToVideoPipelineOutput

输出包含生成视频的 ndarray,当 output_type != "latent" 时;否则,输出包含生成视频的潜在代码以及指示相应的生成视频是否包含“不适合工作场所观看”(nsfw)内容的 bool 列表。

用于生成管道的调用函数。

backward_loop

< >

( latents timesteps prompt_embeds guidance_scale callback callback_steps num_warmup_steps extra_step_kwargs cross_attention_kwargs = None ) latents

参数

  • latents — 时间步 timesteps[0] 的潜变量。
  • timesteps — 执行反向过程的时间步。
  • prompt_embeds — 预生成的文本嵌入。
  • guidance_scale — 较高的 guidance scale 值鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时,Guidance scale 启用。
  • callback (Callable, 可选) — 一个在推理期间每 callback_steps 步调用一次的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每一步都调用回调。
  • extra_step_kwargs — extra_step_kwargs。
  • cross_attention_kwargs — 一个 kwargs 字典,如果指定,则会传递给 AttentionProcessor,如 self.processor 中定义的那样。
  • num_warmup_steps — 预热步骤数。

返回

latents

时间步 timesteps[-1] 时反向过程输出的潜变量。

给定时间步列表执行反向过程。

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。 如果未定义,则必须传递 negative_prompt_embeds。 当不使用引导时忽略(即,如果 guidance_scale 小于 1,则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, 可选) — 从 CLIP 跳过的层数,用于计算提示嵌入。 值为 1 表示预最终层的输出将用于计算提示嵌入。

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

forward_loop

< >

( x_t0 t0 t1 generator ) x_t1

参数

  • x_t0 — 时间 t0 的潜在代码。
  • t0 — 时间步 t0。
  • t1 — 时间步 t1。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成确定性的 torch.Generator

返回

x_t1

从时间 t0 到 t1 应用于 x_t0 的前向过程。

执行从时间 t0 到 t1 的 DDPM 前向过程。 这与添加具有相应方差的噪声相同。

TextToVideoZeroSDXLPipeline

class diffusers.TextToVideoZeroSDXLPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None )

参数

使用 Stable Diffusion XL 进行零样本文本到视频生成的 Pipeline。

此模型继承自 DiffusionPipeline。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str], NoneType] = None video_length: typing.Optional[int] = 8 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 denoising_end: typing.Optional[float] = None guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None frame_ids: typing.Optional[typing.List[int]] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None latents: typing.Optional[torch.Tensor] = None motion_field_strength_x: float = 12 motion_field_strength_y: float = 12 output_type: typing.Optional[str] = 'tensor' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 original_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Optional[typing.Tuple[int, int]] = None t0: int = 44 t1: int = 47 )

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示语。如果未定义,则必须传递 prompt_embeds 来代替。
  • prompt_2 (strList[str], 可选) — 将发送到 tokenizer_2text_encoder_2 的提示语。如果未定义,则 prompt 将在两个文本编码器中都使用。
  • video_length (int, 可选, 默认为 8) — 生成的视频帧数。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度像素值。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度像素值。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲更慢的推理速度。
  • denoising_end (float, 可选) — 如果指定,则确定在有意过早终止之前要完成的总去噪过程的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量噪声,这由调度程序选择的离散时间步长决定。当此管道构成“去噪器混合”多管道设置的一部分时,应理想地使用 denoising_end 参数,如 优化图像输出 中详述的那样。
  • guidance_scale (float, 可选, 默认为 7.5) — 无分类器扩散引导 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 的公式 2 中的 w。通过设置 guidance_scale > 1 启用引导尺度。较高的引导尺度鼓励生成与文本 prompt 紧密相关的图像,但通常以降低图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示语。如果未定义,则必须传递 negative_prompt_embeds 来代替。当不使用引导时(即,如果 guidance_scale 小于 1),则忽略。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成的提示语,将发送到 tokenizer_2text_encoder_2。如果未定义,则 negative_prompt 将在两个文本编码器中都使用。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个提示语要生成的视频数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,对于其他调度器将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • frame_ids (List[int], 可选) — 正在生成的帧的索引。这在逐块生成较长视频时使用。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可以用于轻松调整文本输入,例如 提示语权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可以用于轻松调整文本输入,例如 提示语权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可以用于轻松调整文本输入,例如 提示语权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可以用于轻松调整文本输入,例如 提示语权重。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • latents (torch.Tensor, 可选) — 预生成的带噪潜在变量,从高斯分布中采样,用作图像生成的输入。可以用于使用不同的提示语调整相同的生成结果。如果未提供,则将通过使用提供的随机 generator 进行采样来生成潜在变量张量。
  • motion_field_strength_x (float, 可选, 默认为 12) — 生成视频中沿 x 轴的运动强度。参见 论文 第 3.3.1 节。
  • motion_field_strength_y (float, 可选, 默认为 12) — 生成视频中沿 y 轴的运动强度。参见 论文 第 3.3.1 节。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 将在推理期间每 callback_steps 步调用的函数。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 将调用 callback 函数的频率。如果未指定,则将在每个步骤调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个kwargs字典,如果指定,则会传递给在 diffusers.cross_attentionself.processor 下定义的 AttentionProcessor
  • guidance_rescale (float, 可选, 默认为 0.7) — 由 Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的 Guidance 重新缩放因子。 guidance_scaleCommon Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中被定义为 φ。当使用零终端信噪比(SNR)时,Guidance 重新缩放因子应修复过度曝光的问题。
  • original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 如果 original_sizetarget_size 不同,图像将显示为缩小或放大。如果未指定,original_size 默认为 (width, height)。 作为 SDXL 微调的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。
  • crops_coords_top_left (Tuple[int], 可选, 默认为 (0, 0)) — crops_coords_top_left 可用于生成看起来像是从 crops_coords_top_left 位置向下“裁剪”的图像。通常通过将 crops_coords_top_left 设置为 (0, 0) 来获得良好居中的图像。 作为 SDXL 微调的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。
  • target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的期望高度和宽度。如果未指定,则默认为 (width, height)。 作为 SDXL 微调的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。
  • t0 (int, 可选, 默认为 44) — 时间步 t0。应在范围 [0, num_inference_steps - 1] 内。 参见 论文 的 3.3.1 节。
  • t1 (int, 可选, 默认为 47) — 时间步 t1。应在范围 [t0 + 1, num_inference_steps - 1] 内。 参见 论文 的 3.3.1 节。

调用 pipeline 进行生成时调用的函数。

backward_loop

< >

( latents timesteps prompt_embeds guidance_scale callback callback_steps num_warmup_steps extra_step_kwargs add_text_embeds add_time_ids cross_attention_kwargs = None guidance_rescale: float = 0.0 ) latents

参数

  • latents — 时间步 timesteps[0] 的 Latents。
  • timesteps — 执行反向过程的时间步列表。
  • prompt_embeds — 预生成的文本嵌入。
  • guidance_scale — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时,Guidance scale 启用。
  • callback (Callable, 可选) — 在推理期间每 callback_steps 步调用一次的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每一步都调用回调。
  • extra_step_kwargs — Extra_step_kwargs。
  • cross_attention_kwargs — 一个 kwargs 字典,如果指定,则会传递给 self.processor 中定义的 AttentionProcessor
  • num_warmup_steps — 预热步数。

返回

latents

时间步 timesteps[-1] 的反向过程输出的 Latents

执行给定时间步列表的反向过程

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的 prompt
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的 prompt 或 prompts。如果未定义,则 prompt 将用于两个文本编码器。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器 guidance。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 negative_prompt_embeds。当不使用 guidance 时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts,将发送到 tokenizer_2text_encoder_2。如果未定义,则 negative_prompt 将用于两个文本编码器。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重。 如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重。 如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重。 如果未提供,则将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 缩放比例。
  • clip_skip (int, 可选) — 计算提示词嵌入时,要从 CLIP 跳过的层数。 值为 1 表示预最终层的输出将用于计算提示词嵌入。

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

forward_loop

< >

( x_t0 t0 t1 generator ) x_t1

参数

  • x_t0 — 时间步 t0 的潜在代码。
  • t0 — 时间步 t0。
  • t1 — 时间步 t1。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator

返回

x_t1

从时间 t0 到 t1 应用于 x_t0 的前向过程。

执行从时间 t0 到 t1 的 DDPM 前向过程。 这与添加具有相应方差的噪声相同。

TextToVideoPipelineOutput

class diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.TextToVideoPipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )

参数

  • images ([List[PIL.Image.Image], np.ndarray]) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • nsfw_content_detected ([List[bool]]) — 列表,指示相应的生成图像是否包含“不适合工作场所”(nsfw)内容;如果无法执行安全检查,则为 None

零样本文本到视频管道的输出类。

< > 在 GitHub 上更新