Spaces:
Running
on
Zero
Running
on
Zero
Fixed reqs
Browse files- app_gradio.py +1 -1
- requirements.txt +69 -6
- res_old.txt +46 -0
- text2vid_torch2.py +707 -0
app_gradio.py
CHANGED
@@ -18,7 +18,7 @@ from diffusers import (
|
|
18 |
from transformers import CLIPTokenizer, CLIPTextModel
|
19 |
from diffusers.utils import export_to_video
|
20 |
from typing import List
|
21 |
-
from
|
22 |
from invert_utils import ddim_inversion as dd_inversion
|
23 |
from gifs_filter import filter
|
24 |
import subprocess
|
|
|
18 |
from transformers import CLIPTokenizer, CLIPTextModel
|
19 |
from diffusers.utils import export_to_video
|
20 |
from typing import List
|
21 |
+
from text2vid_torch2 import TextToVideoSDPipelineModded
|
22 |
from invert_utils import ddim_inversion as dd_inversion
|
23 |
from gifs_filter import filter
|
24 |
import subprocess
|
requirements.txt
CHANGED
@@ -1,16 +1,26 @@
|
|
1 |
-
gunicorn
|
2 |
-
spaces
|
3 |
accelerate==0.29.2
|
|
|
|
|
|
|
4 |
blinker==1.9.0
|
5 |
certifi==2024.8.30
|
6 |
charset-normalizer==3.4.0
|
7 |
click==8.1.7
|
|
|
8 |
decorator==4.4.2
|
9 |
diffusers==0.27.2
|
10 |
einops==0.8.0
|
|
|
|
|
|
|
11 |
filelock==3.16.1
|
12 |
Flask==3.0.3
|
13 |
fsspec==2024.10.0
|
|
|
|
|
|
|
|
|
|
|
14 |
huggingface-hub==0.25.2
|
15 |
idna==3.10
|
16 |
imageio==2.36.0
|
@@ -18,29 +28,82 @@ imageio-ffmpeg==0.5.1
|
|
18 |
importlib_metadata==8.5.0
|
19 |
itsdangerous==2.2.0
|
20 |
Jinja2==3.1.4
|
21 |
-
|
|
|
|
|
|
|
22 |
moviepy==1.0.3
|
|
|
|
|
23 |
numpy==1.24.2
|
24 |
nvidia-cublas-cu11==11.10.3.66
|
|
|
|
|
|
|
25 |
nvidia-cuda-nvrtc-cu11==11.7.99
|
|
|
26 |
nvidia-cuda-runtime-cu11==11.7.99
|
|
|
27 |
nvidia-cudnn-cu11==8.5.0.96
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
opencv-python==4.10.0.84
|
|
|
29 |
packaging==24.2
|
|
|
30 |
pillow==10.4.0
|
|
|
31 |
proglog==0.1.10
|
32 |
-
psutil==
|
|
|
|
|
|
|
|
|
|
|
33 |
python-dotenv==1.0.1
|
|
|
|
|
34 |
PyYAML==6.0.2
|
35 |
regex==2024.11.6
|
36 |
requests==2.32.3
|
|
|
|
|
|
|
37 |
safetensors==0.4.5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
tokenizers==0.20.3
|
39 |
-
|
40 |
-
|
|
|
|
|
41 |
tqdm==4.67.0
|
42 |
transformers==4.45.2
|
|
|
|
|
43 |
typing_extensions==4.12.2
|
|
|
44 |
urllib3==2.2.3
|
|
|
|
|
45 |
Werkzeug==3.1.3
|
|
|
46 |
zipp==3.21.0
|
|
|
|
|
|
|
1 |
accelerate==0.29.2
|
2 |
+
aiofiles==23.2.1
|
3 |
+
annotated-types==0.7.0
|
4 |
+
anyio==4.6.2.post1
|
5 |
blinker==1.9.0
|
6 |
certifi==2024.8.30
|
7 |
charset-normalizer==3.4.0
|
8 |
click==8.1.7
|
9 |
+
cmake==3.31.1
|
10 |
decorator==4.4.2
|
11 |
diffusers==0.27.2
|
12 |
einops==0.8.0
|
13 |
+
exceptiongroup==1.2.2
|
14 |
+
fastapi==0.115.5
|
15 |
+
ffmpy==0.4.0
|
16 |
filelock==3.16.1
|
17 |
Flask==3.0.3
|
18 |
fsspec==2024.10.0
|
19 |
+
gradio==5.6.0
|
20 |
+
gradio_client==1.4.3
|
21 |
+
h11==0.14.0
|
22 |
+
httpcore==1.0.7
|
23 |
+
httpx==0.27.2
|
24 |
huggingface-hub==0.25.2
|
25 |
idna==3.10
|
26 |
imageio==2.36.0
|
|
|
28 |
importlib_metadata==8.5.0
|
29 |
itsdangerous==2.2.0
|
30 |
Jinja2==3.1.4
|
31 |
+
lit==18.1.8
|
32 |
+
markdown-it-py==3.0.0
|
33 |
+
MarkupSafe==2.1.5
|
34 |
+
mdurl==0.1.2
|
35 |
moviepy==1.0.3
|
36 |
+
mpmath==1.3.0
|
37 |
+
networkx==3.4.2
|
38 |
numpy==1.24.2
|
39 |
nvidia-cublas-cu11==11.10.3.66
|
40 |
+
nvidia-cublas-cu12==12.4.5.8
|
41 |
+
nvidia-cuda-cupti-cu11==11.7.101
|
42 |
+
nvidia-cuda-cupti-cu12==12.4.127
|
43 |
nvidia-cuda-nvrtc-cu11==11.7.99
|
44 |
+
nvidia-cuda-nvrtc-cu12==12.4.127
|
45 |
nvidia-cuda-runtime-cu11==11.7.99
|
46 |
+
nvidia-cuda-runtime-cu12==12.4.127
|
47 |
nvidia-cudnn-cu11==8.5.0.96
|
48 |
+
nvidia-cudnn-cu12==9.1.0.70
|
49 |
+
nvidia-cufft-cu11==10.9.0.58
|
50 |
+
nvidia-cufft-cu12==11.2.1.3
|
51 |
+
nvidia-curand-cu11==10.2.10.91
|
52 |
+
nvidia-curand-cu12==10.3.5.147
|
53 |
+
nvidia-cusolver-cu11==11.4.0.1
|
54 |
+
nvidia-cusolver-cu12==11.6.1.9
|
55 |
+
nvidia-cusparse-cu11==11.7.4.91
|
56 |
+
nvidia-cusparse-cu12==12.3.1.170
|
57 |
+
nvidia-nccl-cu11==2.14.3
|
58 |
+
nvidia-nccl-cu12==2.21.5
|
59 |
+
nvidia-nvjitlink-cu12==12.4.127
|
60 |
+
nvidia-nvtx-cu11==11.7.91
|
61 |
+
nvidia-nvtx-cu12==12.4.127
|
62 |
opencv-python==4.10.0.84
|
63 |
+
orjson==3.10.12
|
64 |
packaging==24.2
|
65 |
+
pandas==2.2.3
|
66 |
pillow==10.4.0
|
67 |
+
pip==24.2
|
68 |
proglog==0.1.10
|
69 |
+
psutil==5.9.8
|
70 |
+
pydantic==2.10.1
|
71 |
+
pydantic_core==2.27.1
|
72 |
+
pydub==0.25.1
|
73 |
+
Pygments==2.18.0
|
74 |
+
python-dateutil==2.9.0.post0
|
75 |
python-dotenv==1.0.1
|
76 |
+
python-multipart==0.0.12
|
77 |
+
pytz==2024.2
|
78 |
PyYAML==6.0.2
|
79 |
regex==2024.11.6
|
80 |
requests==2.32.3
|
81 |
+
rich==13.9.4
|
82 |
+
ruff==0.8.0
|
83 |
+
safehttpx==0.1.1
|
84 |
safetensors==0.4.5
|
85 |
+
semantic-version==2.10.0
|
86 |
+
setuptools==75.1.0
|
87 |
+
shellingham==1.5.4
|
88 |
+
six==1.16.0
|
89 |
+
sniffio==1.3.1
|
90 |
+
spaces==0.30.4
|
91 |
+
starlette==0.41.3
|
92 |
+
sympy==1.13.1
|
93 |
tokenizers==0.20.3
|
94 |
+
tomlkit==0.12.0
|
95 |
+
torch==2.0.1
|
96 |
+
torchaudio==2.0.2
|
97 |
+
torchvision==0.15.2
|
98 |
tqdm==4.67.0
|
99 |
transformers==4.45.2
|
100 |
+
triton==2.0.0
|
101 |
+
typer==0.13.1
|
102 |
typing_extensions==4.12.2
|
103 |
+
tzdata==2024.2
|
104 |
urllib3==2.2.3
|
105 |
+
uvicorn==0.32.1
|
106 |
+
websockets==12.0
|
107 |
Werkzeug==3.1.3
|
108 |
+
wheel==0.44.0
|
109 |
zipp==3.21.0
|
res_old.txt
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gunicorn
|
2 |
+
spaces
|
3 |
+
accelerate==0.29.2
|
4 |
+
blinker==1.9.0
|
5 |
+
certifi==2024.8.30
|
6 |
+
charset-normalizer==3.4.0
|
7 |
+
click==8.1.7
|
8 |
+
decorator==4.4.2
|
9 |
+
diffusers==0.27.2
|
10 |
+
einops==0.8.0
|
11 |
+
filelock==3.16.1
|
12 |
+
Flask==3.0.3
|
13 |
+
fsspec==2024.10.0
|
14 |
+
huggingface-hub==0.25.2
|
15 |
+
idna==3.10
|
16 |
+
imageio==2.36.0
|
17 |
+
imageio-ffmpeg==0.5.1
|
18 |
+
importlib_metadata==8.5.0
|
19 |
+
itsdangerous==2.2.0
|
20 |
+
Jinja2==3.1.4
|
21 |
+
MarkupSafe==3.0.2
|
22 |
+
moviepy==1.0.3
|
23 |
+
numpy==1.24.2
|
24 |
+
nvidia-cublas-cu11==11.10.3.66
|
25 |
+
nvidia-cuda-nvrtc-cu11==11.7.99
|
26 |
+
nvidia-cuda-runtime-cu11==11.7.99
|
27 |
+
nvidia-cudnn-cu11==8.5.0.96
|
28 |
+
opencv-python==4.10.0.84
|
29 |
+
packaging==24.2
|
30 |
+
pillow==10.4.0
|
31 |
+
proglog==0.1.10
|
32 |
+
psutil==6.1.0
|
33 |
+
python-dotenv==1.0.1
|
34 |
+
PyYAML==6.0.2
|
35 |
+
regex==2024.11.6
|
36 |
+
requests==2.32.3
|
37 |
+
safetensors==0.4.5
|
38 |
+
tokenizers==0.20.3
|
39 |
+
torch==1.13.1
|
40 |
+
torchvision==0.14.1
|
41 |
+
tqdm==4.67.0
|
42 |
+
transformers==4.45.2
|
43 |
+
typing_extensions==4.12.2
|
44 |
+
urllib3==2.2.3
|
45 |
+
Werkzeug==3.1.3
|
46 |
+
zipp==3.21.0
|
text2vid_torch2.py
ADDED
@@ -0,0 +1,707 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
5 |
+
from diffusers.image_processor import VaeImageProcessor
|
6 |
+
from diffusers.models import AutoencoderKL, UNet3DConditionModel
|
7 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
8 |
+
from diffusers.utils import (deprecate,
|
9 |
+
logging,
|
10 |
+
replace_example_docstring)
|
11 |
+
from diffusers.pipelines.text_to_video_synthesis import TextToVideoSDPipelineOutput
|
12 |
+
from torch.nn import functional as F
|
13 |
+
from diffusers.models.attention_processor import Attention
|
14 |
+
import math
|
15 |
+
|
16 |
+
|
17 |
+
TAU_2 = 15
|
18 |
+
TAU_1 = 10
|
19 |
+
|
20 |
+
|
21 |
+
def init_attention_params(unet, num_frames, lambda_=None, bs=None):
|
22 |
+
|
23 |
+
|
24 |
+
for name, module in unet.named_modules():
|
25 |
+
module_name = type(module).__name__
|
26 |
+
if module_name == "Attention":
|
27 |
+
module.processor.LAMBDA = lambda_
|
28 |
+
module.processor.bs = bs
|
29 |
+
module.processor.num_frames = num_frames
|
30 |
+
|
31 |
+
|
32 |
+
def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0,
|
33 |
+
is_causal=False, scale=None, enable_gqa=False, k1 = None, d_l = None) -> torch.Tensor:
|
34 |
+
|
35 |
+
L, S = query.size(-2), key.size(-2)
|
36 |
+
scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale
|
37 |
+
attn_bias = torch.zeros(L, S, dtype=query.dtype).to(query.device)
|
38 |
+
if is_causal:
|
39 |
+
assert attn_mask is None
|
40 |
+
temp_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0)
|
41 |
+
attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
|
42 |
+
attn_bias.to(query.dtype)
|
43 |
+
|
44 |
+
if attn_mask is not None:
|
45 |
+
if attn_mask.dtype == torch.bool:
|
46 |
+
attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
|
47 |
+
else:
|
48 |
+
attn_bias += attn_mask
|
49 |
+
|
50 |
+
if enable_gqa:
|
51 |
+
if k1 is not None and d_l is not None:
|
52 |
+
k1 = k1.repeat_interleave(query.size(-3)//k1.size(-3), -3)
|
53 |
+
key = key.repeat_interleave(query.size(-3)//key.size(-3), -3)
|
54 |
+
value = value.repeat_interleave(query.size(-3)//value.size(-3), -3)
|
55 |
+
|
56 |
+
if k1 is not None:
|
57 |
+
attn_k1 = query @ k1.transpose(-2, -1)
|
58 |
+
attn_weight = query @ key.transpose(-2, -1)
|
59 |
+
attn_weight[:,:len(d_l),0] = attn_k1[:,:len(d_l),0] * d_l
|
60 |
+
attn_weight = attn_weight * scale_factor
|
61 |
+
else:
|
62 |
+
attn_weight = query @ key.transpose(-2, -1) * scale_factor
|
63 |
+
|
64 |
+
attn_weight += attn_bias
|
65 |
+
|
66 |
+
attn_weight = torch.softmax(attn_weight, dim=-1)
|
67 |
+
attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
|
68 |
+
return attn_weight @ value
|
69 |
+
|
70 |
+
class AttnProcessor2_0:
|
71 |
+
r"""
|
72 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
73 |
+
"""
|
74 |
+
|
75 |
+
def __init__(self):
|
76 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
77 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
78 |
+
|
79 |
+
def __call__(
|
80 |
+
self,
|
81 |
+
attn: Attention,
|
82 |
+
hidden_states: torch.Tensor,
|
83 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
84 |
+
attention_mask: Optional[torch.Tensor] = None,
|
85 |
+
temb: Optional[torch.Tensor] = None,
|
86 |
+
*args,
|
87 |
+
**kwargs,
|
88 |
+
) -> torch.Tensor:
|
89 |
+
if len(args) > 0 or kwargs.get("scale", None) is not None:
|
90 |
+
deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
|
91 |
+
deprecate("scale", "1.0.0", deprecation_message)
|
92 |
+
|
93 |
+
residual = hidden_states
|
94 |
+
if attn.spatial_norm is not None:
|
95 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
96 |
+
|
97 |
+
input_ndim = hidden_states.ndim
|
98 |
+
|
99 |
+
if input_ndim == 4:
|
100 |
+
batch_size, channel, height, width = hidden_states.shape
|
101 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
102 |
+
|
103 |
+
batch_size, sequence_length, _ = (
|
104 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
105 |
+
)
|
106 |
+
|
107 |
+
if attention_mask is not None:
|
108 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
109 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
110 |
+
# (batch, heads, source_length, target_length)
|
111 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
112 |
+
|
113 |
+
if attn.group_norm is not None:
|
114 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
115 |
+
|
116 |
+
query = attn.to_q(hidden_states)
|
117 |
+
|
118 |
+
if encoder_hidden_states is None:
|
119 |
+
encoder_hidden_states = hidden_states
|
120 |
+
elif attn.norm_cross:
|
121 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
122 |
+
|
123 |
+
key = attn.to_k(encoder_hidden_states)
|
124 |
+
value = attn.to_v(encoder_hidden_states)
|
125 |
+
|
126 |
+
inner_dim = key.shape[-1]
|
127 |
+
head_dim = inner_dim // attn.heads
|
128 |
+
|
129 |
+
query, key, d_l, k1 = self.get_qk(query, key)
|
130 |
+
|
131 |
+
|
132 |
+
|
133 |
+
|
134 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
135 |
+
|
136 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
137 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
138 |
+
|
139 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
140 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
141 |
+
|
142 |
+
if d_l is not None:
|
143 |
+
k1 = k1.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
144 |
+
hidden_states = scaled_dot_product_attention(
|
145 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False, k1 = k1, d_l = d_l
|
146 |
+
)
|
147 |
+
else:
|
148 |
+
|
149 |
+
hidden_states = scaled_dot_product_attention(
|
150 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
151 |
+
)
|
152 |
+
|
153 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
154 |
+
hidden_states = hidden_states.to(query.dtype)
|
155 |
+
|
156 |
+
# linear proj
|
157 |
+
hidden_states = attn.to_out[0](hidden_states)
|
158 |
+
# dropout
|
159 |
+
hidden_states = attn.to_out[1](hidden_states)
|
160 |
+
|
161 |
+
if input_ndim == 4:
|
162 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
163 |
+
|
164 |
+
if attn.residual_connection:
|
165 |
+
hidden_states = hidden_states + residual
|
166 |
+
|
167 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
168 |
+
|
169 |
+
return hidden_states
|
170 |
+
|
171 |
+
def get_qk(
|
172 |
+
self, query, key):
|
173 |
+
r"""
|
174 |
+
Compute the attention scores.
|
175 |
+
|
176 |
+
Args:
|
177 |
+
query (`torch.Tensor`): The query tensor.
|
178 |
+
key (`torch.Tensor`): The key tensor.
|
179 |
+
attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
|
180 |
+
|
181 |
+
Returns:
|
182 |
+
`torch.Tensor`: The attention probabilities/scores.
|
183 |
+
"""
|
184 |
+
|
185 |
+
|
186 |
+
|
187 |
+
q_old = query.clone()
|
188 |
+
k_old = key.clone()
|
189 |
+
dynamic_lambda = None
|
190 |
+
key1 = None
|
191 |
+
|
192 |
+
if self.use_last_attn_slice:# and self.last_attn_slice[0].shape[0] == query.shape[0]:# and query.shape[1]==self.num_frames:
|
193 |
+
|
194 |
+
if self.last_attn_slice is not None:
|
195 |
+
|
196 |
+
query_list = self.last_attn_slice[0]
|
197 |
+
key_list = self.last_attn_slice[1]
|
198 |
+
|
199 |
+
|
200 |
+
if query.shape[1] == self.num_frames and query.shape == key.shape:
|
201 |
+
|
202 |
+
key1 = key.clone()
|
203 |
+
key1[:,:1,:key_list.shape[2]] = key_list[:,:1]
|
204 |
+
dynamic_lambda = torch.tensor([1 + self.LAMBDA * (i/50) for i in range(self.num_frames)]).to(key.dtype).cuda()
|
205 |
+
|
206 |
+
if q_old.shape == k_old.shape and q_old.shape[1]!=self.num_frames:
|
207 |
+
|
208 |
+
batch_dim = query_list.shape[0] // self.bs
|
209 |
+
all_dim = query.shape[0] // self.bs
|
210 |
+
for i in range(self.bs):
|
211 |
+
query[i*all_dim:(i*all_dim) + batch_dim,:query_list.shape[1],:query_list.shape[2]] = query_list[i*batch_dim:(i+1)*batch_dim]
|
212 |
+
|
213 |
+
if self.save_last_attn_slice:
|
214 |
+
|
215 |
+
self.last_attn_slice = [
|
216 |
+
query,
|
217 |
+
key,
|
218 |
+
]
|
219 |
+
|
220 |
+
self.save_last_attn_slice = False
|
221 |
+
|
222 |
+
|
223 |
+
return query, key, dynamic_lambda, key1
|
224 |
+
|
225 |
+
|
226 |
+
def init_attention_func(unet):
|
227 |
+
|
228 |
+
for name, module in unet.named_modules():
|
229 |
+
module_name = type(module).__name__
|
230 |
+
if module_name == "Attention":
|
231 |
+
|
232 |
+
module.set_processor(AttnProcessor2_0())
|
233 |
+
module.processor.last_attn_slice = None
|
234 |
+
module.processor.use_last_attn_slice = False
|
235 |
+
module.processor.save_last_attn_slice = False
|
236 |
+
module.processor.LAMBDA = 0
|
237 |
+
module.processor.num_frames = None
|
238 |
+
module.processor.bs = 0
|
239 |
+
|
240 |
+
|
241 |
+
return unet
|
242 |
+
|
243 |
+
|
244 |
+
def use_last_self_attention(unet, use=True):
|
245 |
+
for name, module in unet.named_modules():
|
246 |
+
module_name = type(module).__name__
|
247 |
+
if module_name == "Attention" and "attn1" in name:
|
248 |
+
module.processor.use_last_attn_slice = use
|
249 |
+
|
250 |
+
def save_last_self_attention(unet, save=True):
|
251 |
+
for name, module in unet.named_modules():
|
252 |
+
module_name = type(module).__name__
|
253 |
+
if module_name == "Attention" and "attn1" in name:
|
254 |
+
module.processor.save_last_attn_slice = save
|
255 |
+
|
256 |
+
|
257 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
258 |
+
|
259 |
+
EXAMPLE_DOC_STRING = """
|
260 |
+
Examples:
|
261 |
+
```py
|
262 |
+
>>> import torch
|
263 |
+
>>> from diffusers import TextToVideoSDPipeline
|
264 |
+
>>> from diffusers.utils import export_to_video
|
265 |
+
|
266 |
+
>>> pipe = TextToVideoSDPipeline.from_pretrained(
|
267 |
+
... "damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16, variant="fp16"
|
268 |
+
... )
|
269 |
+
>>> pipe.enable_model_cpu_offload()
|
270 |
+
|
271 |
+
>>> prompt = "Spiderman is surfing"
|
272 |
+
>>> video_frames = pipe(prompt).frames[0]
|
273 |
+
>>> video_path = export_to_video(video_frames)
|
274 |
+
>>> video_path
|
275 |
+
```
|
276 |
+
"""
|
277 |
+
|
278 |
+
|
279 |
+
# Copied from diffusers.pipelines.animatediff.pipeline_animatediff.tensor2vid
|
280 |
+
def tensor2vid(video: torch.Tensor, processor: "VaeImageProcessor", output_type: str = "np"):
|
281 |
+
batch_size, channels, num_frames, height, width = video.shape
|
282 |
+
outputs = []
|
283 |
+
for batch_idx in range(batch_size):
|
284 |
+
batch_vid = video[batch_idx].permute(1, 0, 2, 3)
|
285 |
+
batch_output = processor.postprocess(batch_vid, output_type)
|
286 |
+
|
287 |
+
outputs.append(batch_output)
|
288 |
+
|
289 |
+
if output_type == "np":
|
290 |
+
outputs = np.stack(outputs)
|
291 |
+
|
292 |
+
elif output_type == "pt":
|
293 |
+
outputs = torch.stack(outputs)
|
294 |
+
|
295 |
+
elif not output_type == "pil":
|
296 |
+
raise ValueError(f"{output_type} does not exist. Please choose one of ['np', 'pt', 'pil']")
|
297 |
+
|
298 |
+
return outputs
|
299 |
+
|
300 |
+
from diffusers import TextToVideoSDPipeline
|
301 |
+
class TextToVideoSDPipelineModded(TextToVideoSDPipeline):
|
302 |
+
def __init__(
|
303 |
+
self,
|
304 |
+
vae: AutoencoderKL,
|
305 |
+
text_encoder: CLIPTextModel,
|
306 |
+
tokenizer: CLIPTokenizer,
|
307 |
+
unet: UNet3DConditionModel,
|
308 |
+
scheduler: KarrasDiffusionSchedulers,
|
309 |
+
):
|
310 |
+
super().__init__(vae, text_encoder, tokenizer, unet, scheduler)
|
311 |
+
|
312 |
+
|
313 |
+
def call_network(self,
|
314 |
+
negative_prompt_embeds,
|
315 |
+
prompt_embeds,
|
316 |
+
latents,
|
317 |
+
inv_latents,
|
318 |
+
t,
|
319 |
+
i,
|
320 |
+
null_embeds,
|
321 |
+
cross_attention_kwargs,
|
322 |
+
extra_step_kwargs,
|
323 |
+
do_classifier_free_guidance,
|
324 |
+
guidance_scale,
|
325 |
+
):
|
326 |
+
|
327 |
+
|
328 |
+
inv_latent_model_input = inv_latents
|
329 |
+
inv_latent_model_input = self.scheduler.scale_model_input(inv_latent_model_input, t)
|
330 |
+
|
331 |
+
latent_model_input = latents
|
332 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
333 |
+
|
334 |
+
|
335 |
+
if do_classifier_free_guidance:
|
336 |
+
noise_pred_uncond = self.unet(
|
337 |
+
latent_model_input,
|
338 |
+
t,
|
339 |
+
encoder_hidden_states=negative_prompt_embeds,
|
340 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
341 |
+
return_dict=False,
|
342 |
+
)[0]
|
343 |
+
|
344 |
+
noise_null_pred_uncond = self.unet(
|
345 |
+
inv_latent_model_input,
|
346 |
+
t,
|
347 |
+
encoder_hidden_states=negative_prompt_embeds,
|
348 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
349 |
+
return_dict=False,
|
350 |
+
)[0]
|
351 |
+
|
352 |
+
|
353 |
+
|
354 |
+
if i<=TAU_2:
|
355 |
+
save_last_self_attention(self.unet)
|
356 |
+
|
357 |
+
|
358 |
+
noise_null_pred = self.unet(
|
359 |
+
inv_latent_model_input,
|
360 |
+
t,
|
361 |
+
encoder_hidden_states=null_embeds,
|
362 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
363 |
+
return_dict=False,
|
364 |
+
)[0]
|
365 |
+
|
366 |
+
if do_classifier_free_guidance:
|
367 |
+
noise_null_pred = noise_null_pred_uncond + guidance_scale * (noise_null_pred - noise_null_pred_uncond)
|
368 |
+
|
369 |
+
bsz, channel, frames, width, height = inv_latents.shape
|
370 |
+
|
371 |
+
inv_latents = inv_latents.permute(0, 2, 1, 3, 4).reshape(bsz*frames, channel, height, width)
|
372 |
+
noise_null_pred = noise_null_pred.permute(0, 2, 1, 3, 4).reshape(bsz*frames, channel, height, width)
|
373 |
+
inv_latents = self.scheduler.step(noise_null_pred, t, inv_latents, **extra_step_kwargs).prev_sample
|
374 |
+
inv_latents = inv_latents[None, :].reshape((bsz, frames , -1) + inv_latents.shape[2:]).permute(0, 2, 1, 3, 4)
|
375 |
+
|
376 |
+
use_last_self_attention(self.unet)
|
377 |
+
else:
|
378 |
+
noise_null_pred = None
|
379 |
+
|
380 |
+
|
381 |
+
|
382 |
+
|
383 |
+
noise_pred = self.unet(
|
384 |
+
latent_model_input,
|
385 |
+
t,
|
386 |
+
encoder_hidden_states=prompt_embeds, # For unconditional guidance
|
387 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
388 |
+
return_dict=False,
|
389 |
+
)[0]
|
390 |
+
|
391 |
+
use_last_self_attention(self.unet, False)
|
392 |
+
|
393 |
+
|
394 |
+
if do_classifier_free_guidance:
|
395 |
+
noise_pred_text = noise_pred
|
396 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
397 |
+
|
398 |
+
# reshape latents
|
399 |
+
bsz, channel, frames, width, height = latents.shape
|
400 |
+
latents = latents.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)
|
401 |
+
noise_pred = noise_pred.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)
|
402 |
+
|
403 |
+
# compute the previous noisy sample x_t -> x_t-1
|
404 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
405 |
+
|
406 |
+
|
407 |
+
|
408 |
+
# reshape latents back
|
409 |
+
latents = latents[None, :].reshape(bsz, frames, channel, width, height).permute(0, 2, 1, 3, 4)
|
410 |
+
|
411 |
+
|
412 |
+
return {
|
413 |
+
"latents": latents,
|
414 |
+
"inv_latents": inv_latents,
|
415 |
+
"noise_pred": noise_pred,
|
416 |
+
"noise_null_pred": noise_null_pred,
|
417 |
+
}
|
418 |
+
|
419 |
+
def optimize_latents(self, latents, inv_latents, t, i, null_embeds, cross_attention_kwargs, prompt_embeds):
|
420 |
+
inv_scaled = self.scheduler.scale_model_input(inv_latents, t)
|
421 |
+
|
422 |
+
noise_null_pred = self.unet(
|
423 |
+
inv_scaled[:,:,0:1,:,:],
|
424 |
+
t,
|
425 |
+
encoder_hidden_states=null_embeds,
|
426 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
427 |
+
return_dict=False,
|
428 |
+
)[0]
|
429 |
+
|
430 |
+
with torch.enable_grad():
|
431 |
+
|
432 |
+
latent_train = latents[:,:,1:,:,:].clone().detach().requires_grad_(True)
|
433 |
+
optimizer = torch.optim.Adam([latent_train], lr=1e-3)
|
434 |
+
|
435 |
+
for j in range(10):
|
436 |
+
latent_in = torch.cat([inv_latents[:,:,0:1,:,:].detach(), latent_train], dim=2)
|
437 |
+
latent_input_unet = self.scheduler.scale_model_input(latent_in, t)
|
438 |
+
|
439 |
+
noise_pred = self.unet(
|
440 |
+
latent_input_unet,
|
441 |
+
t,
|
442 |
+
encoder_hidden_states=prompt_embeds, # For unconditional guidance
|
443 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
444 |
+
return_dict=False,
|
445 |
+
)[0]
|
446 |
+
|
447 |
+
loss = torch.nn.functional.mse_loss(noise_pred[:,:,0,:,:], noise_null_pred[:,:,0,:,:])
|
448 |
+
|
449 |
+
loss.backward()
|
450 |
+
|
451 |
+
optimizer.step()
|
452 |
+
optimizer.zero_grad()
|
453 |
+
|
454 |
+
print("Iteration {} Subiteration {} Loss {} ".format(i, j, loss.item()))
|
455 |
+
latents = latent_in.detach()
|
456 |
+
return latents
|
457 |
+
|
458 |
+
@torch.no_grad()
|
459 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
460 |
+
def __call__(
|
461 |
+
self,
|
462 |
+
prompt: Union[str, List[str]] = None,
|
463 |
+
height: Optional[int] = None,
|
464 |
+
width: Optional[int] = None,
|
465 |
+
num_frames: int = 16,
|
466 |
+
num_inference_steps: int = 50,
|
467 |
+
guidance_scale: float = 9.0,
|
468 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
469 |
+
eta: float = 0.0,
|
470 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
471 |
+
latents: Optional[torch.FloatTensor] = None,
|
472 |
+
inv_latents: Optional[torch.FloatTensor] = None,
|
473 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
474 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
475 |
+
output_type: Optional[str] = "np",
|
476 |
+
return_dict: bool = True,
|
477 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
478 |
+
callback_steps: int = 1,
|
479 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
480 |
+
clip_skip: Optional[int] = None,
|
481 |
+
lambda_ = 0.5,
|
482 |
+
):
|
483 |
+
r"""
|
484 |
+
The call function to the pipeline for generation.
|
485 |
+
|
486 |
+
Args:
|
487 |
+
prompt (`str` or `List[str]`, *optional*):
|
488 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
489 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
490 |
+
The height in pixels of the generated video.
|
491 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
492 |
+
The width in pixels of the generated video.
|
493 |
+
num_frames (`int`, *optional*, defaults to 16):
|
494 |
+
The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
|
495 |
+
amounts to 2 seconds of video.
|
496 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
497 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
|
498 |
+
expense of slower inference.
|
499 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
500 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
501 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
502 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
503 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
504 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
505 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
506 |
+
The number of images to generate per prompt.
|
507 |
+
eta (`float`, *optional*, defaults to 0.0):
|
508 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
509 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
510 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
511 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
512 |
+
generation deterministic.
|
513 |
+
latents (`torch.FloatTensor`, *optional*):
|
514 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
|
515 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
516 |
+
tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
|
517 |
+
`(batch_size, num_channel, num_frames, height, width)`.
|
518 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
519 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
520 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
521 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
522 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
523 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
524 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
525 |
+
The output format of the generated video. Choose between `torch.FloatTensor` or `np.array`.
|
526 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
527 |
+
Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
|
528 |
+
of a plain tuple.
|
529 |
+
callback (`Callable`, *optional*):
|
530 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
531 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
532 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
533 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
534 |
+
every step.
|
535 |
+
cross_attention_kwargs (`dict`, *optional*):
|
536 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
537 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
538 |
+
clip_skip (`int`, *optional*):
|
539 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
540 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
541 |
+
Examples:
|
542 |
+
|
543 |
+
Returns:
|
544 |
+
[`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] or `tuple`:
|
545 |
+
If `return_dict` is `True`, [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] is
|
546 |
+
returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
|
547 |
+
"""
|
548 |
+
# 0. Default height and width to unet
|
549 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
550 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
551 |
+
|
552 |
+
num_images_per_prompt = 1
|
553 |
+
|
554 |
+
# 1. Check inputs. Raise error if not correct
|
555 |
+
self.check_inputs(
|
556 |
+
prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
|
557 |
+
)
|
558 |
+
|
559 |
+
# # 2. Define call parameters
|
560 |
+
# if prompt is not None and isinstance(prompt, str):
|
561 |
+
# batch_size = 1
|
562 |
+
# elif prompt is not None and isinstance(prompt, list):
|
563 |
+
# batch_size = len(prompt)
|
564 |
+
# else:
|
565 |
+
# batch_size = prompt_embeds.shape[0]
|
566 |
+
|
567 |
+
batch_size = inv_latents.shape[0]
|
568 |
+
device = self._execution_device
|
569 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
570 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
571 |
+
# corresponds to doing no classifier free guidance.
|
572 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
573 |
+
|
574 |
+
# 3. Encode input prompt
|
575 |
+
text_encoder_lora_scale = (
|
576 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
577 |
+
)
|
578 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
579 |
+
[prompt] * batch_size,
|
580 |
+
device,
|
581 |
+
num_images_per_prompt,
|
582 |
+
do_classifier_free_guidance,
|
583 |
+
[negative_prompt] * batch_size if negative_prompt is not None else None,
|
584 |
+
prompt_embeds=prompt_embeds,
|
585 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
586 |
+
lora_scale=text_encoder_lora_scale,
|
587 |
+
clip_skip=clip_skip,
|
588 |
+
)
|
589 |
+
null_embeds, negative_prompt_embeds = self.encode_prompt(
|
590 |
+
[""] * batch_size,
|
591 |
+
device,
|
592 |
+
num_images_per_prompt,
|
593 |
+
do_classifier_free_guidance,
|
594 |
+
[negative_prompt] * batch_size if negative_prompt is not None else None,
|
595 |
+
prompt_embeds=None,
|
596 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
597 |
+
lora_scale=text_encoder_lora_scale,
|
598 |
+
clip_skip=clip_skip,
|
599 |
+
)
|
600 |
+
|
601 |
+
|
602 |
+
|
603 |
+
# 4. Prepare timesteps
|
604 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
605 |
+
timesteps = self.scheduler.timesteps
|
606 |
+
|
607 |
+
# 5. Prepare latent variables
|
608 |
+
num_channels_latents = self.unet.config.in_channels
|
609 |
+
latents = self.prepare_latents(
|
610 |
+
batch_size * num_images_per_prompt,
|
611 |
+
num_channels_latents,
|
612 |
+
num_frames,
|
613 |
+
height,
|
614 |
+
width,
|
615 |
+
prompt_embeds.dtype,
|
616 |
+
device,
|
617 |
+
generator,
|
618 |
+
latents,
|
619 |
+
)
|
620 |
+
inv_latents = self.prepare_latents(
|
621 |
+
batch_size * num_images_per_prompt,
|
622 |
+
num_channels_latents,
|
623 |
+
num_frames,
|
624 |
+
height,
|
625 |
+
width,
|
626 |
+
prompt_embeds.dtype,
|
627 |
+
device,
|
628 |
+
generator,
|
629 |
+
inv_latents,
|
630 |
+
)
|
631 |
+
|
632 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
633 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
634 |
+
|
635 |
+
# 7. Denoising loop
|
636 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
637 |
+
|
638 |
+
init_attention_func(self.unet)
|
639 |
+
print("Setup for Current Run")
|
640 |
+
print("----------------------")
|
641 |
+
print("Prompt ", prompt)
|
642 |
+
print("Batch size ", batch_size)
|
643 |
+
print("Num frames ", latents.shape[2])
|
644 |
+
print("Lambda ", lambda_)
|
645 |
+
|
646 |
+
init_attention_params(self.unet, num_frames=latents.shape[2], lambda_=lambda_, bs = batch_size)
|
647 |
+
|
648 |
+
iters_to_alter = [-1]#i for i in range(0, TAU_1)]
|
649 |
+
|
650 |
+
|
651 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
652 |
+
|
653 |
+
mask_in = torch.zeros(latents.shape).to(dtype=latents.dtype, device=latents.device)
|
654 |
+
mask_in[:, :, 0, :, :] = 1
|
655 |
+
assert latents.shape[0] == inv_latents.shape[0], "Latents and Inverse Latents should have the same batch but got {} and {}".format(latents.shape[0], inv_latents.shape[0])
|
656 |
+
inv_latents = inv_latents.repeat(1,1,num_frames,1,1)
|
657 |
+
|
658 |
+
latents = inv_latents * mask_in + latents * (1-mask_in)
|
659 |
+
|
660 |
+
|
661 |
+
|
662 |
+
for i, t in enumerate(timesteps):
|
663 |
+
|
664 |
+
curr_copy = max(1,num_frames - i)
|
665 |
+
inv_latents = inv_latents[:,:,:curr_copy, :, : ]
|
666 |
+
if i in iters_to_alter:
|
667 |
+
|
668 |
+
latents = self.optimize_latents(latents, inv_latents, t, i, null_embeds, cross_attention_kwargs, prompt_embeds)
|
669 |
+
|
670 |
+
|
671 |
+
output_dict = self.call_network(
|
672 |
+
negative_prompt_embeds,
|
673 |
+
prompt_embeds,
|
674 |
+
latents,
|
675 |
+
inv_latents,
|
676 |
+
t,
|
677 |
+
i,
|
678 |
+
null_embeds,
|
679 |
+
cross_attention_kwargs,
|
680 |
+
extra_step_kwargs,
|
681 |
+
do_classifier_free_guidance,
|
682 |
+
guidance_scale,
|
683 |
+
)
|
684 |
+
latents = output_dict["latents"]
|
685 |
+
inv_latents = output_dict["inv_latents"]
|
686 |
+
|
687 |
+
# call the callback, if provided
|
688 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
689 |
+
progress_bar.update()
|
690 |
+
if callback is not None and i % callback_steps == 0:
|
691 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
692 |
+
callback(step_idx, t, latents)
|
693 |
+
|
694 |
+
# 8. Post processing
|
695 |
+
if output_type == "latent":
|
696 |
+
video = latents
|
697 |
+
else:
|
698 |
+
video_tensor = self.decode_latents(latents)
|
699 |
+
video = tensor2vid(video_tensor, self.image_processor, output_type)
|
700 |
+
|
701 |
+
# 9. Offload all models
|
702 |
+
self.maybe_free_model_hooks()
|
703 |
+
|
704 |
+
if not return_dict:
|
705 |
+
return (video,)
|
706 |
+
|
707 |
+
return TextToVideoSDPipelineOutput(frames=video)
|