Diffusers 文档

Text2Video-Zero

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Text2Video-Zero

LoRA

Text2Video-Zero: Text-to-Image Diffusion Models are Zero-Shot Video Generators 由 Levon Khachatryan、Andranik Movsisyan、Vahram Tadevosyan、Roberto Henschel、张扬王、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)

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

  • 运动场强度(参阅论文,第 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 管道。
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 )

__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) — 较高的引导比例值鼓励模型生成与文本 prompt 密切相关的图像,但会牺牲较低的图像质量。当 guidance_scale > 1 时,启用引导比例。
  • negative_prompt (strList[str], 可选) — 引导视频生成中不包含内容的提示词。如果未定义,您需要传入 negative_prompt_embeds。当不使用引导时 (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 函数的频率。如果未指定,将在每个步骤调用 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) — 时间步 t0。应在 [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 — 较高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但会以较低的图像质量为代价。当 guidance_scale > 1 时启用引导比例。
  • callback (Callable, 可选) — 在推理过程中每隔 callback_steps 步调用的函数。该函数以以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,将在每个步骤调用 callback。
  • extra_step_kwargs — extra_step_kwargs。
  • cross_attention_kwargs — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor
  • 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_embeds 将从 negative_prompt 输入参数生成。
  • 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

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 )

__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 论文中公式 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://huggingface.co/papers/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_embeds 将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从`prompt`输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,负向池化文本嵌入将从`negative_prompt`输入参数生成。
  • latents (torch.Tensor, optional) — 预生成的噪声潜在量,从高斯分布采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,则将使用提供的随机`generator`进行采样生成一个潜在量张量。
  • motion_field_strength_x (float, optional, defaults to 12) — 生成视频中沿 x 轴的运动强度。请参阅论文,第 3.3.1 节。
  • motion_field_strength_y (float, optional, defaults to 12) — 生成视频中沿 y 轴的运动强度。请参阅论文,第 3.3.1 节。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • callback (Callable, optional) — 在推理过程中,每 callback_steps 步调用的函数。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, optional, defaults to 1) — 调用 callback 函数的频率。如果未指定,则在每一步都调用回调。
  • cross_attention_kwargs (dict, optional) — 如果指定,此 kwargs 字典将传递给 diffusers.cross_attention 中定义的 self.processorAttentionProcessor
  • guidance_rescale (float, optional, defaults to 0.7) — Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的指导重缩放因子。guidance_scaleCommon Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中定义为 φ。指导重缩放因子应该修复使用零终端信噪比时的过曝问题。
  • original_size (Tuple[int], optional, defaults to (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], optional, defaults to (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], optional, defaults to (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽度和高度。如果未指定,它将默认为 (width, height)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节所述。
  • t0 (int, optional, defaults to 44) — 时间步 t0。应在 [0, num_inference_steps - 1] 范围内。请参阅论文,第 3.3.1 节。
  • t1 (int, optional, defaults to 47) — 时间步 t0。应在 [t0 + 1, num_inference_steps - 1] 范围内。请参阅论文,第 3.3.1 节。

调用管道进行生成时调用的函数。

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]的潜在量。
  • timesteps — 执行反向过程的时间步。
  • prompt_embeds — 预生成的文本嵌入。
  • guidance_scale — 较高的指导比例值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时启用指导比例。
  • callback (Callable, optional) — 在推理过程中,每 callback_steps 步调用的函数。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, optional, defaults to 1) — 调用 callback 函数的频率。如果未指定,则在每一步都调用回调。
  • extra_step_kwargs — 额外步长kwargs。
  • cross_attention_kwargs — 如果指定,此 kwargs 字典将传递给 self.processor 中定义的 AttentionProcessor
  • num_warmup_steps — 热身步数。

返回

latents

在时间步timesteps[-1]反向过程的潜在量

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

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 (str or List[str], optional) — 要编码的提示词
  • prompt_2 (str or List[str], optional) — 要发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,prompt 将用于两个文本编码器。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由指导
  • negative_prompt (str or List[str], optional) — 不用于指导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。当不使用指导时(即,如果 guidance_scale 小于 1),则忽略。
  • negative_prompt_2 (str or List[str], optional) — 不用于指导图像生成并发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则 negative_prompt 将用于两个文本编码器。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,负向提示词嵌入将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则池化文本嵌入将从 prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,负向池化文本嵌入将从 negative_prompt 输入参数生成。
  • lora_scale (float, optional) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, optional) — 在计算提示词嵌入时要跳过的 CLIP 层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。

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

forward_loop

< >

( x_t0 t0 t1 generator ) x_t1

参数

  • x_t0 — 时间 t0 的潜在代码。
  • t0 — 时间步 t0。
  • t1 — 时间步 t1。
  • generator (torch.Generator or List[torch.Generator], optional) — 一个 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]) — 去噪后的 PIL 图像列表,长度为 batch_size,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • nsfw_content_detected ([List[bool]]) — 表示相应生成的图像是否包含“不安全工作”(nsfw)内容的列表,如果无法执行安全检查,则为 None

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

< > 在 GitHub 上更新