Spaces:
Running
on
Zero
Running
on
Zero
Upload 6 files
Browse files- CogVideoX/README.md +19 -0
- CogVideoX/cli.py +90 -0
- CogVideoX/pipeline_rgba.py +744 -0
- CogVideoX/rgba_utils.py +313 -0
- CogVideoX/test.py +26 -0
- app.py +323 -0
CogVideoX/README.md
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Getting Started
|
2 |
+
|
3 |
+
Download the corresponding pre-trained LoRA weights from the [model zoo](https://github.com/lwang592/TransPixar/README.md##model-zoo).
|
4 |
+
|
5 |
+
## Inference
|
6 |
+
|
7 |
+
To generate the RGBA video, run:
|
8 |
+
|
9 |
+
```bash
|
10 |
+
python cli.py \
|
11 |
+
--lora_path /path/to/lora \
|
12 |
+
--prompt "..." \
|
13 |
+
```
|
14 |
+
|
15 |
+
This command generates the RGB and Alpha videos simultaneously and saves them. Specifically, the RGB video is saved in its premultiplied form. To blend this video with any background image, you can simply use the following formula:
|
16 |
+
|
17 |
+
```python
|
18 |
+
com = rgb + (1 - alpha) * bgr
|
19 |
+
```
|
CogVideoX/cli.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
from diffusers import CogVideoXDPMScheduler
|
4 |
+
from pipeline_rgba import CogVideoXPipeline
|
5 |
+
from diffusers.utils import export_to_video
|
6 |
+
import argparse
|
7 |
+
import numpy as np
|
8 |
+
from rgba_utils import *
|
9 |
+
|
10 |
+
def main(args):
|
11 |
+
# 1. load pipeline
|
12 |
+
pipe = CogVideoXPipeline.from_pretrained(args.model_path, torch_dtype=torch.bfloat16)
|
13 |
+
pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
|
14 |
+
pipe.enable_sequential_cpu_offload()
|
15 |
+
pipe.vae.enable_slicing()
|
16 |
+
pipe.vae.enable_tiling()
|
17 |
+
|
18 |
+
|
19 |
+
# 2. define prompt and arguments
|
20 |
+
pipeline_args = {
|
21 |
+
"prompt": args.prompt,
|
22 |
+
"guidance_scale": args.guidance_scale,
|
23 |
+
"num_inference_steps": args.num_inference_steps,
|
24 |
+
"height": args.height,
|
25 |
+
"width": args.width,
|
26 |
+
"num_frames": args.num_frames,
|
27 |
+
"output_type": "latent",
|
28 |
+
"use_dynamic_cfg":True,
|
29 |
+
}
|
30 |
+
|
31 |
+
# 3. prepare rgbx utils
|
32 |
+
# breakpoint()
|
33 |
+
seq_length = 2 * (
|
34 |
+
(args.height // pipe.vae_scale_factor_spatial // 2)
|
35 |
+
* (args.width // pipe.vae_scale_factor_spatial // 2)
|
36 |
+
* ((args.num_frames - 1) // pipe.vae_scale_factor_temporal + 1)
|
37 |
+
)
|
38 |
+
# seq_length = 35100
|
39 |
+
|
40 |
+
prepare_for_rgba_inference(
|
41 |
+
pipe.transformer,
|
42 |
+
rgba_weights_path=args.lora_path,
|
43 |
+
device="cuda",
|
44 |
+
dtype=torch.bfloat16,
|
45 |
+
text_length=226,
|
46 |
+
seq_length=seq_length, # this is for the creation of attention mask.
|
47 |
+
)
|
48 |
+
|
49 |
+
# 4. run inference
|
50 |
+
generator = torch.manual_seed(args.seed) if args.seed else None
|
51 |
+
frames_latents = pipe(**pipeline_args, generator=generator).frames
|
52 |
+
|
53 |
+
frames_latents_rgb, frames_latents_alpha = frames_latents.chunk(2, dim=1)
|
54 |
+
|
55 |
+
frames_rgb = decode_latents(pipe, frames_latents_rgb)
|
56 |
+
frames_alpha = decode_latents(pipe, frames_latents_alpha)
|
57 |
+
|
58 |
+
|
59 |
+
pooled_alpha = np.max(frames_alpha, axis=-1, keepdims=True)
|
60 |
+
frames_alpha_pooled = np.repeat(pooled_alpha, 3, axis=-1)
|
61 |
+
premultiplied_rgb = frames_rgb * frames_alpha_pooled
|
62 |
+
|
63 |
+
if os.path.exists(args.output_path) == False:
|
64 |
+
os.makedirs(args.output_path)
|
65 |
+
|
66 |
+
export_to_video(premultiplied_rgb[0], os.path.join(args.output_path, "rgb.mp4"), fps=args.fps)
|
67 |
+
export_to_video(frames_alpha[0], os.path.join(args.output_path, "alpha.mp4"), fps=args.fps)
|
68 |
+
|
69 |
+
|
70 |
+
if __name__ == "__main__":
|
71 |
+
parser = argparse.ArgumentParser(description="Generate a video from a text prompt")
|
72 |
+
parser.add_argument("--prompt", type=str, required=True, help="The description of the video to be generated")
|
73 |
+
parser.add_argument("--lora_path", type=str, default="/hpc2hdd/home/lwang592/projects/CogVideo/sat/outputs/training/ckpts-5b-attn_rebias-partial_lora-8gpu-wo_t2a/lora-rgba-12-21-19-11/5000/rgba_lora.safetensors", help="The path of the LoRA weights to be used")
|
74 |
+
|
75 |
+
parser.add_argument(
|
76 |
+
"--model_path", type=str, default="THUDM/CogVideoX-5B", help="Path of the pre-trained model use"
|
77 |
+
)
|
78 |
+
|
79 |
+
|
80 |
+
parser.add_argument("--output_path", type=str, default="./output", help="The path save generated video")
|
81 |
+
parser.add_argument("--guidance_scale", type=float, default=6.0, help="The scale for classifier-free guidance")
|
82 |
+
parser.add_argument("--num_inference_steps", type=int, default=50, help="Inference steps")
|
83 |
+
parser.add_argument("--num_frames", type=int, default=49, help="Number of steps for the inference process")
|
84 |
+
parser.add_argument("--width", type=int, default=720, help="Number of steps for the inference process")
|
85 |
+
parser.add_argument("--height", type=int, default=480, help="Number of steps for the inference process")
|
86 |
+
parser.add_argument("--fps", type=int, default=8, help="Number of steps for the inference process")
|
87 |
+
parser.add_argument("--seed", type=int, default=None, help="The seed for reproducibility")
|
88 |
+
args = parser.parse_args()
|
89 |
+
|
90 |
+
main(args)
|
CogVideoX/pipeline_rgba.py
ADDED
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
|
2 |
+
# All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
import inspect
|
17 |
+
import math
|
18 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
19 |
+
|
20 |
+
import torch
|
21 |
+
from transformers import T5EncoderModel, T5Tokenizer
|
22 |
+
|
23 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
24 |
+
from diffusers.loaders import CogVideoXLoraLoaderMixin
|
25 |
+
from diffusers.models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
|
26 |
+
from diffusers.models.embeddings import get_3d_rotary_pos_embed
|
27 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
28 |
+
from diffusers.schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
|
29 |
+
from diffusers.utils import logging, replace_example_docstring
|
30 |
+
from diffusers.utils.torch_utils import randn_tensor
|
31 |
+
from diffusers.video_processor import VideoProcessor
|
32 |
+
from diffusers.pipelines.cogvideo.pipeline_output import CogVideoXPipelineOutput
|
33 |
+
|
34 |
+
|
35 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
36 |
+
|
37 |
+
|
38 |
+
EXAMPLE_DOC_STRING = """
|
39 |
+
Examples:
|
40 |
+
```python
|
41 |
+
>>> import torch
|
42 |
+
>>> from diffusers import CogVideoXPipeline
|
43 |
+
>>> from diffusers.utils import export_to_video
|
44 |
+
|
45 |
+
>>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
|
46 |
+
>>> pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16).to("cuda")
|
47 |
+
>>> prompt = (
|
48 |
+
... "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
|
49 |
+
... "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
|
50 |
+
... "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
|
51 |
+
... "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
|
52 |
+
... "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
|
53 |
+
... "atmosphere of this unique musical performance."
|
54 |
+
... )
|
55 |
+
>>> video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
|
56 |
+
>>> export_to_video(video, "output.mp4", fps=8)
|
57 |
+
```
|
58 |
+
"""
|
59 |
+
|
60 |
+
|
61 |
+
# Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid
|
62 |
+
def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
|
63 |
+
tw = tgt_width
|
64 |
+
th = tgt_height
|
65 |
+
h, w = src
|
66 |
+
r = h / w
|
67 |
+
if r > (th / tw):
|
68 |
+
resize_height = th
|
69 |
+
resize_width = int(round(th / h * w))
|
70 |
+
else:
|
71 |
+
resize_width = tw
|
72 |
+
resize_height = int(round(tw / w * h))
|
73 |
+
|
74 |
+
crop_top = int(round((th - resize_height) / 2.0))
|
75 |
+
crop_left = int(round((tw - resize_width) / 2.0))
|
76 |
+
|
77 |
+
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
|
78 |
+
|
79 |
+
|
80 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
81 |
+
def retrieve_timesteps(
|
82 |
+
scheduler,
|
83 |
+
num_inference_steps: Optional[int] = None,
|
84 |
+
device: Optional[Union[str, torch.device]] = None,
|
85 |
+
timesteps: Optional[List[int]] = None,
|
86 |
+
sigmas: Optional[List[float]] = None,
|
87 |
+
**kwargs,
|
88 |
+
):
|
89 |
+
r"""
|
90 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
91 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
92 |
+
|
93 |
+
Args:
|
94 |
+
scheduler (`SchedulerMixin`):
|
95 |
+
The scheduler to get timesteps from.
|
96 |
+
num_inference_steps (`int`):
|
97 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
98 |
+
must be `None`.
|
99 |
+
device (`str` or `torch.device`, *optional*):
|
100 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
101 |
+
timesteps (`List[int]`, *optional*):
|
102 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
103 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
104 |
+
sigmas (`List[float]`, *optional*):
|
105 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
106 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
107 |
+
|
108 |
+
Returns:
|
109 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
110 |
+
second element is the number of inference steps.
|
111 |
+
"""
|
112 |
+
if timesteps is not None and sigmas is not None:
|
113 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
114 |
+
if timesteps is not None:
|
115 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
116 |
+
if not accepts_timesteps:
|
117 |
+
raise ValueError(
|
118 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
119 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
120 |
+
)
|
121 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
122 |
+
timesteps = scheduler.timesteps
|
123 |
+
num_inference_steps = len(timesteps)
|
124 |
+
elif sigmas is not None:
|
125 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
126 |
+
if not accept_sigmas:
|
127 |
+
raise ValueError(
|
128 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
129 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
130 |
+
)
|
131 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
132 |
+
timesteps = scheduler.timesteps
|
133 |
+
num_inference_steps = len(timesteps)
|
134 |
+
else:
|
135 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
136 |
+
timesteps = scheduler.timesteps
|
137 |
+
return timesteps, num_inference_steps
|
138 |
+
|
139 |
+
|
140 |
+
class CogVideoXPipeline(DiffusionPipeline, CogVideoXLoraLoaderMixin):
|
141 |
+
r"""
|
142 |
+
Pipeline for text-to-video generation using CogVideoX.
|
143 |
+
|
144 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
145 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
146 |
+
|
147 |
+
Args:
|
148 |
+
vae ([`AutoencoderKL`]):
|
149 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
150 |
+
text_encoder ([`T5EncoderModel`]):
|
151 |
+
Frozen text-encoder. CogVideoX uses
|
152 |
+
[T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
|
153 |
+
[t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
|
154 |
+
tokenizer (`T5Tokenizer`):
|
155 |
+
Tokenizer of class
|
156 |
+
[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
|
157 |
+
transformer ([`CogVideoXTransformer3DModel`]):
|
158 |
+
A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents.
|
159 |
+
scheduler ([`SchedulerMixin`]):
|
160 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
|
161 |
+
"""
|
162 |
+
|
163 |
+
_optional_components = []
|
164 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
165 |
+
|
166 |
+
_callback_tensor_inputs = [
|
167 |
+
"latents",
|
168 |
+
"prompt_embeds",
|
169 |
+
"negative_prompt_embeds",
|
170 |
+
]
|
171 |
+
|
172 |
+
def __init__(
|
173 |
+
self,
|
174 |
+
tokenizer: T5Tokenizer,
|
175 |
+
text_encoder: T5EncoderModel,
|
176 |
+
vae: AutoencoderKLCogVideoX,
|
177 |
+
transformer: CogVideoXTransformer3DModel,
|
178 |
+
scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
|
179 |
+
):
|
180 |
+
super().__init__()
|
181 |
+
|
182 |
+
self.register_modules(
|
183 |
+
tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler
|
184 |
+
)
|
185 |
+
self.vae_scale_factor_spatial = (
|
186 |
+
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
|
187 |
+
)
|
188 |
+
self.vae_scale_factor_temporal = (
|
189 |
+
self.vae.config.temporal_compression_ratio if hasattr(self, "vae") and self.vae is not None else 4
|
190 |
+
)
|
191 |
+
self.vae_scaling_factor_image = (
|
192 |
+
self.vae.config.scaling_factor if hasattr(self, "vae") and self.vae is not None else 0.7
|
193 |
+
)
|
194 |
+
|
195 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
196 |
+
|
197 |
+
def _get_t5_prompt_embeds(
|
198 |
+
self,
|
199 |
+
prompt: Union[str, List[str]] = None,
|
200 |
+
num_videos_per_prompt: int = 1,
|
201 |
+
max_sequence_length: int = 226,
|
202 |
+
device: Optional[torch.device] = None,
|
203 |
+
dtype: Optional[torch.dtype] = None,
|
204 |
+
):
|
205 |
+
device = device or self._execution_device
|
206 |
+
dtype = dtype or self.text_encoder.dtype
|
207 |
+
|
208 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
209 |
+
batch_size = len(prompt)
|
210 |
+
|
211 |
+
text_inputs = self.tokenizer(
|
212 |
+
prompt,
|
213 |
+
padding="max_length",
|
214 |
+
max_length=max_sequence_length,
|
215 |
+
truncation=True,
|
216 |
+
add_special_tokens=True,
|
217 |
+
return_tensors="pt",
|
218 |
+
)
|
219 |
+
text_input_ids = text_inputs.input_ids
|
220 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
221 |
+
|
222 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
223 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
|
224 |
+
logger.warning(
|
225 |
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
226 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
227 |
+
)
|
228 |
+
|
229 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
|
230 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
231 |
+
|
232 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
233 |
+
_, seq_len, _ = prompt_embeds.shape
|
234 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
235 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
236 |
+
|
237 |
+
return prompt_embeds
|
238 |
+
|
239 |
+
def encode_prompt(
|
240 |
+
self,
|
241 |
+
prompt: Union[str, List[str]],
|
242 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
243 |
+
do_classifier_free_guidance: bool = True,
|
244 |
+
num_videos_per_prompt: int = 1,
|
245 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
246 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
247 |
+
max_sequence_length: int = 226,
|
248 |
+
device: Optional[torch.device] = None,
|
249 |
+
dtype: Optional[torch.dtype] = None,
|
250 |
+
):
|
251 |
+
r"""
|
252 |
+
Encodes the prompt into text encoder hidden states.
|
253 |
+
|
254 |
+
Args:
|
255 |
+
prompt (`str` or `List[str]`, *optional*):
|
256 |
+
prompt to be encoded
|
257 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
258 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
259 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
260 |
+
less than `1`).
|
261 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
262 |
+
Whether to use classifier free guidance or not.
|
263 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
264 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
265 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
266 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
267 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
268 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
269 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
270 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
271 |
+
argument.
|
272 |
+
device: (`torch.device`, *optional*):
|
273 |
+
torch device
|
274 |
+
dtype: (`torch.dtype`, *optional*):
|
275 |
+
torch dtype
|
276 |
+
"""
|
277 |
+
device = device or self._execution_device
|
278 |
+
|
279 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
280 |
+
if prompt is not None:
|
281 |
+
batch_size = len(prompt)
|
282 |
+
else:
|
283 |
+
batch_size = prompt_embeds.shape[0]
|
284 |
+
|
285 |
+
if prompt_embeds is None:
|
286 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
287 |
+
prompt=prompt,
|
288 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
289 |
+
max_sequence_length=max_sequence_length,
|
290 |
+
device=device,
|
291 |
+
dtype=dtype,
|
292 |
+
)
|
293 |
+
|
294 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
295 |
+
negative_prompt = negative_prompt or ""
|
296 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
297 |
+
|
298 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
299 |
+
raise TypeError(
|
300 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
301 |
+
f" {type(prompt)}."
|
302 |
+
)
|
303 |
+
elif batch_size != len(negative_prompt):
|
304 |
+
raise ValueError(
|
305 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
306 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
307 |
+
" the batch size of `prompt`."
|
308 |
+
)
|
309 |
+
|
310 |
+
negative_prompt_embeds = self._get_t5_prompt_embeds(
|
311 |
+
prompt=negative_prompt,
|
312 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
313 |
+
max_sequence_length=max_sequence_length,
|
314 |
+
device=device,
|
315 |
+
dtype=dtype,
|
316 |
+
)
|
317 |
+
|
318 |
+
return prompt_embeds, negative_prompt_embeds
|
319 |
+
|
320 |
+
def prepare_latents(
|
321 |
+
self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
|
322 |
+
):
|
323 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
324 |
+
raise ValueError(
|
325 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
326 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
327 |
+
)
|
328 |
+
|
329 |
+
shape = (
|
330 |
+
batch_size,
|
331 |
+
(num_frames - 1) // self.vae_scale_factor_temporal + 1,
|
332 |
+
num_channels_latents,
|
333 |
+
height // self.vae_scale_factor_spatial,
|
334 |
+
width // self.vae_scale_factor_spatial,
|
335 |
+
)
|
336 |
+
|
337 |
+
if latents is None:
|
338 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
339 |
+
else:
|
340 |
+
latents = latents.to(device)
|
341 |
+
|
342 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
343 |
+
latents = latents * self.scheduler.init_noise_sigma
|
344 |
+
return latents
|
345 |
+
|
346 |
+
def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
|
347 |
+
latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width]
|
348 |
+
latents = 1 / self.vae_scaling_factor_image * latents
|
349 |
+
|
350 |
+
frames = self.vae.decode(latents).sample
|
351 |
+
return frames
|
352 |
+
|
353 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
354 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
355 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
356 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
357 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
358 |
+
# and should be between [0, 1]
|
359 |
+
|
360 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
361 |
+
extra_step_kwargs = {}
|
362 |
+
if accepts_eta:
|
363 |
+
extra_step_kwargs["eta"] = eta
|
364 |
+
|
365 |
+
# check if the scheduler accepts generator
|
366 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
367 |
+
if accepts_generator:
|
368 |
+
extra_step_kwargs["generator"] = generator
|
369 |
+
return extra_step_kwargs
|
370 |
+
|
371 |
+
# Copied from diffusers.pipelines.latte.pipeline_latte.LattePipeline.check_inputs
|
372 |
+
def check_inputs(
|
373 |
+
self,
|
374 |
+
prompt,
|
375 |
+
height,
|
376 |
+
width,
|
377 |
+
negative_prompt,
|
378 |
+
callback_on_step_end_tensor_inputs,
|
379 |
+
prompt_embeds=None,
|
380 |
+
negative_prompt_embeds=None,
|
381 |
+
):
|
382 |
+
if height % 8 != 0 or width % 8 != 0:
|
383 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
384 |
+
|
385 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
386 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
387 |
+
):
|
388 |
+
raise ValueError(
|
389 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
390 |
+
)
|
391 |
+
if prompt is not None and prompt_embeds is not None:
|
392 |
+
raise ValueError(
|
393 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
394 |
+
" only forward one of the two."
|
395 |
+
)
|
396 |
+
elif prompt is None and prompt_embeds is None:
|
397 |
+
raise ValueError(
|
398 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
399 |
+
)
|
400 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
401 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
402 |
+
|
403 |
+
if prompt is not None and negative_prompt_embeds is not None:
|
404 |
+
raise ValueError(
|
405 |
+
f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
|
406 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
407 |
+
)
|
408 |
+
|
409 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
410 |
+
raise ValueError(
|
411 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
412 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
413 |
+
)
|
414 |
+
|
415 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
416 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
417 |
+
raise ValueError(
|
418 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
419 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
420 |
+
f" {negative_prompt_embeds.shape}."
|
421 |
+
)
|
422 |
+
|
423 |
+
def fuse_qkv_projections(self) -> None:
|
424 |
+
r"""Enables fused QKV projections."""
|
425 |
+
self.fusing_transformer = True
|
426 |
+
self.transformer.fuse_qkv_projections()
|
427 |
+
|
428 |
+
def unfuse_qkv_projections(self) -> None:
|
429 |
+
r"""Disable QKV projection fusion if enabled."""
|
430 |
+
if not self.fusing_transformer:
|
431 |
+
logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.")
|
432 |
+
else:
|
433 |
+
self.transformer.unfuse_qkv_projections()
|
434 |
+
self.fusing_transformer = False
|
435 |
+
|
436 |
+
def _prepare_rotary_positional_embeddings(
|
437 |
+
self,
|
438 |
+
height: int,
|
439 |
+
width: int,
|
440 |
+
num_frames: int,
|
441 |
+
device: torch.device,
|
442 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
443 |
+
grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
|
444 |
+
grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
|
445 |
+
base_size_width = 720 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
|
446 |
+
base_size_height = 480 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
|
447 |
+
|
448 |
+
grid_crops_coords = get_resize_crop_region_for_grid(
|
449 |
+
(grid_height, grid_width), base_size_width, base_size_height
|
450 |
+
)
|
451 |
+
freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
|
452 |
+
embed_dim=self.transformer.config.attention_head_dim,
|
453 |
+
crops_coords=grid_crops_coords,
|
454 |
+
grid_size=(grid_height, grid_width),
|
455 |
+
temporal_size=num_frames,
|
456 |
+
)
|
457 |
+
|
458 |
+
freqs_cos = freqs_cos.to(device=device)
|
459 |
+
freqs_sin = freqs_sin.to(device=device)
|
460 |
+
return freqs_cos, freqs_sin
|
461 |
+
|
462 |
+
@property
|
463 |
+
def guidance_scale(self):
|
464 |
+
return self._guidance_scale
|
465 |
+
|
466 |
+
@property
|
467 |
+
def num_timesteps(self):
|
468 |
+
return self._num_timesteps
|
469 |
+
|
470 |
+
@property
|
471 |
+
def attention_kwargs(self):
|
472 |
+
return self._attention_kwargs
|
473 |
+
|
474 |
+
@property
|
475 |
+
def interrupt(self):
|
476 |
+
return self._interrupt
|
477 |
+
|
478 |
+
@torch.no_grad()
|
479 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
480 |
+
def __call__(
|
481 |
+
self,
|
482 |
+
prompt: Optional[Union[str, List[str]]] = None,
|
483 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
484 |
+
height: int = 480,
|
485 |
+
width: int = 720,
|
486 |
+
num_frames: int = 49,
|
487 |
+
num_inference_steps: int = 50,
|
488 |
+
timesteps: Optional[List[int]] = None,
|
489 |
+
guidance_scale: float = 6,
|
490 |
+
use_dynamic_cfg: bool = False,
|
491 |
+
num_videos_per_prompt: int = 1,
|
492 |
+
eta: float = 0.0,
|
493 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
494 |
+
latents: Optional[torch.FloatTensor] = None,
|
495 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
496 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
497 |
+
output_type: str = "pil",
|
498 |
+
return_dict: bool = True,
|
499 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
500 |
+
callback_on_step_end: Optional[
|
501 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
502 |
+
] = None,
|
503 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
504 |
+
max_sequence_length: int = 226,
|
505 |
+
) -> Union[CogVideoXPipelineOutput, Tuple]:
|
506 |
+
"""
|
507 |
+
Function invoked when calling the pipeline for generation.
|
508 |
+
|
509 |
+
Args:
|
510 |
+
prompt (`str` or `List[str]`, *optional*):
|
511 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
512 |
+
instead.
|
513 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
514 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
515 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
516 |
+
less than `1`).
|
517 |
+
height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
|
518 |
+
The height in pixels of the generated image. This is set to 480 by default for the best results.
|
519 |
+
width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
|
520 |
+
The width in pixels of the generated image. This is set to 720 by default for the best results.
|
521 |
+
num_frames (`int`, defaults to `48`):
|
522 |
+
Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
|
523 |
+
contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where
|
524 |
+
num_seconds is 6 and fps is 8. However, since videos can be saved at any fps, the only condition that
|
525 |
+
needs to be satisfied is that of divisibility mentioned above.
|
526 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
527 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
528 |
+
expense of slower inference.
|
529 |
+
timesteps (`List[int]`, *optional*):
|
530 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
531 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
532 |
+
passed will be used. Must be in descending order.
|
533 |
+
guidance_scale (`float`, *optional*, defaults to 7.0):
|
534 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
535 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
536 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
537 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
538 |
+
usually at the expense of lower image quality.
|
539 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
540 |
+
The number of videos to generate per prompt.
|
541 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
542 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
543 |
+
to make generation deterministic.
|
544 |
+
latents (`torch.FloatTensor`, *optional*):
|
545 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
546 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
547 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
548 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
549 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
550 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
551 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
552 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
553 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
554 |
+
argument.
|
555 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
556 |
+
The output format of the generate image. Choose between
|
557 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
558 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
559 |
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
560 |
+
of a plain tuple.
|
561 |
+
attention_kwargs (`dict`, *optional*):
|
562 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
563 |
+
`self.processor` in
|
564 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
565 |
+
callback_on_step_end (`Callable`, *optional*):
|
566 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
567 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
568 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
569 |
+
`callback_on_step_end_tensor_inputs`.
|
570 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
571 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
572 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
573 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
574 |
+
max_sequence_length (`int`, defaults to `226`):
|
575 |
+
Maximum sequence length in encoded prompt. Must be consistent with
|
576 |
+
`self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
|
577 |
+
|
578 |
+
Examples:
|
579 |
+
|
580 |
+
Returns:
|
581 |
+
[`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] or `tuple`:
|
582 |
+
[`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
|
583 |
+
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
584 |
+
"""
|
585 |
+
|
586 |
+
if num_frames > 49:
|
587 |
+
raise ValueError(
|
588 |
+
"The number of frames must be less than 49 for now due to static positional embeddings. This will be updated in the future to remove this limitation."
|
589 |
+
)
|
590 |
+
|
591 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
592 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
593 |
+
|
594 |
+
num_videos_per_prompt = 1
|
595 |
+
|
596 |
+
# 1. Check inputs. Raise error if not correct
|
597 |
+
self.check_inputs(
|
598 |
+
prompt,
|
599 |
+
height,
|
600 |
+
width,
|
601 |
+
negative_prompt,
|
602 |
+
callback_on_step_end_tensor_inputs,
|
603 |
+
prompt_embeds,
|
604 |
+
negative_prompt_embeds,
|
605 |
+
)
|
606 |
+
self._guidance_scale = guidance_scale
|
607 |
+
self._attention_kwargs = attention_kwargs
|
608 |
+
self._interrupt = False
|
609 |
+
|
610 |
+
# 2. Default call parameters
|
611 |
+
if prompt is not None and isinstance(prompt, str):
|
612 |
+
batch_size = 1
|
613 |
+
elif prompt is not None and isinstance(prompt, list):
|
614 |
+
batch_size = len(prompt)
|
615 |
+
else:
|
616 |
+
batch_size = prompt_embeds.shape[0]
|
617 |
+
|
618 |
+
device = self._execution_device
|
619 |
+
|
620 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
621 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
622 |
+
# corresponds to doing no classifier free guidance.
|
623 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
624 |
+
|
625 |
+
# 3. Encode input prompt
|
626 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
627 |
+
prompt,
|
628 |
+
negative_prompt,
|
629 |
+
do_classifier_free_guidance,
|
630 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
631 |
+
prompt_embeds=prompt_embeds,
|
632 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
633 |
+
max_sequence_length=max_sequence_length,
|
634 |
+
device=device,
|
635 |
+
)
|
636 |
+
if do_classifier_free_guidance:
|
637 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
638 |
+
|
639 |
+
# 4. Prepare timesteps
|
640 |
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
641 |
+
self._num_timesteps = len(timesteps)
|
642 |
+
|
643 |
+
# 5. Prepare latents.
|
644 |
+
latent_channels = self.transformer.config.in_channels
|
645 |
+
latents = self.prepare_latents(
|
646 |
+
batch_size * num_videos_per_prompt,
|
647 |
+
latent_channels,
|
648 |
+
num_frames,
|
649 |
+
height,
|
650 |
+
width,
|
651 |
+
prompt_embeds.dtype,
|
652 |
+
device,
|
653 |
+
generator,
|
654 |
+
latents,
|
655 |
+
).repeat(1,2,1,1,1) # Luozhou
|
656 |
+
|
657 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
658 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
659 |
+
|
660 |
+
# 7. Create rotary embeds if required
|
661 |
+
image_rotary_emb = (
|
662 |
+
self._prepare_rotary_positional_embeddings(height, width, latents.size(1) // 2, device) # Luozhou
|
663 |
+
if self.transformer.config.use_rotary_positional_embeddings
|
664 |
+
else None
|
665 |
+
)
|
666 |
+
|
667 |
+
# 8. Denoising loop
|
668 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
669 |
+
|
670 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
671 |
+
# for DPM-solver++
|
672 |
+
old_pred_original_sample = None
|
673 |
+
for i, t in enumerate(timesteps):
|
674 |
+
if self.interrupt:
|
675 |
+
continue
|
676 |
+
|
677 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
678 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
679 |
+
|
680 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
681 |
+
timestep = t.expand(latent_model_input.shape[0])
|
682 |
+
|
683 |
+
# predict noise model_output
|
684 |
+
noise_pred = self.transformer(
|
685 |
+
hidden_states=latent_model_input,
|
686 |
+
encoder_hidden_states=prompt_embeds,
|
687 |
+
timestep=timestep,
|
688 |
+
image_rotary_emb=image_rotary_emb,
|
689 |
+
attention_kwargs=attention_kwargs,
|
690 |
+
return_dict=False,
|
691 |
+
)[0]
|
692 |
+
noise_pred = noise_pred.float()
|
693 |
+
|
694 |
+
# perform guidance
|
695 |
+
if use_dynamic_cfg:
|
696 |
+
self._guidance_scale = 1 + guidance_scale * (
|
697 |
+
(1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
|
698 |
+
)
|
699 |
+
if do_classifier_free_guidance:
|
700 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
701 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
702 |
+
|
703 |
+
# compute the previous noisy sample x_t -> x_t-1
|
704 |
+
if not isinstance(self.scheduler, CogVideoXDPMScheduler):
|
705 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
706 |
+
else:
|
707 |
+
latents, old_pred_original_sample = self.scheduler.step(
|
708 |
+
noise_pred,
|
709 |
+
old_pred_original_sample,
|
710 |
+
t,
|
711 |
+
timesteps[i - 1] if i > 0 else None,
|
712 |
+
latents,
|
713 |
+
**extra_step_kwargs,
|
714 |
+
return_dict=False,
|
715 |
+
)
|
716 |
+
latents = latents.to(prompt_embeds.dtype)
|
717 |
+
|
718 |
+
# call the callback, if provided
|
719 |
+
if callback_on_step_end is not None:
|
720 |
+
callback_kwargs = {}
|
721 |
+
for k in callback_on_step_end_tensor_inputs:
|
722 |
+
callback_kwargs[k] = locals()[k]
|
723 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
724 |
+
|
725 |
+
latents = callback_outputs.pop("latents", latents)
|
726 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
727 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
728 |
+
|
729 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
730 |
+
progress_bar.update()
|
731 |
+
|
732 |
+
if not output_type == "latent":
|
733 |
+
video = self.decode_latents(latents)
|
734 |
+
video = self.video_processor.postprocess_video(video=video, output_type=output_type)
|
735 |
+
else:
|
736 |
+
video = latents
|
737 |
+
|
738 |
+
# Offload all models
|
739 |
+
self.maybe_free_model_hooks()
|
740 |
+
|
741 |
+
if not return_dict:
|
742 |
+
return (video,)
|
743 |
+
|
744 |
+
return CogVideoXPipelineOutput(frames=video)
|
CogVideoX/rgba_utils.py
ADDED
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
5 |
+
from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
|
6 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
7 |
+
from safetensors.torch import load_file
|
8 |
+
|
9 |
+
logger = logging.get_logger(__name__)
|
10 |
+
|
11 |
+
@torch.no_grad()
|
12 |
+
def decode_latents(pipe, latents):
|
13 |
+
video = pipe.decode_latents(latents)
|
14 |
+
video = pipe.video_processor.postprocess_video(video=video, output_type="np")
|
15 |
+
return video
|
16 |
+
|
17 |
+
def create_attention_mask(text_length: int, seq_length: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
18 |
+
"""
|
19 |
+
Create an attention mask to block text from attending to alpha.
|
20 |
+
|
21 |
+
Args:
|
22 |
+
text_length: Length of the text sequence.
|
23 |
+
seq_length: Length of the other sequence.
|
24 |
+
device: The device where the mask will be stored.
|
25 |
+
dtype: The data type of the mask tensor.
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
An attention mask tensor.
|
29 |
+
"""
|
30 |
+
total_length = text_length + seq_length
|
31 |
+
dense_mask = torch.ones((total_length, total_length), dtype=torch.bool)
|
32 |
+
dense_mask[:text_length, text_length + seq_length // 2:] = False
|
33 |
+
return dense_mask.to(device=device, dtype=dtype)
|
34 |
+
|
35 |
+
class RGBALoRACogVideoXAttnProcessor:
|
36 |
+
r"""
|
37 |
+
Processor for implementing scaled dot-product attention for the CogVideoX model.
|
38 |
+
It applies a rotary embedding on query and key vectors, but does not include spatial normalization.
|
39 |
+
"""
|
40 |
+
|
41 |
+
def __init__(self, device, dtype, attention_mask, lora_rank=128, lora_alpha=1.0, latent_dim=3072):
|
42 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
43 |
+
raise ImportError("CogVideoXAttnProcessor requires PyTorch 2.0 or later.")
|
44 |
+
|
45 |
+
# Initialize LoRA layers
|
46 |
+
self.lora_alpha = lora_alpha
|
47 |
+
self.lora_rank = lora_rank
|
48 |
+
|
49 |
+
# Helper function to create LoRA layers
|
50 |
+
def create_lora_layer(in_dim, mid_dim, out_dim):
|
51 |
+
return nn.Sequential(
|
52 |
+
nn.Linear(in_dim, mid_dim, bias=False, device=device, dtype=dtype),
|
53 |
+
nn.Linear(mid_dim, out_dim, bias=False, device=device, dtype=dtype)
|
54 |
+
)
|
55 |
+
|
56 |
+
self.to_q_lora = create_lora_layer(latent_dim, lora_rank, latent_dim)
|
57 |
+
self.to_k_lora = create_lora_layer(latent_dim, lora_rank, latent_dim)
|
58 |
+
self.to_v_lora = create_lora_layer(latent_dim, lora_rank, latent_dim)
|
59 |
+
self.to_out_lora = create_lora_layer(latent_dim, lora_rank, latent_dim)
|
60 |
+
|
61 |
+
# Store attention mask
|
62 |
+
self.attention_mask = attention_mask
|
63 |
+
|
64 |
+
def _apply_lora(self, hidden_states, seq_len, query, key, value, scaling):
|
65 |
+
"""Applies LoRA updates to query, key, and value tensors."""
|
66 |
+
query_delta = self.to_q_lora(hidden_states).to(query.device)
|
67 |
+
query[:, -seq_len // 2:, :] += query_delta[:, -seq_len // 2:, :] * scaling
|
68 |
+
|
69 |
+
key_delta = self.to_k_lora(hidden_states).to(key.device)
|
70 |
+
key[:, -seq_len // 2:, :] += key_delta[:, -seq_len // 2:, :] * scaling
|
71 |
+
|
72 |
+
value_delta = self.to_v_lora(hidden_states).to(value.device)
|
73 |
+
value[:, -seq_len // 2:, :] += value_delta[:, -seq_len // 2:, :] * scaling
|
74 |
+
|
75 |
+
return query, key, value
|
76 |
+
|
77 |
+
def _apply_rotary_embedding(self, query, key, image_rotary_emb, seq_len, text_seq_length, attn):
|
78 |
+
"""Applies rotary embeddings to query and key tensors."""
|
79 |
+
from diffusers.models.embeddings import apply_rotary_emb
|
80 |
+
|
81 |
+
# Apply rotary embedding to RGB and alpha sections
|
82 |
+
query[:, :, text_seq_length:text_seq_length + seq_len // 2] = apply_rotary_emb(
|
83 |
+
query[:, :, text_seq_length:text_seq_length + seq_len // 2], image_rotary_emb)
|
84 |
+
query[:, :, text_seq_length + seq_len // 2:] = apply_rotary_emb(
|
85 |
+
query[:, :, text_seq_length + seq_len // 2:], image_rotary_emb)
|
86 |
+
|
87 |
+
if not attn.is_cross_attention:
|
88 |
+
key[:, :, text_seq_length:text_seq_length + seq_len // 2] = apply_rotary_emb(
|
89 |
+
key[:, :, text_seq_length:text_seq_length + seq_len // 2], image_rotary_emb)
|
90 |
+
key[:, :, text_seq_length + seq_len // 2:] = apply_rotary_emb(
|
91 |
+
key[:, :, text_seq_length + seq_len // 2:], image_rotary_emb)
|
92 |
+
|
93 |
+
return query, key
|
94 |
+
|
95 |
+
def __call__(
|
96 |
+
self,
|
97 |
+
attn,
|
98 |
+
hidden_states: torch.Tensor,
|
99 |
+
encoder_hidden_states: torch.Tensor,
|
100 |
+
attention_mask: Optional[torch.Tensor] = None,
|
101 |
+
image_rotary_emb: Optional[torch.Tensor] = None,
|
102 |
+
) -> torch.Tensor:
|
103 |
+
# Concatenate encoder and decoder hidden states
|
104 |
+
text_seq_length = encoder_hidden_states.size(1)
|
105 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
106 |
+
|
107 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
108 |
+
seq_len = hidden_states.shape[1] - text_seq_length
|
109 |
+
scaling = self.lora_alpha / self.lora_rank
|
110 |
+
|
111 |
+
# Apply LoRA to query, key, value
|
112 |
+
query = attn.to_q(hidden_states)
|
113 |
+
key = attn.to_k(hidden_states)
|
114 |
+
value = attn.to_v(hidden_states)
|
115 |
+
|
116 |
+
query, key, value = self._apply_lora(hidden_states, seq_len, query, key, value, scaling)
|
117 |
+
|
118 |
+
# Reshape query, key, value for multi-head attention
|
119 |
+
inner_dim = key.shape[-1]
|
120 |
+
head_dim = inner_dim // attn.heads
|
121 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
122 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
123 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
124 |
+
|
125 |
+
# Normalize query and key if required
|
126 |
+
if attn.norm_q is not None:
|
127 |
+
query = attn.norm_q(query)
|
128 |
+
if attn.norm_k is not None:
|
129 |
+
key = attn.norm_k(key)
|
130 |
+
|
131 |
+
# Apply rotary embeddings if provided
|
132 |
+
if image_rotary_emb is not None:
|
133 |
+
query, key = self._apply_rotary_embedding(query, key, image_rotary_emb, seq_len, text_seq_length, attn)
|
134 |
+
|
135 |
+
# Compute scaled dot-product attention
|
136 |
+
hidden_states = F.scaled_dot_product_attention(
|
137 |
+
query, key, value, attn_mask=self.attention_mask, dropout_p=0.0, is_causal=False
|
138 |
+
)
|
139 |
+
|
140 |
+
# Reshape the output tensor back to the original shape
|
141 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
142 |
+
|
143 |
+
# Apply linear projection and LoRA to the output
|
144 |
+
original_hidden_states = attn.to_out[0](hidden_states)
|
145 |
+
hidden_states_delta = self.to_out_lora(hidden_states).to(hidden_states.device)
|
146 |
+
original_hidden_states[:, -seq_len // 2:, :] += hidden_states_delta[:, -seq_len // 2:, :] * scaling
|
147 |
+
|
148 |
+
# Apply dropout
|
149 |
+
hidden_states = attn.to_out[1](original_hidden_states)
|
150 |
+
|
151 |
+
# Split back into encoder and decoder hidden states
|
152 |
+
encoder_hidden_states, hidden_states = hidden_states.split(
|
153 |
+
[text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
|
154 |
+
)
|
155 |
+
|
156 |
+
return hidden_states, encoder_hidden_states
|
157 |
+
|
158 |
+
def prepare_for_rgba_inference(
|
159 |
+
model, rgba_weights_path: str, device: torch.device, dtype: torch.dtype,
|
160 |
+
lora_rank: int = 128, lora_alpha: float = 1.0, text_length: int = 226, seq_length: int = 35100
|
161 |
+
):
|
162 |
+
def load_lora_sequential_weights(lora_layer, lora_layers, prefix):
|
163 |
+
lora_layer[0].load_state_dict({'weight': lora_layers[f"{prefix}.lora_A.weight"]})
|
164 |
+
lora_layer[1].load_state_dict({'weight': lora_layers[f"{prefix}.lora_B.weight"]})
|
165 |
+
|
166 |
+
|
167 |
+
rgba_weights = load_file(rgba_weights_path)
|
168 |
+
aux_emb = rgba_weights['domain_emb']
|
169 |
+
|
170 |
+
attention_mask = create_attention_mask(text_length, seq_length, device, dtype)
|
171 |
+
attn_procs = {}
|
172 |
+
|
173 |
+
for name in model.attn_processors.keys():
|
174 |
+
attn_processor = RGBALoRACogVideoXAttnProcessor(
|
175 |
+
device=device, dtype=dtype, attention_mask=attention_mask,
|
176 |
+
lora_rank=lora_rank, lora_alpha=lora_alpha
|
177 |
+
)
|
178 |
+
|
179 |
+
index = name.split('.')[1]
|
180 |
+
base_prefix = f'transformer.transformer_blocks.{index}.attn1'
|
181 |
+
|
182 |
+
for lora_layer, prefix in [
|
183 |
+
(attn_processor.to_q_lora, f'{base_prefix}.to_q'),
|
184 |
+
(attn_processor.to_k_lora, f'{base_prefix}.to_k'),
|
185 |
+
(attn_processor.to_v_lora, f'{base_prefix}.to_v'),
|
186 |
+
(attn_processor.to_out_lora, f'{base_prefix}.to_out.0'),
|
187 |
+
]:
|
188 |
+
load_lora_sequential_weights(lora_layer, rgba_weights, prefix)
|
189 |
+
|
190 |
+
attn_procs[name] = attn_processor
|
191 |
+
|
192 |
+
model.set_attn_processor(attn_procs)
|
193 |
+
|
194 |
+
def custom_forward(self):
|
195 |
+
def forward(
|
196 |
+
hidden_states: torch.Tensor,
|
197 |
+
encoder_hidden_states: torch.Tensor,
|
198 |
+
timestep: Union[int, float, torch.LongTensor],
|
199 |
+
timestep_cond: Optional[torch.Tensor] = None,
|
200 |
+
ofs: Optional[Union[int, float, torch.LongTensor]] = None,
|
201 |
+
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
202 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
203 |
+
return_dict: bool = True,
|
204 |
+
):
|
205 |
+
if attention_kwargs is not None:
|
206 |
+
attention_kwargs = attention_kwargs.copy()
|
207 |
+
lora_scale = attention_kwargs.pop("scale", 1.0)
|
208 |
+
else:
|
209 |
+
lora_scale = 1.0
|
210 |
+
|
211 |
+
if USE_PEFT_BACKEND:
|
212 |
+
# weight the lora layers by setting `lora_scale` for each PEFT layer
|
213 |
+
scale_lora_layers(self, lora_scale)
|
214 |
+
else:
|
215 |
+
if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
|
216 |
+
logger.warning(
|
217 |
+
"Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
|
218 |
+
)
|
219 |
+
|
220 |
+
batch_size, num_frames, channels, height, width = hidden_states.shape
|
221 |
+
|
222 |
+
# 1. Time embedding
|
223 |
+
timesteps = timestep
|
224 |
+
t_emb = self.time_proj(timesteps)
|
225 |
+
|
226 |
+
# timesteps does not contain any weights and will always return f32 tensors
|
227 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
228 |
+
# there might be better ways to encapsulate this.
|
229 |
+
t_emb = t_emb.to(dtype=hidden_states.dtype)
|
230 |
+
emb = self.time_embedding(t_emb, timestep_cond)
|
231 |
+
|
232 |
+
if self.ofs_embedding is not None:
|
233 |
+
ofs_emb = self.ofs_proj(ofs)
|
234 |
+
ofs_emb = ofs_emb.to(dtype=hidden_states.dtype)
|
235 |
+
ofs_emb = self.ofs_embedding(ofs_emb)
|
236 |
+
emb = emb + ofs_emb
|
237 |
+
|
238 |
+
# 2. Patch embedding
|
239 |
+
hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
|
240 |
+
hidden_states = self.embedding_dropout(hidden_states)
|
241 |
+
|
242 |
+
text_seq_length = encoder_hidden_states.shape[1]
|
243 |
+
encoder_hidden_states = hidden_states[:, :text_seq_length]
|
244 |
+
hidden_states = hidden_states[:, text_seq_length:]
|
245 |
+
|
246 |
+
hidden_states[:, hidden_states.size(1) // 2:, :] += aux_emb.expand(batch_size, -1, -1).to(hidden_states.device, dtype=hidden_states.dtype)
|
247 |
+
|
248 |
+
# 3. Transformer blocks
|
249 |
+
for i, block in enumerate(self.transformer_blocks):
|
250 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
251 |
+
|
252 |
+
def create_custom_forward(module):
|
253 |
+
def custom_forward(*inputs):
|
254 |
+
return module(*inputs)
|
255 |
+
|
256 |
+
return custom_forward
|
257 |
+
|
258 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
259 |
+
hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
|
260 |
+
create_custom_forward(block),
|
261 |
+
hidden_states,
|
262 |
+
encoder_hidden_states,
|
263 |
+
emb,
|
264 |
+
image_rotary_emb,
|
265 |
+
**ckpt_kwargs,
|
266 |
+
)
|
267 |
+
else:
|
268 |
+
hidden_states, encoder_hidden_states = block(
|
269 |
+
hidden_states=hidden_states,
|
270 |
+
encoder_hidden_states=encoder_hidden_states,
|
271 |
+
temb=emb,
|
272 |
+
image_rotary_emb=image_rotary_emb,
|
273 |
+
)
|
274 |
+
|
275 |
+
if not self.config.use_rotary_positional_embeddings:
|
276 |
+
# CogVideoX-2B
|
277 |
+
hidden_states = self.norm_final(hidden_states)
|
278 |
+
else:
|
279 |
+
# CogVideoX-5B
|
280 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
281 |
+
hidden_states = self.norm_final(hidden_states)
|
282 |
+
hidden_states = hidden_states[:, text_seq_length:]
|
283 |
+
|
284 |
+
# 4. Final block
|
285 |
+
hidden_states = self.norm_out(hidden_states, temb=emb)
|
286 |
+
hidden_states = self.proj_out(hidden_states)
|
287 |
+
|
288 |
+
# 5. Unpatchify
|
289 |
+
p = self.config.patch_size
|
290 |
+
p_t = self.config.patch_size_t
|
291 |
+
|
292 |
+
if p_t is None:
|
293 |
+
output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p)
|
294 |
+
output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
|
295 |
+
else:
|
296 |
+
output = hidden_states.reshape(
|
297 |
+
batch_size, (num_frames + p_t - 1) // p_t, height // p, width // p, -1, p_t, p, p
|
298 |
+
)
|
299 |
+
output = output.permute(0, 1, 5, 4, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(1, 2)
|
300 |
+
|
301 |
+
if USE_PEFT_BACKEND:
|
302 |
+
# remove `lora_scale` from each PEFT layer
|
303 |
+
unscale_lora_layers(self, lora_scale)
|
304 |
+
|
305 |
+
if not return_dict:
|
306 |
+
return (output,)
|
307 |
+
return Transformer2DModelOutput(sample=output)
|
308 |
+
|
309 |
+
|
310 |
+
return forward
|
311 |
+
|
312 |
+
model.forward = custom_forward(model)
|
313 |
+
|
CogVideoX/test.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from diffusers import CogVideoXImageToVideoPipeline
|
3 |
+
from diffusers.utils import export_to_video, load_image
|
4 |
+
|
5 |
+
prompt = "A dragon is flipping its wings"
|
6 |
+
image = load_image(image="/hpc2hdd/home/lwang592/projects/CogVideo/sat/configs/i2v/Dragon.jpg")
|
7 |
+
pipe = CogVideoXImageToVideoPipeline.from_pretrained(
|
8 |
+
"THUDM/CogVideoX-5b-I2V",
|
9 |
+
torch_dtype=torch.bfloat16
|
10 |
+
)
|
11 |
+
|
12 |
+
pipe.enable_sequential_cpu_offload()
|
13 |
+
pipe.vae.enable_tiling()
|
14 |
+
pipe.vae.enable_slicing()
|
15 |
+
|
16 |
+
video = pipe(
|
17 |
+
prompt=prompt,
|
18 |
+
image=image,
|
19 |
+
num_videos_per_prompt=1,
|
20 |
+
num_inference_steps=50,
|
21 |
+
num_frames=13,
|
22 |
+
guidance_scale=6,
|
23 |
+
generator=torch.Generator(device="cuda").manual_seed(42),
|
24 |
+
).frames[0]
|
25 |
+
|
26 |
+
export_to_video(video, "output.mp4", fps=8)
|
app.py
ADDED
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
THis is the main file for the gradio web demo. It uses the CogVideoX-5B model to generate videos gradio web demo.
|
3 |
+
set environment variable OPENAI_API_KEY to use the OpenAI API to enhance the prompt.
|
4 |
+
Usage:
|
5 |
+
OpenAI_API_KEY=your_openai_api_key OPENAI_BASE_URL=https://api.openai.com/v1 python inference/gradio_web_demo.py
|
6 |
+
"""
|
7 |
+
|
8 |
+
import math
|
9 |
+
import os
|
10 |
+
import random
|
11 |
+
import threading
|
12 |
+
import time
|
13 |
+
|
14 |
+
import cv2
|
15 |
+
import tempfile
|
16 |
+
import imageio_ffmpeg
|
17 |
+
import gradio as gr
|
18 |
+
import torch
|
19 |
+
from PIL import Image
|
20 |
+
# from diffusers import (
|
21 |
+
# CogVideoXPipeline,
|
22 |
+
# CogVideoXDPMScheduler,
|
23 |
+
# CogVideoXVideoToVideoPipeline,
|
24 |
+
# CogVideoXImageToVideoPipeline,
|
25 |
+
# CogVideoXTransformer3DModel,
|
26 |
+
# )
|
27 |
+
from typing import Union, List
|
28 |
+
from CogVideoX.pipeline_rgba import CogVideoXPipeline
|
29 |
+
from CogVideoX.rgba_utils import *
|
30 |
+
from diffusers import CogVideoXDPMScheduler
|
31 |
+
|
32 |
+
from diffusers.utils import load_video, load_image, export_to_video
|
33 |
+
from datetime import datetime, timedelta
|
34 |
+
|
35 |
+
from diffusers.image_processor import VaeImageProcessor
|
36 |
+
import moviepy.editor as mp
|
37 |
+
import numpy as np
|
38 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
39 |
+
import gc
|
40 |
+
|
41 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
42 |
+
|
43 |
+
# hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
|
44 |
+
hf_hub_download(repo_id="wileewang/TransPixar", filename="cogvideox_rgba_lora.safetensors", local_dir="model_cogvideox_rgba_lora")
|
45 |
+
# snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
|
46 |
+
|
47 |
+
pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5B", torch_dtype=torch.bfloat16)
|
48 |
+
# pipe.enable_sequential_cpu_offload()
|
49 |
+
pipe.vae.enable_slicing()
|
50 |
+
pipe.vae.enable_tiling()
|
51 |
+
pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
|
52 |
+
seq_length = 2 * (
|
53 |
+
(480 // pipe.vae_scale_factor_spatial // 2)
|
54 |
+
* (720 // pipe.vae_scale_factor_spatial // 2)
|
55 |
+
* ((13 - 1) // pipe.vae_scale_factor_temporal + 1)
|
56 |
+
)
|
57 |
+
prepare_for_rgba_inference(
|
58 |
+
pipe.transformer,
|
59 |
+
rgba_weights_path="model_cogvideox_rgba_lora/cogvideox_rgba_lora.safetensors",
|
60 |
+
device="cuda",
|
61 |
+
dtype=torch.bfloat16,
|
62 |
+
text_length=226,
|
63 |
+
seq_length=seq_length, # this is for the creation of attention mask.
|
64 |
+
)
|
65 |
+
|
66 |
+
# pipe.transformer.to(memory_format=torch.channels_last)
|
67 |
+
# pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
|
68 |
+
# pipe_image.transformer.to(memory_format=torch.channels_last)
|
69 |
+
# pipe_image.transformer = torch.compile(pipe_image.transformer, mode="max-autotune", fullgraph=True)
|
70 |
+
|
71 |
+
os.makedirs("./output", exist_ok=True)
|
72 |
+
os.makedirs("./gradio_tmp", exist_ok=True)
|
73 |
+
|
74 |
+
# upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
|
75 |
+
# frame_interpolation_model = load_rife_model("model_rife")
|
76 |
+
|
77 |
+
|
78 |
+
sys_prompt = """You are part of a team of bots that creates videos. You work with an assistant bot that will draw anything you say in square brackets.
|
79 |
+
For example , outputting " a beautiful morning in the woods with the sun peaking through the trees " will trigger your partner bot to output an video of a forest morning , as described. You will be prompted by people looking to create detailed , amazing videos. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive.
|
80 |
+
There are a few rules to follow:
|
81 |
+
You will only ever output a single video description per user request.
|
82 |
+
When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
|
83 |
+
Other times the user will not want modifications , but instead want a new image . In this case , you should ignore your previous conversation with the user.
|
84 |
+
Video descriptions must have the same num of words as examples below. Extra words will be ignored.
|
85 |
+
"""
|
86 |
+
def save_video(tensor: Union[List[np.ndarray], List[Image.Image]], fps: int = 8, prefix='rgb'):
|
87 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
88 |
+
video_path = f"./output/{prefix}_{timestamp}.mp4"
|
89 |
+
os.makedirs(os.path.dirname(video_path), exist_ok=True)
|
90 |
+
export_to_video(tensor, video_path, fps=fps)
|
91 |
+
return video_path
|
92 |
+
|
93 |
+
def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):
|
94 |
+
width, height = get_video_dimensions(input_video)
|
95 |
+
|
96 |
+
if width == 720 and height == 480:
|
97 |
+
processed_video = input_video
|
98 |
+
else:
|
99 |
+
processed_video = center_crop_resize(input_video)
|
100 |
+
return processed_video
|
101 |
+
|
102 |
+
|
103 |
+
def get_video_dimensions(input_video_path):
|
104 |
+
reader = imageio_ffmpeg.read_frames(input_video_path)
|
105 |
+
metadata = next(reader)
|
106 |
+
return metadata["size"]
|
107 |
+
|
108 |
+
|
109 |
+
def center_crop_resize(input_video_path, target_width=720, target_height=480):
|
110 |
+
cap = cv2.VideoCapture(input_video_path)
|
111 |
+
|
112 |
+
orig_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
113 |
+
orig_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
114 |
+
orig_fps = cap.get(cv2.CAP_PROP_FPS)
|
115 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
116 |
+
|
117 |
+
width_factor = target_width / orig_width
|
118 |
+
height_factor = target_height / orig_height
|
119 |
+
resize_factor = max(width_factor, height_factor)
|
120 |
+
|
121 |
+
inter_width = int(orig_width * resize_factor)
|
122 |
+
inter_height = int(orig_height * resize_factor)
|
123 |
+
|
124 |
+
target_fps = 8
|
125 |
+
ideal_skip = max(0, math.ceil(orig_fps / target_fps) - 1)
|
126 |
+
skip = min(5, ideal_skip) # Cap at 5
|
127 |
+
|
128 |
+
while (total_frames / (skip + 1)) < 49 and skip > 0:
|
129 |
+
skip -= 1
|
130 |
+
|
131 |
+
processed_frames = []
|
132 |
+
frame_count = 0
|
133 |
+
total_read = 0
|
134 |
+
|
135 |
+
while frame_count < 49 and total_read < total_frames:
|
136 |
+
ret, frame = cap.read()
|
137 |
+
if not ret:
|
138 |
+
break
|
139 |
+
|
140 |
+
if total_read % (skip + 1) == 0:
|
141 |
+
resized = cv2.resize(frame, (inter_width, inter_height), interpolation=cv2.INTER_AREA)
|
142 |
+
|
143 |
+
start_x = (inter_width - target_width) // 2
|
144 |
+
start_y = (inter_height - target_height) // 2
|
145 |
+
cropped = resized[start_y : start_y + target_height, start_x : start_x + target_width]
|
146 |
+
|
147 |
+
processed_frames.append(cropped)
|
148 |
+
frame_count += 1
|
149 |
+
|
150 |
+
total_read += 1
|
151 |
+
|
152 |
+
cap.release()
|
153 |
+
|
154 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
|
155 |
+
temp_video_path = temp_file.name
|
156 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
157 |
+
out = cv2.VideoWriter(temp_video_path, fourcc, target_fps, (target_width, target_height))
|
158 |
+
|
159 |
+
for frame in processed_frames:
|
160 |
+
out.write(frame)
|
161 |
+
|
162 |
+
out.release()
|
163 |
+
|
164 |
+
return temp_video_path
|
165 |
+
|
166 |
+
|
167 |
+
|
168 |
+
def infer(
|
169 |
+
prompt: str,
|
170 |
+
num_inference_steps: int,
|
171 |
+
guidance_scale: float,
|
172 |
+
seed: int = -1,
|
173 |
+
progress=gr.Progress(track_tqdm=True),
|
174 |
+
):
|
175 |
+
if seed == -1:
|
176 |
+
seed = random.randint(0, 2**8 - 1)
|
177 |
+
pipe.to(device)
|
178 |
+
video_pt = pipe(
|
179 |
+
prompt=prompt + ", isolated background",
|
180 |
+
num_videos_per_prompt=1,
|
181 |
+
num_inference_steps=num_inference_steps,
|
182 |
+
num_frames=13,
|
183 |
+
use_dynamic_cfg=True,
|
184 |
+
output_type="latent",
|
185 |
+
guidance_scale=guidance_scale,
|
186 |
+
generator=torch.Generator(device=device).manual_seed(int(seed)),
|
187 |
+
).frames
|
188 |
+
# pipe.to("cpu")
|
189 |
+
gc.collect()
|
190 |
+
return (video_pt, seed)
|
191 |
+
|
192 |
+
|
193 |
+
def convert_to_gif(video_path):
|
194 |
+
clip = mp.VideoFileClip(video_path)
|
195 |
+
clip = clip.set_fps(8)
|
196 |
+
clip = clip.resize(height=240)
|
197 |
+
gif_path = video_path.replace(".mp4", ".gif")
|
198 |
+
clip.write_gif(gif_path, fps=8)
|
199 |
+
return gif_path
|
200 |
+
|
201 |
+
|
202 |
+
def delete_old_files():
|
203 |
+
while True:
|
204 |
+
now = datetime.now()
|
205 |
+
cutoff = now - timedelta(minutes=10)
|
206 |
+
directories = ["./output", "./gradio_tmp"]
|
207 |
+
|
208 |
+
for directory in directories:
|
209 |
+
for filename in os.listdir(directory):
|
210 |
+
file_path = os.path.join(directory, filename)
|
211 |
+
if os.path.isfile(file_path):
|
212 |
+
file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
|
213 |
+
if file_mtime < cutoff:
|
214 |
+
os.remove(file_path)
|
215 |
+
time.sleep(600)
|
216 |
+
|
217 |
+
|
218 |
+
threading.Thread(target=delete_old_files, daemon=True).start()
|
219 |
+
# examples_videos = [["example_videos/horse.mp4"], ["example_videos/kitten.mp4"], ["example_videos/train_running.mp4"]]
|
220 |
+
# examples_images = [["example_images/beach.png"], ["example_images/street.png"], ["example_images/camping.png"]]
|
221 |
+
|
222 |
+
with gr.Blocks() as demo:
|
223 |
+
gr.Markdown("""
|
224 |
+
<div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
|
225 |
+
TransPixar + CogVideoX-5B Huggingface Space🤗
|
226 |
+
</div>
|
227 |
+
<div style="text-align: center;">
|
228 |
+
<a href="https://huggingface.co/wileewang/TransPixar">🤗 TransPixar LoRA Hub</a> |
|
229 |
+
<a href="https://github.com/wileewang/TransPixar">🌐 Github</a> |
|
230 |
+
<a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
|
231 |
+
</div>
|
232 |
+
<div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
|
233 |
+
⚠️ This demo is for academic research and experiential use only.
|
234 |
+
</div>
|
235 |
+
""")
|
236 |
+
with gr.Row():
|
237 |
+
with gr.Column():
|
238 |
+
# with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
|
239 |
+
# image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")
|
240 |
+
# examples_component_images = gr.Examples(examples_images, inputs=[image_input], cache_examples=False)
|
241 |
+
# with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):
|
242 |
+
# video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")
|
243 |
+
# strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")
|
244 |
+
# examples_component_videos = gr.Examples(examples_videos, inputs=[video_input], cache_examples=False)
|
245 |
+
prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
|
246 |
+
with gr.Group():
|
247 |
+
with gr.Column():
|
248 |
+
with gr.Row():
|
249 |
+
seed_param = gr.Number(
|
250 |
+
label="Inference Seed (Enter a positive number, -1 for random)", value=-1
|
251 |
+
)
|
252 |
+
# with gr.Row():
|
253 |
+
# enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
|
254 |
+
# enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
|
255 |
+
# gr.Markdown(
|
256 |
+
# "✨In this demo, we use [RIFE](https://github.com/hzwer/ECCV2022-RIFE) for frame interpolation and [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) for upscaling(Super-Resolution).<br> The entire process is based on open-source solutions."
|
257 |
+
# )
|
258 |
+
|
259 |
+
generate_button = gr.Button("🎬 Generate Video")
|
260 |
+
|
261 |
+
# Add the note at the bottom-left
|
262 |
+
with gr.Row():
|
263 |
+
gr.Markdown(
|
264 |
+
"""
|
265 |
+
**Note:** The RGB is a premultiplied version to avoid the color decontamination problem.
|
266 |
+
It can directly composite with a background using:
|
267 |
+
```
|
268 |
+
composite = rgb + (1 - alpha) * background
|
269 |
+
```
|
270 |
+
"""
|
271 |
+
)
|
272 |
+
|
273 |
+
with gr.Column():
|
274 |
+
rgb_video_output = gr.Video(label="Generate RGB Video", width=720, height=480)
|
275 |
+
alpha_video_output = gr.Video(label="Generate Alpha Video", width=720, height=480)
|
276 |
+
with gr.Row():
|
277 |
+
download_rgb_video_button = gr.File(label="📥 Download RGB Video", visible=False)
|
278 |
+
download_alpha_video_button = gr.File(label="📥 Download Alpha Video", visible=False)
|
279 |
+
seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
|
280 |
+
|
281 |
+
|
282 |
+
def generate(
|
283 |
+
prompt,
|
284 |
+
seed_value,
|
285 |
+
progress=gr.Progress(track_tqdm=True)
|
286 |
+
):
|
287 |
+
latents, seed = infer(
|
288 |
+
prompt,
|
289 |
+
num_inference_steps=25, # NOT Changed
|
290 |
+
guidance_scale=7.0, # NOT Changed
|
291 |
+
seed=seed_value,
|
292 |
+
progress=progress,
|
293 |
+
)
|
294 |
+
|
295 |
+
latents_rgb, latents_alpha = latents.chunk(2, dim=1)
|
296 |
+
|
297 |
+
frames_rgb = decode_latents(pipe, latents_rgb)
|
298 |
+
frames_alpha = decode_latents(pipe, latents_alpha)
|
299 |
+
|
300 |
+
pooled_alpha = np.max(frames_alpha, axis=-1, keepdims=True)
|
301 |
+
frames_alpha_pooled = np.repeat(pooled_alpha, 3, axis=-1)
|
302 |
+
premultiplied_rgb = frames_rgb * frames_alpha_pooled
|
303 |
+
|
304 |
+
rgb_video_path = save_video(premultiplied_rgb[0], fps=8, prefix='rgb')
|
305 |
+
rgb_video_update = gr.update(visible=True, value=rgb_video_path)
|
306 |
+
|
307 |
+
alpha_video_path = save_video(frames_alpha_pooled[0], fps=8, prefix='alpha')
|
308 |
+
alpha_video_update = gr.update(visible=True, value=alpha_video_path)
|
309 |
+
seed_update = gr.update(visible=True, value=seed)
|
310 |
+
|
311 |
+
return rgb_video_path, alpha_video_path, rgb_video_update, alpha_video_update, seed_update
|
312 |
+
|
313 |
+
|
314 |
+
generate_button.click(
|
315 |
+
generate,
|
316 |
+
inputs=[prompt, seed_param],
|
317 |
+
outputs=[rgb_video_output, alpha_video_output, download_rgb_video_button, download_alpha_video_button, seed_text],
|
318 |
+
)
|
319 |
+
|
320 |
+
|
321 |
+
if __name__ == "__main__":
|
322 |
+
demo.queue(max_size=15)
|
323 |
+
demo.launch()
|