Spaces:
Running
on
Zero
Running
on
Zero
QinOwen
commited on
Commit
•
824b515
1
Parent(s):
b1828f2
add-vader-videocrafter
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +231 -0
- Core/actpred_scorer.py +88 -0
- Core/aesthetic_scorer.py +46 -0
- Core/compression_scorer.py +111 -0
- Core/prompts.py +159 -0
- Core/weather_scorer.py +161 -0
- VADER-VideoCrafter/License +470 -0
- VADER-VideoCrafter/configs/inference_i2v_512_v1.0.yaml +83 -0
- VADER-VideoCrafter/configs/inference_t2v_1024_v1.0.yaml +77 -0
- VADER-VideoCrafter/configs/inference_t2v_512_v1.0.yaml +74 -0
- VADER-VideoCrafter/configs/inference_t2v_512_v2.0.yaml +77 -0
- VADER-VideoCrafter/lvdm/basics.py +100 -0
- VADER-VideoCrafter/lvdm/common.py +96 -0
- VADER-VideoCrafter/lvdm/distributions.py +96 -0
- VADER-VideoCrafter/lvdm/ema.py +77 -0
- VADER-VideoCrafter/lvdm/models/autoencoder.py +220 -0
- VADER-VideoCrafter/lvdm/models/ddpm3d.py +765 -0
- VADER-VideoCrafter/lvdm/models/samplers/ddim.py +368 -0
- VADER-VideoCrafter/lvdm/models/utils_diffusion.py +105 -0
- VADER-VideoCrafter/lvdm/modules/attention.py +476 -0
- VADER-VideoCrafter/lvdm/modules/encoders/condition.py +393 -0
- VADER-VideoCrafter/lvdm/modules/encoders/ip_resampler.py +137 -0
- VADER-VideoCrafter/lvdm/modules/networks/ae_modules.py +846 -0
- VADER-VideoCrafter/lvdm/modules/networks/openaimodel3d.py +578 -0
- VADER-VideoCrafter/lvdm/modules/x_transformer.py +640 -0
- VADER-VideoCrafter/readme.md +138 -0
- VADER-VideoCrafter/requirements.txt +28 -0
- VADER-VideoCrafter/scripts/main/ddp_wrapper.py +47 -0
- VADER-VideoCrafter/scripts/main/funcs.py +231 -0
- VADER-VideoCrafter/scripts/main/train_t2v_lora.py +817 -0
- VADER-VideoCrafter/scripts/run_text2video_inference.sh +30 -0
- VADER-VideoCrafter/scripts/run_text2video_train.sh +28 -0
- VADER-VideoCrafter/utils/utils.py +77 -0
- app.py +207 -4
- assets/activities.txt +3 -0
- assets/chatgpt_custom.txt +50 -0
- assets/chatgpt_custom_actpred.txt +41 -0
- assets/chatgpt_custom_actpred2.txt +50 -0
- assets/chatgpt_custom_animal.txt +24 -0
- assets/chatgpt_custom_animal_action.txt +40 -0
- assets/chatgpt_custom_animal_clothes.txt +50 -0
- assets/chatgpt_custom_animal_clothesV2.txt +50 -0
- assets/chatgpt_custom_animal_clothesV3.txt +96 -0
- assets/chatgpt_custom_animal_housework.txt +150 -0
- assets/chatgpt_custom_animal_sport.txt +25 -0
- assets/chatgpt_custom_animal_sportV2.txt +50 -0
- assets/chatgpt_custom_animal_technology.txt +50 -0
- assets/chatgpt_custom_banana.txt +50 -0
- assets/chatgpt_custom_book_cup.txt +25 -0
- assets/chatgpt_custom_book_cup_character.txt +25 -0
.gitignore
ADDED
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
**/__pycache__
|
2 |
+
**/*.pyc
|
3 |
+
**/*.log
|
4 |
+
**/*.png
|
5 |
+
**/*.jpg
|
6 |
+
**/*.mp4
|
7 |
+
HPSv2
|
8 |
+
**/HPSv2
|
9 |
+
wandb
|
10 |
+
|
11 |
+
# VADER-VideoCrafter
|
12 |
+
VADER-VideoCrafter/.DS_Store
|
13 |
+
VADER-VideoCrafter/.vscode
|
14 |
+
VADER-VideoCrafter/__pycache__
|
15 |
+
VADER-VideoCrafter/*.egg-info
|
16 |
+
VADER-VideoCrafter/checkpoints
|
17 |
+
VADER-VideoCrafter/results
|
18 |
+
VADER-VideoCrafter/wandb
|
19 |
+
VADER-VideoCrafter/project_dir
|
20 |
+
VADER-VideoCrafter/scripts/evaluation/__pycache__
|
21 |
+
VADER-VideoCrafter/scripts/lvdm/__pycache__
|
22 |
+
|
23 |
+
|
24 |
+
# Byte-compiled / optimized / DLL files
|
25 |
+
VADER-Open-Sora/__pycache__/
|
26 |
+
VADER-Open-Sora/scripts/__pycache__
|
27 |
+
VADER-Open-Sora/opensora/__pycache__
|
28 |
+
VADER-Open-Sora/*.py[cod]
|
29 |
+
VADER-Open-Sora/*$py.class
|
30 |
+
|
31 |
+
# C extensions
|
32 |
+
VADER-Open-Sora/*.so
|
33 |
+
|
34 |
+
# Distribution / packaging
|
35 |
+
VADER-Open-Sora/.Python
|
36 |
+
VADER-Open-Sora/build/
|
37 |
+
VADER-Open-Sora/develop-eggs/
|
38 |
+
VADER-Open-Sora/dist/
|
39 |
+
VADER-Open-Sora/downloads/
|
40 |
+
VADER-Open-Sora/eggs/
|
41 |
+
VADER-Open-Sora/.eggs/
|
42 |
+
VADER-Open-Sora/lib/
|
43 |
+
VADER-Open-Sora/lib64/
|
44 |
+
VADER-Open-Sora/parts/
|
45 |
+
VADER-Open-Sora/sdist/
|
46 |
+
VADER-Open-Sora/var/
|
47 |
+
VADER-Open-Sora/wheels/
|
48 |
+
VADER-Open-Sora/share/python-wheels/
|
49 |
+
VADER-Open-Sora/*.egg-info/
|
50 |
+
VADER-Open-Sora/.installed.cfg
|
51 |
+
VADER-Open-Sora/*.egg
|
52 |
+
VADER-Open-Sora/MANIFEST
|
53 |
+
|
54 |
+
# PyInstaller
|
55 |
+
# Usually these files are written by a python script from a template
|
56 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
57 |
+
VADER-Open-Sora/*.manifest
|
58 |
+
VADER-Open-Sora/*.spec
|
59 |
+
|
60 |
+
# Installer logs
|
61 |
+
VADER-Open-Sora/pip-log.txt
|
62 |
+
VADER-Open-Sora/pip-delete-this-directory.txt
|
63 |
+
|
64 |
+
# Unit test / coverage reports
|
65 |
+
VADER-Open-Sora/htmlcov/
|
66 |
+
VADER-Open-Sora/.tox/
|
67 |
+
VADER-Open-Sora/.nox/
|
68 |
+
VADER-Open-Sora/.coverage
|
69 |
+
VADER-Open-Sora/.coverage.*
|
70 |
+
VADER-Open-Sora/.cache
|
71 |
+
VADER-Open-Sora/nosetests.xml
|
72 |
+
VADER-Open-Sora/coverage.xml
|
73 |
+
VADER-Open-Sora/*.cover
|
74 |
+
VADER-Open-Sora/*.py,cover
|
75 |
+
VADER-Open-Sora/.hypothesis/
|
76 |
+
VADER-Open-Sora/.pytest_cache/
|
77 |
+
VADER-Open-Sora/cover/
|
78 |
+
|
79 |
+
# Translations
|
80 |
+
VADER-Open-Sora/*.mo
|
81 |
+
VADER-Open-Sora/*.pot
|
82 |
+
|
83 |
+
# Django stuff:
|
84 |
+
VADER-Open-Sora/*.log
|
85 |
+
VADER-Open-Sora/local_settings.py
|
86 |
+
VADER-Open-Sora/db.sqlite3
|
87 |
+
VADER-Open-Sora/db.sqlite3-journal
|
88 |
+
|
89 |
+
# Flask stuff:
|
90 |
+
VADER-Open-Sora/instance/
|
91 |
+
VADER-Open-Sora/.webassets-cache
|
92 |
+
|
93 |
+
# Scrapy stuff:
|
94 |
+
VADER-Open-Sora/.scrapy
|
95 |
+
|
96 |
+
# Sphinx documentation
|
97 |
+
VADER-Open-Sora/docs/_build/
|
98 |
+
|
99 |
+
# PyBuilder
|
100 |
+
VADER-Open-Sora/.pybuilder/
|
101 |
+
VADER-Open-Sora/target/
|
102 |
+
|
103 |
+
# Jupyter Notebook
|
104 |
+
VADER-Open-Sora/.ipynb_checkpoints
|
105 |
+
|
106 |
+
# IPython
|
107 |
+
VADER-Open-Sora/profile_default/
|
108 |
+
VADER-Open-Sora/ipython_config.py
|
109 |
+
|
110 |
+
# pyenv
|
111 |
+
# For a library or package, you might want to ignore these files since the code is
|
112 |
+
# intended to run in multiple environments; otherwise, check them in:
|
113 |
+
# .python-version
|
114 |
+
|
115 |
+
# pipenv
|
116 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
117 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
118 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
119 |
+
# install all needed dependencies.
|
120 |
+
#Pipfile.lock
|
121 |
+
|
122 |
+
# poetry
|
123 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
124 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
125 |
+
# commonly ignored for libraries.
|
126 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
127 |
+
#poetry.lock
|
128 |
+
|
129 |
+
# pdm
|
130 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
131 |
+
#pdm.lock
|
132 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
133 |
+
# in version control.
|
134 |
+
# https://pdm.fming.dev/#use-with-ide
|
135 |
+
VADER-Open-Sora/.pdm.toml
|
136 |
+
|
137 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
138 |
+
VADER-Open-Sora/__pypackages__/
|
139 |
+
|
140 |
+
# Celery stuff
|
141 |
+
VADER-Open-Sora/celerybeat-schedule
|
142 |
+
VADER-Open-Sora/celerybeat.pid
|
143 |
+
|
144 |
+
# SageMath parsed files
|
145 |
+
VADER-Open-Sora/*.sage.py
|
146 |
+
|
147 |
+
# Environments
|
148 |
+
VADER-Open-Sora/.env
|
149 |
+
VADER-Open-Sora/.venv
|
150 |
+
VADER-Open-Sora/env/
|
151 |
+
VADER-Open-Sora/venv/
|
152 |
+
VADER-Open-Sora/ENV/
|
153 |
+
VADER-Open-Sora/env.bak/
|
154 |
+
VADER-Open-Sora/venv.bak/
|
155 |
+
|
156 |
+
|
157 |
+
# Spyder project settings
|
158 |
+
VADER-Open-Sora/.spyderproject
|
159 |
+
VADER-Open-Sora/.spyproject
|
160 |
+
|
161 |
+
# Rope project settings
|
162 |
+
VADER-Open-Sora/.ropeproject
|
163 |
+
|
164 |
+
# mkdocs documentation
|
165 |
+
VADER-Open-Sora/site
|
166 |
+
|
167 |
+
# mypy
|
168 |
+
VADER-Open-Sora/.mypy_cache/
|
169 |
+
VADER-Open-Sora/.dmypy.json
|
170 |
+
VADER-Open-Sora/dmypy.json
|
171 |
+
|
172 |
+
# Pyre type checker
|
173 |
+
VADER-Open-Sora/.pyre/
|
174 |
+
|
175 |
+
# pytype static type analyzer
|
176 |
+
VADER-Open-Sora/.pytype/
|
177 |
+
|
178 |
+
# Cython debug symbols
|
179 |
+
VADER-Open-Sora/cython_debug/
|
180 |
+
|
181 |
+
# PyCharm
|
182 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
183 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
184 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
185 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
186 |
+
VADER-Open-Sora/.idea/
|
187 |
+
VADER-Open-Sora/.vscode/
|
188 |
+
|
189 |
+
# macos
|
190 |
+
VADER-Open-Sora/*.DS_Store
|
191 |
+
|
192 |
+
# misc files
|
193 |
+
VADER-Open-Sora/data/
|
194 |
+
VADER-Open-Sora/dataset/
|
195 |
+
VADER-Open-Sora/runs/
|
196 |
+
VADER-Open-Sora/checkpoints/
|
197 |
+
VADER-Open-Sora/outputs/
|
198 |
+
VADER-Open-Sora/outputs
|
199 |
+
VADER-Open-Sora/samples/
|
200 |
+
VADER-Open-Sora/samples
|
201 |
+
VADER-Open-Sora/logs/
|
202 |
+
VADER-Open-Sora/pretrained_models/
|
203 |
+
VADER-Open-Sora/pretrained_models
|
204 |
+
VADER-Open-Sora/evaluation_results/
|
205 |
+
VADER-Open-Sora/cache/
|
206 |
+
VADER-Open-Sora/*.swp
|
207 |
+
|
208 |
+
# Secret files
|
209 |
+
VADER-Open-Sora/hostfile
|
210 |
+
VADER-Open-Sora/run.sh
|
211 |
+
VADER-Open-Sora/gradio_cached_examples/
|
212 |
+
VADER-Open-Sora/wandb/
|
213 |
+
|
214 |
+
# vae weights
|
215 |
+
VADER-Open-Sora/eval/vae/flolpips/weights/
|
216 |
+
|
217 |
+
# npm
|
218 |
+
VADER-Open-Sora/node_modules/
|
219 |
+
VADER-Open-Sora/package-lock.json
|
220 |
+
VADER-Open-Sora/package.json
|
221 |
+
|
222 |
+
# PLLaVA
|
223 |
+
VADER-Open-Sora/tools/caption/pllava_dir/PLLaVA/
|
224 |
+
|
225 |
+
# vbench
|
226 |
+
VADER-Open-Sora/vbench
|
227 |
+
VADER-Open-Sora/!eval/vbench
|
228 |
+
VADER-Open-Sora/vbench2_beta_i2v
|
229 |
+
|
230 |
+
# Video files
|
231 |
+
VADER-Open-Sora/project_dir
|
Core/actpred_scorer.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from transformers import VideoMAEFeatureExtractor, VideoMAEForVideoClassification
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
class ActPredScorer(torch.nn.Module):
|
7 |
+
|
8 |
+
def __init__(self, model_name = "MCG-NJU/videomae-base-finetuned-kinetics", num_frames = 16, device = 'cuda', dtype=torch.float32):
|
9 |
+
super().__init__()
|
10 |
+
self.model = VideoMAEForVideoClassification.from_pretrained(model_name, num_frames = num_frames, torch_dtype=dtype)
|
11 |
+
self.feature_extractor = VideoMAEFeatureExtractor.from_pretrained(model_name)
|
12 |
+
self.device = device
|
13 |
+
self.model.to(device)
|
14 |
+
|
15 |
+
def get_target_class_idx(self, target_action):
|
16 |
+
def mapping_func(x):
|
17 |
+
if 'piano' in x:
|
18 |
+
return 'playing piano'
|
19 |
+
if 'guitar' in x:
|
20 |
+
return 'playing guitar'
|
21 |
+
if 'doughnuts' in x:
|
22 |
+
return 'eating doughnuts'
|
23 |
+
if 'beer' in x:
|
24 |
+
return 'drinking beer'
|
25 |
+
if 'badminton' in x:
|
26 |
+
return 'playing badminton'
|
27 |
+
if 'cello' in x:
|
28 |
+
return 'playing cello'
|
29 |
+
if 'scooter' in x:
|
30 |
+
return 'riding scooter'
|
31 |
+
if 'ballet' in x:
|
32 |
+
return 'dancing ballet'
|
33 |
+
if 'pancake' in x:
|
34 |
+
return 'flipping pancake'
|
35 |
+
if 'violin' in x:
|
36 |
+
return 'playing violin'
|
37 |
+
if 'wood' in x:
|
38 |
+
return 'chopping wood'
|
39 |
+
if 'watermelon' in x:
|
40 |
+
return 'eating watermelon'
|
41 |
+
if 'jogging' in x:
|
42 |
+
return 'jogging'
|
43 |
+
else:
|
44 |
+
print(f"Please add your action mapping to ActPredScorer. Mapping not found for {x}")
|
45 |
+
raise NotImplementedError
|
46 |
+
|
47 |
+
|
48 |
+
try:
|
49 |
+
target_class_idx = self.model.config.label2id[target_action]
|
50 |
+
except:
|
51 |
+
target_class_idx = self.model.config.label2id[mapping_func(target_action)]
|
52 |
+
return target_class_idx
|
53 |
+
|
54 |
+
def get_loss_and_score(self, norm_vid, target_action):
|
55 |
+
''' video should be a torch array of dtype float, with values from 0-1, of dimension (num_frames, height, width, 3)'''
|
56 |
+
|
57 |
+
target_class_idx = self.get_target_class_idx(target_action)
|
58 |
+
outputs = self.model(norm_vid, labels = torch.tensor([target_class_idx]).to(self.device))
|
59 |
+
loss = outputs.loss
|
60 |
+
logits = outputs.logits
|
61 |
+
|
62 |
+
norm_logits = torch.exp(logits)/ (torch.exp(logits).sum())
|
63 |
+
norm_logits = norm_logits.squeeze()
|
64 |
+
|
65 |
+
score = norm_logits[target_class_idx]
|
66 |
+
return loss, score, self.get_pred_class(logits)
|
67 |
+
|
68 |
+
def get_pred_class(self, logits):
|
69 |
+
predicted_class_idx = logits.argmax(-1).item()
|
70 |
+
return self.model.config.id2label[predicted_class_idx]
|
71 |
+
|
72 |
+
def gen_rand_labels_file(labels_list, out_file, num_labels = 50):
|
73 |
+
idxs = np.random.choice(len(labels_list), num_labels, replace = False)
|
74 |
+
rand_labels = [labels_list[i] for i in idxs]
|
75 |
+
rand_labels.sort()
|
76 |
+
with open(out_file, 'w') as f:
|
77 |
+
for line in rand_labels:
|
78 |
+
f.write(f"{line}\n")
|
79 |
+
|
80 |
+
if __name__ == '__main__':
|
81 |
+
# import numpy as np
|
82 |
+
# scorer = ActPredScorer(num_frames = 7)
|
83 |
+
# video_torch = [torch.randn((3,256,256)).clamp(0,1) for _ in range(7)]
|
84 |
+
# encoding = scorer.feature_extractor(video_torch, do_rescale = False, return_tensors="pt")
|
85 |
+
# print(scorer.get_loss_and_score(video_torch))
|
86 |
+
scorer = ActPredScorer(num_frames = 7)
|
87 |
+
labels = scorer.model.config.id2label
|
88 |
+
|
Core/aesthetic_scorer.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Based on https://github.com/christophschuhmann/improved-aesthetic-predictor/blob/fe88a163f4661b4ddabba0751ff645e2e620746e/simple_inference.py
|
2 |
+
# import ipdb
|
3 |
+
# st = ipdb.set_trace
|
4 |
+
from importlib_resources import files
|
5 |
+
import torch
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
from transformers import CLIPModel, CLIPProcessor
|
9 |
+
from PIL import Image
|
10 |
+
ASSETS_PATH = files("assets")
|
11 |
+
# ASSETS_PATH = "assets"
|
12 |
+
|
13 |
+
class MLPDiff(nn.Module):
|
14 |
+
def __init__(self):
|
15 |
+
super().__init__()
|
16 |
+
self.layers = nn.Sequential(
|
17 |
+
nn.Linear(768, 1024),
|
18 |
+
nn.Dropout(0.2),
|
19 |
+
nn.Linear(1024, 128),
|
20 |
+
nn.Dropout(0.2),
|
21 |
+
nn.Linear(128, 64),
|
22 |
+
nn.Dropout(0.1),
|
23 |
+
nn.Linear(64, 16),
|
24 |
+
nn.Linear(16, 1),
|
25 |
+
)
|
26 |
+
|
27 |
+
|
28 |
+
def forward(self, embed):
|
29 |
+
return self.layers(embed)
|
30 |
+
|
31 |
+
|
32 |
+
class AestheticScorerDiff(torch.nn.Module):
|
33 |
+
def __init__(self, dtype):
|
34 |
+
super().__init__()
|
35 |
+
self.clip = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")
|
36 |
+
self.mlp = MLPDiff()
|
37 |
+
state_dict = torch.load(ASSETS_PATH.joinpath("sac+logos+ava1-l14-linearMSE.pth"))
|
38 |
+
self.mlp.load_state_dict(state_dict)
|
39 |
+
self.dtype = dtype
|
40 |
+
self.eval()
|
41 |
+
|
42 |
+
def __call__(self, images):
|
43 |
+
device = next(self.parameters()).device
|
44 |
+
embed = self.clip.get_image_features(pixel_values=images)
|
45 |
+
embed = embed / torch.linalg.vector_norm(embed, dim=-1, keepdim=True)
|
46 |
+
return self.mlp(embed).squeeze(1)
|
Core/compression_scorer.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapt from Cheng An Hsieh, et. al.: https://github.com/RewardMultiverse/reward-multiverse
|
2 |
+
from PIL import Image
|
3 |
+
import io
|
4 |
+
import numpy as np
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch
|
7 |
+
import torchvision
|
8 |
+
import albumentations as A
|
9 |
+
from transformers import CLIPModel, CLIPProcessor
|
10 |
+
# import ipdb
|
11 |
+
# st = ipdb.set_trace
|
12 |
+
|
13 |
+
def jpeg_compressibility(device):
|
14 |
+
def _fn(images):
|
15 |
+
'''
|
16 |
+
args:
|
17 |
+
images: shape NCHW
|
18 |
+
'''
|
19 |
+
org_type = images.dtype
|
20 |
+
if isinstance(images, torch.Tensor):
|
21 |
+
images = (images * 255).round().clamp(0, 255).to(torch.uint8).cpu().numpy()
|
22 |
+
images = images.transpose(0, 2, 3, 1) # NCHW -> NHWC
|
23 |
+
|
24 |
+
transform_images_tensor = torch.Tensor(np.array(images)).to(device, dtype=org_type)
|
25 |
+
transform_images_tensor = (transform_images_tensor.permute(0,3,1,2) / 255).clamp(0,1) # NHWC -> NCHW
|
26 |
+
transform_images_pil = [Image.fromarray(image) for image in images]
|
27 |
+
buffers = [io.BytesIO() for _ in transform_images_pil]
|
28 |
+
|
29 |
+
for image, buffer in zip(transform_images_pil, buffers):
|
30 |
+
image.save(buffer, format="JPEG", quality=95)
|
31 |
+
|
32 |
+
sizes = [buffer.tell() / 1000 for buffer in buffers]
|
33 |
+
|
34 |
+
return np.array(sizes), transform_images_tensor
|
35 |
+
|
36 |
+
return _fn
|
37 |
+
|
38 |
+
|
39 |
+
class MLP(nn.Module):
|
40 |
+
def __init__(self):
|
41 |
+
super().__init__()
|
42 |
+
self.layers = nn.Sequential(
|
43 |
+
nn.Linear(768, 512),
|
44 |
+
nn.ReLU(),
|
45 |
+
nn.Dropout(0.2),
|
46 |
+
nn.Linear(512, 256),
|
47 |
+
nn.ReLU(),
|
48 |
+
nn.Dropout(0.2),
|
49 |
+
nn.Linear(256, 128),
|
50 |
+
nn.ReLU(),
|
51 |
+
nn.Dropout(0.2),
|
52 |
+
nn.Linear(128, 32),
|
53 |
+
nn.ReLU(),
|
54 |
+
nn.Dropout(0.1),
|
55 |
+
nn.Linear(32, 1),
|
56 |
+
)
|
57 |
+
|
58 |
+
def forward(self, embed):
|
59 |
+
return self.layers(embed)
|
60 |
+
|
61 |
+
def jpegcompression_loss_fn(target=None,
|
62 |
+
grad_scale=0,
|
63 |
+
device=None,
|
64 |
+
accelerator=None,
|
65 |
+
torch_dtype=None,
|
66 |
+
reward_model_resume_from=None):
|
67 |
+
scorer = JpegCompressionScorer(dtype=torch_dtype, model_path=reward_model_resume_from).to(device, dtype=torch_dtype)
|
68 |
+
scorer.requires_grad_(False)
|
69 |
+
scorer.eval()
|
70 |
+
def loss_fn(im_pix_un):
|
71 |
+
if accelerator.mixed_precision == "fp16":
|
72 |
+
with accelerator.autocast():
|
73 |
+
rewards = scorer(im_pix_un)
|
74 |
+
else:
|
75 |
+
rewards = scorer(im_pix_un)
|
76 |
+
|
77 |
+
if target is None:
|
78 |
+
loss = rewards
|
79 |
+
else:
|
80 |
+
loss = abs(rewards - target)
|
81 |
+
return loss * grad_scale, rewards
|
82 |
+
return loss_fn
|
83 |
+
|
84 |
+
class JpegCompressionScorer(nn.Module):
|
85 |
+
def __init__(self, dtype=None, model_path=None):
|
86 |
+
super().__init__()
|
87 |
+
self.clip = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")
|
88 |
+
self.clip.requires_grad_(False)
|
89 |
+
self.score_generator = MLP()
|
90 |
+
|
91 |
+
if model_path:
|
92 |
+
state_dict = torch.load(model_path)
|
93 |
+
self.score_generator.load_state_dict(state_dict)
|
94 |
+
if dtype:
|
95 |
+
self.dtype = dtype
|
96 |
+
self.target_size = (224,224)
|
97 |
+
self.normalize = torchvision.transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
|
98 |
+
std=[0.26862954, 0.26130258, 0.27577711])
|
99 |
+
|
100 |
+
|
101 |
+
def set_device(self, device, inference_type):
|
102 |
+
# self.clip.to(device, dtype = inference_type)
|
103 |
+
self.score_generator.to(device) # , dtype = inference_type
|
104 |
+
|
105 |
+
def __call__(self, images):
|
106 |
+
device = next(self.parameters()).device
|
107 |
+
im_pix = torchvision.transforms.Resize(self.target_size)(images)
|
108 |
+
im_pix = self.normalize(im_pix).to(images.dtype)
|
109 |
+
embed = self.clip.get_image_features(pixel_values=im_pix)
|
110 |
+
embed = embed / torch.linalg.vector_norm(embed, dim=-1, keepdim=True)
|
111 |
+
return self.score_generator(embed).squeeze(1)
|
Core/prompts.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from importlib_resources import files
|
2 |
+
import os
|
3 |
+
import functools
|
4 |
+
import random
|
5 |
+
import inflect
|
6 |
+
|
7 |
+
IE = inflect.engine()
|
8 |
+
ASSETS_PATH = files("assets")
|
9 |
+
# ASSETS_PATH = "assets"
|
10 |
+
|
11 |
+
|
12 |
+
@functools.lru_cache(maxsize=None)
|
13 |
+
def _load_lines(path):
|
14 |
+
"""
|
15 |
+
Load lines from a file. First tries to load from `path` directly, and if that doesn't exist, searches the
|
16 |
+
`ddpo_pytorch/assets` directory for a file named `path`.
|
17 |
+
"""
|
18 |
+
if not os.path.exists(path):
|
19 |
+
newpath = ASSETS_PATH.joinpath(path)
|
20 |
+
if not os.path.exists(newpath):
|
21 |
+
raise FileNotFoundError(f"Could not find {path} or assets/{path}")
|
22 |
+
path = newpath
|
23 |
+
with open(path, "r") as f:
|
24 |
+
return [line.strip() for line in f.readlines()]
|
25 |
+
|
26 |
+
def hps_v2_all(nouns_file=None, activities_file=None):
|
27 |
+
return from_file("hps_v2_all.txt")
|
28 |
+
|
29 |
+
def hps_custom(nouns_file=None, activities_file=None):
|
30 |
+
return from_file("hps_custom.txt")
|
31 |
+
|
32 |
+
def hps_debug(nouns_file=None, activities_file=None):
|
33 |
+
return from_file("hps_debug.txt")
|
34 |
+
|
35 |
+
def hps_single(nouns_file=None, activities_file=None):
|
36 |
+
return from_file("hps_single.txt")
|
37 |
+
|
38 |
+
def kinetics_4rand(nouns_file=None, activities_file=None):
|
39 |
+
return from_file("kinetics_4rand.txt")
|
40 |
+
|
41 |
+
def kinetics_50rand(nouns_file=None, activities_file=None):
|
42 |
+
return from_file("kinetics_50rand.txt")
|
43 |
+
|
44 |
+
def simple_animals():
|
45 |
+
return from_file("simple_animals.txt")
|
46 |
+
|
47 |
+
def eval_simple_animals():
|
48 |
+
return from_file("eval_simple_animals.txt")
|
49 |
+
|
50 |
+
def eval_hps_v2_all(nouns_file=None, activities_file=None):
|
51 |
+
return from_file("hps_v2_all_eval.txt")
|
52 |
+
|
53 |
+
def chatgpt_custom(nouns_file=None, activities_file=None):
|
54 |
+
return from_file("chatgpt_custom.txt")
|
55 |
+
|
56 |
+
def chatgpt_custom_instruments(nouns_file=None, activities_file=None):
|
57 |
+
return from_file("chatgpt_custom_instruments.txt")
|
58 |
+
|
59 |
+
def chatgpt_custom_human(nouns_file=None, activities_file=None):
|
60 |
+
return from_file("chatgpt_custom_human.txt")
|
61 |
+
|
62 |
+
def chatgpt_custom_human_activity(nouns_file=None, activities_file=None):
|
63 |
+
return from_file("chatgpt_custom_human_activity.txt")
|
64 |
+
|
65 |
+
def chatgpt_custom_animal(nouns_file=None, activities_file=None):
|
66 |
+
return from_file("chatgpt_custom_animal.txt")
|
67 |
+
|
68 |
+
def chatgpt_custom_animal_sport(nouns_file=None, activities_file=None):
|
69 |
+
return from_file("chatgpt_custom_animal_sport.txt")
|
70 |
+
|
71 |
+
def chatgpt_custom_animal_sportV2(nouns_file=None, activities_file=None):
|
72 |
+
return from_file("chatgpt_custom_animal_sportV2.txt")
|
73 |
+
|
74 |
+
def chatgpt_custom_animal_clothes(nouns_file=None, activities_file=None):
|
75 |
+
return from_file("chatgpt_custom_animal_clothes.txt")
|
76 |
+
|
77 |
+
def chatgpt_custom_animal_clothesV2(nouns_file=None, activities_file=None):
|
78 |
+
return from_file("chatgpt_custom_animal_clothesV2.txt")
|
79 |
+
|
80 |
+
def chatgpt_custom_animal_clothesV3(nouns_file=None, activities_file=None):
|
81 |
+
return from_file("chatgpt_custom_animal_clothesV3.txt")
|
82 |
+
|
83 |
+
def chatgpt_custom_animal_technology(nouns_file=None, activities_file=None):
|
84 |
+
return from_file("chatgpt_custom_animal_technology.txt")
|
85 |
+
|
86 |
+
def chatgpt_custom_animal_housework(nouns_file=None, activities_file=None):
|
87 |
+
return from_file("chatgpt_custom_animal_housework.txt")
|
88 |
+
|
89 |
+
def chatgpt_custom_animal_action(nouns_file=None, activities_file=None):
|
90 |
+
return from_file("chatgpt_custom_animal_action.txt")
|
91 |
+
|
92 |
+
def chatgpt_custom_outdoor(nouns_file=None, activities_file=None):
|
93 |
+
return from_file("chatgpt_custom_outdoor.txt")
|
94 |
+
|
95 |
+
def chatgpt_custom_rainy(nouns_file=None, activities_file=None):
|
96 |
+
return from_file("chatgpt_custom_rainy.txt")
|
97 |
+
|
98 |
+
def chatgpt_custom_snowy(nouns_file=None, activities_file=None):
|
99 |
+
return from_file("chatgpt_custom_snowy.txt")
|
100 |
+
|
101 |
+
def chatgpt_custom_dog(nouns_file=None, activities_file=None):
|
102 |
+
return from_file("chatgpt_custom_dog.txt")
|
103 |
+
|
104 |
+
def chatgpt_custom_banana(nouns_file=None, activities_file=None):
|
105 |
+
return from_file("chatgpt_custom_banana.txt")
|
106 |
+
|
107 |
+
def chatgpt_custom_forest(nouns_file=None, activities_file=None):
|
108 |
+
return from_file("chatgpt_custom_forest.txt")
|
109 |
+
|
110 |
+
def chatgpt_custom_forest_vivid(nouns_file=None, activities_file=None):
|
111 |
+
return from_file("chatgpt_custom_forest_vivid.txt")
|
112 |
+
|
113 |
+
def chatgpt_custom_cruel_animal(nouns_file=None, activities_file=None):
|
114 |
+
return from_file("chatgpt_custom_cruel_animal.txt")
|
115 |
+
|
116 |
+
def chatgpt_custom_cruel_animal2(nouns_file=None, activities_file=None):
|
117 |
+
return from_file("chatgpt_custom_cruel_animal2.txt")
|
118 |
+
|
119 |
+
def chatgpt_custom_bottle_glass(nouns_file=None, activities_file=None):
|
120 |
+
return from_file("chatgpt_custom_bottle_glass.txt")
|
121 |
+
|
122 |
+
def chatgpt_custom_book_cup(nouns_file=None, activities_file=None):
|
123 |
+
return from_file("chatgpt_custom_book_cup.txt")
|
124 |
+
|
125 |
+
def chatgpt_custom_book_cup_character(nouns_file=None, activities_file=None):
|
126 |
+
return from_file("chatgpt_custom_book_cup_character.txt")
|
127 |
+
|
128 |
+
def chatgpt_custom_cute(nouns_file=None, activities_file=None):
|
129 |
+
return from_file("chatgpt_custom_cute.txt")
|
130 |
+
|
131 |
+
def chatgpt_custom_ice(nouns_file=None, activities_file=None):
|
132 |
+
return from_file("chatgpt_custom_ice.txt")
|
133 |
+
|
134 |
+
def chatgpt_custom_compression(nouns_file=None, activities_file=None):
|
135 |
+
return from_file("chatgpt_custom_compression.txt")
|
136 |
+
|
137 |
+
def chatgpt_custom_compression_animals(nouns_file=None, activities_file=None):
|
138 |
+
return from_file("chatgpt_custom_compression_animals.txt")
|
139 |
+
|
140 |
+
def chatgpt_custom_actpred(nouns_file=None, activities_file=None):
|
141 |
+
return from_file("chatgpt_custom_actpred.txt")
|
142 |
+
|
143 |
+
def chatgpt_custom_actpred2(nouns_file=None, activities_file=None):
|
144 |
+
return from_file("chatgpt_custom_actpred2.txt")
|
145 |
+
|
146 |
+
def chatgpt_custom_instruments_unseen(nouns_file=None, activities_file=None):
|
147 |
+
return from_file("chatgpt_custom_instruments_unseen.txt")
|
148 |
+
|
149 |
+
def from_file(path, low=None, high=None, **kwargs):
|
150 |
+
prompts = _load_lines(path)[low:high]
|
151 |
+
return random.choice(prompts), {}
|
152 |
+
|
153 |
+
def from_str(_str, **kwargs):
|
154 |
+
return _str, {}
|
155 |
+
|
156 |
+
def nouns_activities(nouns_file, activities_file, **kwargs):
|
157 |
+
nouns = _load_lines(nouns_file)
|
158 |
+
activities = _load_lines(activities_file)
|
159 |
+
return f"{IE.a(random.choice(nouns))} {random.choice(activities)}", {}
|
Core/weather_scorer.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copy from Cheng An Hsieh, et. al.: https://github.com/RewardMultiverse/reward-multiverse
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torchvision
|
5 |
+
from transformers import CLIPModel, CLIPProcessor
|
6 |
+
|
7 |
+
class SimpleCNN(nn.Module): # parameter = 6333513
|
8 |
+
def __init__(self, num_class = None):
|
9 |
+
super(SimpleCNN, self).__init__()
|
10 |
+
self.layer1 = nn.Sequential(
|
11 |
+
nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1),
|
12 |
+
nn.ReLU(),
|
13 |
+
nn.MaxPool2d(kernel_size=2, stride=2))
|
14 |
+
self.layer2 = nn.Sequential(
|
15 |
+
nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1),
|
16 |
+
nn.ReLU(),
|
17 |
+
nn.MaxPool2d(kernel_size=2, stride=2))
|
18 |
+
self.layer3 = nn.Sequential(
|
19 |
+
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
|
20 |
+
nn.ReLU(),
|
21 |
+
nn.MaxPool2d(kernel_size=2, stride=2))
|
22 |
+
self.layer4 = nn.Sequential(
|
23 |
+
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
|
24 |
+
nn.ReLU(),
|
25 |
+
nn.MaxPool2d(kernel_size=2, stride=2))
|
26 |
+
self.fc1 = nn.Linear(128 * 32 * 32, 1000)
|
27 |
+
self.fc2 = nn.Linear(1000, num_class)
|
28 |
+
|
29 |
+
def forward(self, x):
|
30 |
+
x = self.layer1(x)
|
31 |
+
# print("x1", x.shape)
|
32 |
+
x = self.layer2(x)
|
33 |
+
# print("x2", x.shape)
|
34 |
+
x = self.layer3(x)
|
35 |
+
# print("x3", x.shape)
|
36 |
+
x = self.layer4(x)
|
37 |
+
# print("x4", x.shape)
|
38 |
+
|
39 |
+
x = x.reshape(x.size(0), -1)
|
40 |
+
# print("x reshape", x.shape)
|
41 |
+
x = torch.relu(self.fc1(x))
|
42 |
+
x = self.fc2(x)
|
43 |
+
return x
|
44 |
+
|
45 |
+
|
46 |
+
class MLP(nn.Module):
|
47 |
+
def __init__(self):
|
48 |
+
super().__init__()
|
49 |
+
self.layers = nn.Sequential( # regression
|
50 |
+
nn.Linear(768, 1024),
|
51 |
+
nn.Dropout(0.2),
|
52 |
+
nn.Linear(1024, 128),
|
53 |
+
nn.Dropout(0.2),
|
54 |
+
nn.Linear(128, 64),
|
55 |
+
nn.Dropout(0.1),
|
56 |
+
nn.Linear(64, 16),
|
57 |
+
nn.Linear(16, 1),
|
58 |
+
nn.Sigmoid()
|
59 |
+
)
|
60 |
+
|
61 |
+
# self.layers = nn.Sequential( # classification
|
62 |
+
# nn.Linear(768, 1024),
|
63 |
+
# nn.Dropout(0.2),
|
64 |
+
# nn.Linear(1024, 128),
|
65 |
+
# nn.Dropout(0.2),
|
66 |
+
# nn.Linear(128, 64),
|
67 |
+
# nn.Dropout(0.1),
|
68 |
+
# nn.Linear(64, 16),
|
69 |
+
# nn.Linear(16, 2)
|
70 |
+
# )
|
71 |
+
|
72 |
+
def forward(self, embed):
|
73 |
+
return self.layers(embed)
|
74 |
+
|
75 |
+
class MLP_Resnet(nn.Module):
|
76 |
+
def __init__(self, num_class):
|
77 |
+
super().__init__()
|
78 |
+
self.layers = nn.Sequential(
|
79 |
+
nn.Linear(1000, 128),
|
80 |
+
# nn.Dropout(0.2),
|
81 |
+
nn.Linear(128, 64),
|
82 |
+
# nn.Dropout(0.2),
|
83 |
+
nn.Linear(64, 16),
|
84 |
+
nn.Linear(16, num_class),
|
85 |
+
)
|
86 |
+
|
87 |
+
def forward(self, embed):
|
88 |
+
return self.layers(embed)
|
89 |
+
|
90 |
+
|
91 |
+
def weather_loss_fn(target=None, # TODO: use config.task to decide returned loss_fn
|
92 |
+
grad_scale=0,
|
93 |
+
device=None,
|
94 |
+
accelerator=None,
|
95 |
+
torch_dtype=None,
|
96 |
+
reward_model_resume_from=None,
|
97 |
+
num_of_labels=None):
|
98 |
+
scorer = WeatherScorer(dtype=torch_dtype, model_path=reward_model_resume_from, num_class=num_of_labels).to(device, dtype=torch_dtype)
|
99 |
+
scorer.requires_grad_(False)
|
100 |
+
scorer.eval()
|
101 |
+
|
102 |
+
def loss_fn(im_pix_un):
|
103 |
+
if accelerator.mixed_precision == "fp16":
|
104 |
+
with accelerator.autocast():
|
105 |
+
rewards = scorer(im_pix_un)
|
106 |
+
else:
|
107 |
+
rewards = scorer(im_pix_un)
|
108 |
+
|
109 |
+
target_tensors = torch.full((rewards.shape[0],), target).to(rewards.device, dtype=rewards.dtype) # regression
|
110 |
+
criterion = torch.nn.MSELoss(reduction = "sum") # regression
|
111 |
+
# target_tensors = torch.full((rewards.shape[0],), target).to(rewards.device, dtype=torch.long) # classification
|
112 |
+
# criterion = nn.CrossEntropyLoss(reduction="sum") # classification
|
113 |
+
loss = criterion(rewards, target_tensors)
|
114 |
+
return loss * grad_scale, rewards #nn.Softmax(dim=-1)(rewards) # rewards (reg)
|
115 |
+
return loss_fn
|
116 |
+
|
117 |
+
|
118 |
+
class WeatherModel(nn.Module):
|
119 |
+
def __init__(self, num_class = None):
|
120 |
+
super().__init__()
|
121 |
+
self.embed_model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)
|
122 |
+
self.score_model = MLP_Resnet(num_class)
|
123 |
+
def __call__(self, im):
|
124 |
+
return self.score_model(self.embed_model(im))
|
125 |
+
|
126 |
+
|
127 |
+
class WeatherScorer(nn.Module): # Reward model
|
128 |
+
def __init__(self, dtype=None, model_path = None, num_class = None):
|
129 |
+
super().__init__()
|
130 |
+
self.clip = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")
|
131 |
+
self.clip.requires_grad_(False)
|
132 |
+
self.clip.eval()
|
133 |
+
self.score_generator = MLP()
|
134 |
+
# self.score_generator = WeatherModel(num_class) # resnet + mlp
|
135 |
+
if model_path:
|
136 |
+
state_dict = torch.load(model_path)
|
137 |
+
self.score_generator.load_state_dict(state_dict)
|
138 |
+
self.score_generator.requires_grad_(False)
|
139 |
+
self.score_generator.eval()
|
140 |
+
# self.clip.requires_grad_(False)
|
141 |
+
# self.clip.eval()
|
142 |
+
else:
|
143 |
+
self.score_generator.requires_grad_(True)
|
144 |
+
if dtype:
|
145 |
+
self.dtype = dtype
|
146 |
+
self.target_size = (224,224) # resnet 224, cnn 512 (use 224 for both...?)
|
147 |
+
self.normalize = torchvision.transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
|
148 |
+
std=[0.26862954, 0.26130258, 0.27577711])
|
149 |
+
|
150 |
+
def set_device(self, device, inference_type):
|
151 |
+
self.clip.to(device, dtype = inference_type) # uncomment for mlp
|
152 |
+
self.score_generator.to(device) # dtype = inference_dtype
|
153 |
+
|
154 |
+
def __call__(self, images):
|
155 |
+
device = next(self.parameters()).device
|
156 |
+
im_pix = torchvision.transforms.Resize(self.target_size)(images)
|
157 |
+
im_pix = self.normalize(im_pix).to(images.dtype)
|
158 |
+
embed = self.clip.get_image_features(pixel_values=im_pix)
|
159 |
+
embed = embed / torch.linalg.vector_norm(embed, dim=-1, keepdim=True)
|
160 |
+
return self.score_generator(embed).squeeze(1) # CLIP + MLP
|
161 |
+
# return self.score_generator(im_pix).squeeze(1) # for simpleCNN
|
VADER-VideoCrafter/License
ADDED
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
This license applies to the source codes that are open sourced in connection with the VideoCrafter1.
|
2 |
+
|
3 |
+
Copyright (C) 2023 THL A29 Limited, a Tencent company.
|
4 |
+
|
5 |
+
Apache License
|
6 |
+
Version 2.0, January 2004
|
7 |
+
http://www.apache.org/licenses/
|
8 |
+
|
9 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
10 |
+
|
11 |
+
1. Definitions.
|
12 |
+
|
13 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
14 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
15 |
+
|
16 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
17 |
+
the copyright owner that is granting the License.
|
18 |
+
|
19 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
20 |
+
other entities that control, are controlled by, or are under common
|
21 |
+
control with that entity. For the purposes of this definition,
|
22 |
+
"control" means (i) the power, direct or indirect, to cause the
|
23 |
+
direction or management of such entity, whether by contract or
|
24 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
25 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
26 |
+
|
27 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
28 |
+
exercising permissions granted by this License.
|
29 |
+
|
30 |
+
"Source" form shall mean the preferred form for making modifications,
|
31 |
+
including but not limited to software source code, documentation
|
32 |
+
source, and configuration files.
|
33 |
+
|
34 |
+
"Object" form shall mean any form resulting from mechanical
|
35 |
+
transformation or translation of a Source form, including but
|
36 |
+
not limited to compiled object code, generated documentation,
|
37 |
+
and conversions to other media types.
|
38 |
+
|
39 |
+
"Work" shall mean the work of authorship, whether in Source or
|
40 |
+
Object form, made available under the License, as indicated by a
|
41 |
+
copyright notice that is included in or attached to the work
|
42 |
+
(an example is provided in the Appendix below).
|
43 |
+
|
44 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
45 |
+
form, that is based on (or derived from) the Work and for which the
|
46 |
+
editorial revisions, annotations, elaborations, or other modifications
|
47 |
+
represent, as a whole, an original work of authorship. For the purposes
|
48 |
+
of this License, Derivative Works shall not include works that remain
|
49 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
50 |
+
the Work and Derivative Works thereof.
|
51 |
+
|
52 |
+
"Contribution" shall mean any work of authorship, including
|
53 |
+
the original version of the Work and any modifications or additions
|
54 |
+
to that Work or Derivative Works thereof, that is intentionally
|
55 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
56 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
57 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
58 |
+
means any form of electronic, verbal, or written communication sent
|
59 |
+
to the Licensor or its representatives, including but not limited to
|
60 |
+
communication on electronic mailing lists, source code control systems,
|
61 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
62 |
+
Licensor for the purpose of discussing and improving the Work, but
|
63 |
+
excluding communication that is conspicuously marked or otherwise
|
64 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
65 |
+
|
66 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
67 |
+
on behalf of whom a Contribution has been received by Licensor and
|
68 |
+
subsequently incorporated within the Work.
|
69 |
+
|
70 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
71 |
+
this License, each Contributor hereby grants to You a perpetual,
|
72 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
73 |
+
copyright license to reproduce, prepare Derivative Works of,
|
74 |
+
publicly display, publicly perform, sublicense, and distribute the
|
75 |
+
Work and such Derivative Works in Source or Object form.
|
76 |
+
|
77 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
78 |
+
this License, each Contributor hereby grants to You a perpetual,
|
79 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
80 |
+
(except as stated in this section) patent license to make, have made,
|
81 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
82 |
+
where such license applies only to those patent claims licensable
|
83 |
+
by such Contributor that are necessarily infringed by their
|
84 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
85 |
+
with the Work to which such Contribution(s) was submitted. If You
|
86 |
+
institute patent litigation against any entity (including a
|
87 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
88 |
+
or a Contribution incorporated within the Work constitutes direct
|
89 |
+
or contributory patent infringement, then any patent licenses
|
90 |
+
granted to You under this License for that Work shall terminate
|
91 |
+
as of the date such litigation is filed.
|
92 |
+
|
93 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
94 |
+
Work or Derivative Works thereof in any medium, with or without
|
95 |
+
modifications, and in Source or Object form, provided that You
|
96 |
+
meet the following conditions:
|
97 |
+
|
98 |
+
(a) You must give any other recipients of the Work or
|
99 |
+
Derivative Works a copy of this License; and
|
100 |
+
|
101 |
+
(b) You must cause any modified files to carry prominent notices
|
102 |
+
stating that You changed the files; and
|
103 |
+
|
104 |
+
(c) You must retain, in the Source form of any Derivative Works
|
105 |
+
that You distribute, all copyright, patent, trademark, and
|
106 |
+
attribution notices from the Source form of the Work,
|
107 |
+
excluding those notices that do not pertain to any part of
|
108 |
+
the Derivative Works; and
|
109 |
+
|
110 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
111 |
+
distribution, then any Derivative Works that You distribute must
|
112 |
+
include a readable copy of the attribution notices contained
|
113 |
+
within such NOTICE file, excluding those notices that do not
|
114 |
+
pertain to any part of the Derivative Works, in at least one
|
115 |
+
of the following places: within a NOTICE text file distributed
|
116 |
+
as part of the Derivative Works; within the Source form or
|
117 |
+
documentation, if provided along with the Derivative Works; or,
|
118 |
+
within a display generated by the Derivative Works, if and
|
119 |
+
wherever such third-party notices normally appear. The contents
|
120 |
+
of the NOTICE file are for informational purposes only and
|
121 |
+
do not modify the License. You may add Your own attribution
|
122 |
+
notices within Derivative Works that You distribute, alongside
|
123 |
+
or as an addendum to the NOTICE text from the Work, provided
|
124 |
+
that such additional attribution notices cannot be construed
|
125 |
+
as modifying the License.
|
126 |
+
|
127 |
+
You may add Your own copyright statement to Your modifications and
|
128 |
+
may provide additional or different license terms and conditions
|
129 |
+
for use, reproduction, or distribution of Your modifications, or
|
130 |
+
for any such Derivative Works as a whole, provided Your use,
|
131 |
+
reproduction, and distribution of the Work otherwise complies with
|
132 |
+
the conditions stated in this License.
|
133 |
+
|
134 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
135 |
+
any Contribution intentionally submitted for inclusion in the Work
|
136 |
+
by You to the Licensor shall be under the terms and conditions of
|
137 |
+
this License, without any additional terms or conditions.
|
138 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
139 |
+
the terms of any separate license agreement you may have executed
|
140 |
+
with Licensor regarding such Contributions.
|
141 |
+
|
142 |
+
6. Trademarks. This License does not grant permission to use the trade
|
143 |
+
names, trademarks, service marks, or product names of the Licensor,
|
144 |
+
except as required for reasonable and customary use in describing the
|
145 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
146 |
+
|
147 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
148 |
+
agreed to in writing, Licensor provides the Work (and each
|
149 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
150 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
151 |
+
implied, including, without limitation, any warranties or conditions
|
152 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
153 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
154 |
+
appropriateness of using or redistributing the Work and assume any
|
155 |
+
risks associated with Your exercise of permissions under this License.
|
156 |
+
|
157 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
158 |
+
whether in tort (including negligence), contract, or otherwise,
|
159 |
+
unless required by applicable law (such as deliberate and grossly
|
160 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
161 |
+
liable to You for damages, including any direct, indirect, special,
|
162 |
+
incidental, or consequential damages of any character arising as a
|
163 |
+
result of this License or out of the use or inability to use the
|
164 |
+
Work (including but not limited to damages for loss of goodwill,
|
165 |
+
work stoppage, computer failure or malfunction, or any and all
|
166 |
+
other commercial damages or losses), even if such Contributor
|
167 |
+
has been advised of the possibility of such damages.
|
168 |
+
|
169 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
170 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
171 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
172 |
+
or other liability obligations and/or rights consistent with this
|
173 |
+
License. However, in accepting such obligations, You may act only
|
174 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
175 |
+
of any other Contributor, and only if You agree to indemnify,
|
176 |
+
defend, and hold each Contributor harmless for any liability
|
177 |
+
incurred by, or claims asserted against, such Contributor by reason
|
178 |
+
of your accepting any such warranty or additional liability.
|
179 |
+
|
180 |
+
10. This code is provided for research purposes only and is
|
181 |
+
not to be used for any commercial purposes. By using this code,
|
182 |
+
you agree that it will be used solely for academic research, scholarly work,
|
183 |
+
and non-commercial activities. Any use of this code for commercial purposes,
|
184 |
+
including but not limited to, selling, distributing, or incorporating it into
|
185 |
+
commercial products or services, is strictly prohibited. Violation of this
|
186 |
+
clause may result in legal actions and penalties.
|
187 |
+
|
188 |
+
END OF TERMS AND CONDITIONS
|
189 |
+
|
190 |
+
APPENDIX: How to apply the Apache License to your work.
|
191 |
+
|
192 |
+
To apply the Apache License to your work, attach the following
|
193 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
194 |
+
replaced with your own identifying information. (Don't include
|
195 |
+
the brackets!) The text should be enclosed in the appropriate
|
196 |
+
comment syntax for the file format. We also recommend that a
|
197 |
+
file or class name and description of purpose be included on the
|
198 |
+
same "printed page" as the copyright notice for easier
|
199 |
+
identification within third-party archives.
|
200 |
+
|
201 |
+
Copyright [yyyy] [name of copyright owner]
|
202 |
+
|
203 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
204 |
+
you may not use this file except in compliance with the License.
|
205 |
+
You may obtain a copy of the License at
|
206 |
+
|
207 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
208 |
+
|
209 |
+
Unless required by applicable law or agreed to in writing, software
|
210 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
211 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
212 |
+
See the License for the specific language governing permissions and
|
213 |
+
limitations under the License.
|
214 |
+
|
215 |
+
|
216 |
+
Other dependencies and licenses (if such optional components are used):
|
217 |
+
|
218 |
+
|
219 |
+
Components under BSD 3-Clause License:
|
220 |
+
------------------------------------------------
|
221 |
+
1. numpy
|
222 |
+
Copyright (c) 2005-2022, NumPy Developers.
|
223 |
+
All rights reserved.
|
224 |
+
|
225 |
+
2. pytorch
|
226 |
+
Copyright (c) 2016- Facebook, Inc (Adam Paszke)
|
227 |
+
Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
|
228 |
+
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
|
229 |
+
Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
|
230 |
+
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
|
231 |
+
Copyright (c) 2011-2013 NYU (Clement Farabet)
|
232 |
+
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
|
233 |
+
Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
|
234 |
+
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
|
235 |
+
|
236 |
+
3. torchvision
|
237 |
+
Copyright (c) Soumith Chintala 2016,
|
238 |
+
All rights reserved.
|
239 |
+
|
240 |
+
Redistribution and use in source and binary forms, with or without
|
241 |
+
modification, are permitted provided that the following conditions are met:
|
242 |
+
|
243 |
+
* Redistributions of source code must retain the above copyright notice, this
|
244 |
+
list of conditions and the following disclaimer.
|
245 |
+
|
246 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
247 |
+
this list of conditions and the following disclaimer in the documentation
|
248 |
+
and/or other materials provided with the distribution.
|
249 |
+
|
250 |
+
* Neither the name of the copyright holder nor the names of its
|
251 |
+
contributors may be used to endorse or promote products derived from
|
252 |
+
this software without specific prior written permission.
|
253 |
+
|
254 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
255 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
256 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
257 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
258 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
259 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
260 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
261 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
262 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
263 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
264 |
+
|
265 |
+
Component under Apache v2 License:
|
266 |
+
-----------------------------------------------------
|
267 |
+
1. timm
|
268 |
+
Copyright 2019 Ross Wightman
|
269 |
+
|
270 |
+
Apache License
|
271 |
+
Version 2.0, January 2004
|
272 |
+
http://www.apache.org/licenses/
|
273 |
+
|
274 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
275 |
+
|
276 |
+
1. Definitions.
|
277 |
+
|
278 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
279 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
280 |
+
|
281 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
282 |
+
the copyright owner that is granting the License.
|
283 |
+
|
284 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
285 |
+
other entities that control, are controlled by, or are under common
|
286 |
+
control with that entity. For the purposes of this definition,
|
287 |
+
"control" means (i) the power, direct or indirect, to cause the
|
288 |
+
direction or management of such entity, whether by contract or
|
289 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
290 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
291 |
+
|
292 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
293 |
+
exercising permissions granted by this License.
|
294 |
+
|
295 |
+
"Source" form shall mean the preferred form for making modifications,
|
296 |
+
including but not limited to software source code, documentation
|
297 |
+
source, and configuration files.
|
298 |
+
|
299 |
+
"Object" form shall mean any form resulting from mechanical
|
300 |
+
transformation or translation of a Source form, including but
|
301 |
+
not limited to compiled object code, generated documentation,
|
302 |
+
and conversions to other media types.
|
303 |
+
|
304 |
+
"Work" shall mean the work of authorship, whether in Source or
|
305 |
+
Object form, made available under the License, as indicated by a
|
306 |
+
copyright notice that is included in or attached to the work
|
307 |
+
(an example is provided in the Appendix below).
|
308 |
+
|
309 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
310 |
+
form, that is based on (or derived from) the Work and for which the
|
311 |
+
editorial revisions, annotations, elaborations, or other modifications
|
312 |
+
represent, as a whole, an original work of authorship. For the purposes
|
313 |
+
of this License, Derivative Works shall not include works that remain
|
314 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
315 |
+
the Work and Derivative Works thereof.
|
316 |
+
|
317 |
+
"Contribution" shall mean any work of authorship, including
|
318 |
+
the original version of the Work and any modifications or additions
|
319 |
+
to that Work or Derivative Works thereof, that is intentionally
|
320 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
321 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
322 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
323 |
+
means any form of electronic, verbal, or written communication sent
|
324 |
+
to the Licensor or its representatives, including but not limited to
|
325 |
+
communication on electronic mailing lists, source code control systems,
|
326 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
327 |
+
Licensor for the purpose of discussing and improving the Work, but
|
328 |
+
excluding communication that is conspicuously marked or otherwise
|
329 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
330 |
+
|
331 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
332 |
+
on behalf of whom a Contribution has been received by Licensor and
|
333 |
+
subsequently incorporated within the Work.
|
334 |
+
|
335 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
336 |
+
this License, each Contributor hereby grants to You a perpetual,
|
337 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
338 |
+
copyright license to reproduce, prepare Derivative Works of,
|
339 |
+
publicly display, publicly perform, sublicense, and distribute the
|
340 |
+
Work and such Derivative Works in Source or Object form.
|
341 |
+
|
342 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
343 |
+
this License, each Contributor hereby grants to You a perpetual,
|
344 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
345 |
+
(except as stated in this section) patent license to make, have made,
|
346 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
347 |
+
where such license applies only to those patent claims licensable
|
348 |
+
by such Contributor that are necessarily infringed by their
|
349 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
350 |
+
with the Work to which such Contribution(s) was submitted. If You
|
351 |
+
institute patent litigation against any entity (including a
|
352 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
353 |
+
or a Contribution incorporated within the Work constitutes direct
|
354 |
+
or contributory patent infringement, then any patent licenses
|
355 |
+
granted to You under this License for that Work shall terminate
|
356 |
+
as of the date such litigation is filed.
|
357 |
+
|
358 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
359 |
+
Work or Derivative Works thereof in any medium, with or without
|
360 |
+
modifications, and in Source or Object form, provided that You
|
361 |
+
meet the following conditions:
|
362 |
+
|
363 |
+
(a) You must give any other recipients of the Work or
|
364 |
+
Derivative Works a copy of this License; and
|
365 |
+
|
366 |
+
(b) You must cause any modified files to carry prominent notices
|
367 |
+
stating that You changed the files; and
|
368 |
+
|
369 |
+
(c) You must retain, in the Source form of any Derivative Works
|
370 |
+
that You distribute, all copyright, patent, trademark, and
|
371 |
+
attribution notices from the Source form of the Work,
|
372 |
+
excluding those notices that do not pertain to any part of
|
373 |
+
the Derivative Works; and
|
374 |
+
|
375 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
376 |
+
distribution, then any Derivative Works that You distribute must
|
377 |
+
include a readable copy of the attribution notices contained
|
378 |
+
within such NOTICE file, excluding those notices that do not
|
379 |
+
pertain to any part of the Derivative Works, in at least one
|
380 |
+
of the following places: within a NOTICE text file distributed
|
381 |
+
as part of the Derivative Works; within the Source form or
|
382 |
+
documentation, if provided along with the Derivative Works; or,
|
383 |
+
within a display generated by the Derivative Works, if and
|
384 |
+
wherever such third-party notices normally appear. The contents
|
385 |
+
of the NOTICE file are for informational purposes only and
|
386 |
+
do not modify the License. You may add Your own attribution
|
387 |
+
notices within Derivative Works that You distribute, alongside
|
388 |
+
or as an addendum to the NOTICE text from the Work, provided
|
389 |
+
that such additional attribution notices cannot be construed
|
390 |
+
as modifying the License.
|
391 |
+
|
392 |
+
You may add Your own copyright statement to Your modifications and
|
393 |
+
may provide additional or different license terms and conditions
|
394 |
+
for use, reproduction, or distribution of Your modifications, or
|
395 |
+
for any such Derivative Works as a whole, provided Your use,
|
396 |
+
reproduction, and distribution of the Work otherwise complies with
|
397 |
+
the conditions stated in this License.
|
398 |
+
|
399 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
400 |
+
any Contribution intentionally submitted for inclusion in the Work
|
401 |
+
by You to the Licensor shall be under the terms and conditions of
|
402 |
+
this License, without any additional terms or conditions.
|
403 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
404 |
+
the terms of any separate license agreement you may have executed
|
405 |
+
with Licensor regarding such Contributions.
|
406 |
+
|
407 |
+
6. Trademarks. This License does not grant permission to use the trade
|
408 |
+
names, trademarks, service marks, or product names of the Licensor,
|
409 |
+
except as required for reasonable and customary use in describing the
|
410 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
411 |
+
|
412 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
413 |
+
agreed to in writing, Licensor provides the Work (and each
|
414 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
415 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
416 |
+
implied, including, without limitation, any warranties or conditions
|
417 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
418 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
419 |
+
appropriateness of using or redistributing the Work and assume any
|
420 |
+
risks associated with Your exercise of permissions under this License.
|
421 |
+
|
422 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
423 |
+
whether in tort (including negligence), contract, or otherwise,
|
424 |
+
unless required by applicable law (such as deliberate and grossly
|
425 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
426 |
+
liable to You for damages, including any direct, indirect, special,
|
427 |
+
incidental, or consequential damages of any character arising as a
|
428 |
+
result of this License or out of the use or inability to use the
|
429 |
+
Work (including but not limited to damages for loss of goodwill,
|
430 |
+
work stoppage, computer failure or malfunction, or any and all
|
431 |
+
other commercial damages or losses), even if such Contributor
|
432 |
+
has been advised of the possibility of such damages.
|
433 |
+
|
434 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
435 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
436 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
437 |
+
or other liability obligations and/or rights consistent with this
|
438 |
+
License. However, in accepting such obligations, You may act only
|
439 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
440 |
+
of any other Contributor, and only if You agree to indemnify,
|
441 |
+
defend, and hold each Contributor harmless for any liability
|
442 |
+
incurred by, or claims asserted against, such Contributor by reason
|
443 |
+
of your accepting any such warranty or additional liability.
|
444 |
+
|
445 |
+
END OF TERMS AND CONDITIONS
|
446 |
+
|
447 |
+
APPENDIX: How to apply the Apache License to your work.
|
448 |
+
|
449 |
+
To apply the Apache License to your work, attach the following
|
450 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
451 |
+
replaced with your own identifying information. (Don't include
|
452 |
+
the brackets!) The text should be enclosed in the appropriate
|
453 |
+
comment syntax for the file format. We also recommend that a
|
454 |
+
file or class name and description of purpose be included on the
|
455 |
+
same "printed page" as the copyright notice for easier
|
456 |
+
identification within third-party archives.
|
457 |
+
|
458 |
+
Copyright [yyyy] [name of copyright owner]
|
459 |
+
|
460 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
461 |
+
you may not use this file except in compliance with the License.
|
462 |
+
You may obtain a copy of the License at
|
463 |
+
|
464 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
465 |
+
|
466 |
+
Unless required by applicable law or agreed to in writing, software
|
467 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
468 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
469 |
+
See the License for the specific language governing permissions and
|
470 |
+
limitations under the License.
|
VADER-VideoCrafter/configs/inference_i2v_512_v1.0.yaml
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: lvdm.models.ddpm3d.LatentVisualDiffusion
|
3 |
+
params:
|
4 |
+
linear_start: 0.00085
|
5 |
+
linear_end: 0.012
|
6 |
+
num_timesteps_cond: 1
|
7 |
+
timesteps: 1000
|
8 |
+
first_stage_key: video
|
9 |
+
cond_stage_key: caption
|
10 |
+
cond_stage_trainable: false
|
11 |
+
conditioning_key: crossattn
|
12 |
+
image_size:
|
13 |
+
- 40
|
14 |
+
- 64
|
15 |
+
channels: 4
|
16 |
+
scale_by_std: false
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: false
|
19 |
+
uncond_type: empty_seq
|
20 |
+
use_scale: true
|
21 |
+
scale_b: 0.7
|
22 |
+
finegrained: true
|
23 |
+
unet_config:
|
24 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
25 |
+
params:
|
26 |
+
in_channels: 4
|
27 |
+
out_channels: 4
|
28 |
+
model_channels: 320
|
29 |
+
attention_resolutions:
|
30 |
+
- 4
|
31 |
+
- 2
|
32 |
+
- 1
|
33 |
+
num_res_blocks: 2
|
34 |
+
channel_mult:
|
35 |
+
- 1
|
36 |
+
- 2
|
37 |
+
- 4
|
38 |
+
- 4
|
39 |
+
num_head_channels: 64
|
40 |
+
transformer_depth: 1
|
41 |
+
context_dim: 1024
|
42 |
+
use_linear: true
|
43 |
+
use_checkpoint: true
|
44 |
+
temporal_conv: true
|
45 |
+
temporal_attention: true
|
46 |
+
temporal_selfatt_only: true
|
47 |
+
use_relative_position: false
|
48 |
+
use_causal_attention: false
|
49 |
+
use_image_attention: true
|
50 |
+
temporal_length: 16
|
51 |
+
addition_attention: true
|
52 |
+
fps_cond: true
|
53 |
+
first_stage_config:
|
54 |
+
target: lvdm.models.autoencoder.AutoencoderKL
|
55 |
+
params:
|
56 |
+
embed_dim: 4
|
57 |
+
monitor: val/rec_loss
|
58 |
+
ddconfig:
|
59 |
+
double_z: true
|
60 |
+
z_channels: 4
|
61 |
+
resolution: 512
|
62 |
+
in_channels: 3
|
63 |
+
out_ch: 3
|
64 |
+
ch: 128
|
65 |
+
ch_mult:
|
66 |
+
- 1
|
67 |
+
- 2
|
68 |
+
- 4
|
69 |
+
- 4
|
70 |
+
num_res_blocks: 2
|
71 |
+
attn_resolutions: []
|
72 |
+
dropout: 0.0
|
73 |
+
lossconfig:
|
74 |
+
target: torch.nn.Identity
|
75 |
+
cond_stage_config:
|
76 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
77 |
+
params:
|
78 |
+
freeze: true
|
79 |
+
layer: penultimate
|
80 |
+
cond_img_config:
|
81 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
|
82 |
+
params:
|
83 |
+
freeze: true
|
VADER-VideoCrafter/configs/inference_t2v_1024_v1.0.yaml
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: lvdm.models.ddpm3d.LatentDiffusion
|
3 |
+
params:
|
4 |
+
linear_start: 0.00085
|
5 |
+
linear_end: 0.012
|
6 |
+
num_timesteps_cond: 1
|
7 |
+
timesteps: 1000
|
8 |
+
first_stage_key: video
|
9 |
+
cond_stage_key: caption
|
10 |
+
cond_stage_trainable: false
|
11 |
+
conditioning_key: crossattn
|
12 |
+
image_size:
|
13 |
+
- 72
|
14 |
+
- 128
|
15 |
+
channels: 4
|
16 |
+
scale_by_std: false
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: false
|
19 |
+
uncond_type: empty_seq
|
20 |
+
use_scale: true
|
21 |
+
fix_scale_bug: true
|
22 |
+
unet_config:
|
23 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
24 |
+
params:
|
25 |
+
in_channels: 4
|
26 |
+
out_channels: 4
|
27 |
+
model_channels: 320
|
28 |
+
attention_resolutions:
|
29 |
+
- 4
|
30 |
+
- 2
|
31 |
+
- 1
|
32 |
+
num_res_blocks: 2
|
33 |
+
channel_mult:
|
34 |
+
- 1
|
35 |
+
- 2
|
36 |
+
- 4
|
37 |
+
- 4
|
38 |
+
num_head_channels: 64
|
39 |
+
transformer_depth: 1
|
40 |
+
context_dim: 1024
|
41 |
+
use_linear: true
|
42 |
+
use_checkpoint: true
|
43 |
+
temporal_conv: false
|
44 |
+
temporal_attention: true
|
45 |
+
temporal_selfatt_only: true
|
46 |
+
use_relative_position: true
|
47 |
+
use_causal_attention: false
|
48 |
+
temporal_length: 16
|
49 |
+
addition_attention: true
|
50 |
+
fps_cond: true
|
51 |
+
first_stage_config:
|
52 |
+
target: lvdm.models.autoencoder.AutoencoderKL
|
53 |
+
params:
|
54 |
+
embed_dim: 4
|
55 |
+
monitor: val/rec_loss
|
56 |
+
ddconfig:
|
57 |
+
double_z: true
|
58 |
+
z_channels: 4
|
59 |
+
resolution: 512
|
60 |
+
in_channels: 3
|
61 |
+
out_ch: 3
|
62 |
+
ch: 128
|
63 |
+
ch_mult:
|
64 |
+
- 1
|
65 |
+
- 2
|
66 |
+
- 4
|
67 |
+
- 4
|
68 |
+
num_res_blocks: 2
|
69 |
+
attn_resolutions: []
|
70 |
+
dropout: 0.0
|
71 |
+
lossconfig:
|
72 |
+
target: torch.nn.Identity
|
73 |
+
cond_stage_config:
|
74 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
75 |
+
params:
|
76 |
+
freeze: true
|
77 |
+
layer: penultimate
|
VADER-VideoCrafter/configs/inference_t2v_512_v1.0.yaml
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: lvdm.models.ddpm3d.LatentDiffusion
|
3 |
+
params:
|
4 |
+
linear_start: 0.00085
|
5 |
+
linear_end: 0.012
|
6 |
+
num_timesteps_cond: 1
|
7 |
+
timesteps: 1000
|
8 |
+
first_stage_key: video
|
9 |
+
cond_stage_key: caption
|
10 |
+
cond_stage_trainable: false
|
11 |
+
conditioning_key: crossattn
|
12 |
+
image_size:
|
13 |
+
- 40
|
14 |
+
- 64
|
15 |
+
channels: 4
|
16 |
+
scale_by_std: false
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: false
|
19 |
+
uncond_type: empty_seq
|
20 |
+
unet_config:
|
21 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
22 |
+
params:
|
23 |
+
in_channels: 4
|
24 |
+
out_channels: 4
|
25 |
+
model_channels: 320
|
26 |
+
attention_resolutions:
|
27 |
+
- 4
|
28 |
+
- 2
|
29 |
+
- 1
|
30 |
+
num_res_blocks: 2
|
31 |
+
channel_mult:
|
32 |
+
- 1
|
33 |
+
- 2
|
34 |
+
- 4
|
35 |
+
- 4
|
36 |
+
num_head_channels: 64
|
37 |
+
transformer_depth: 1
|
38 |
+
context_dim: 1024
|
39 |
+
use_linear: true
|
40 |
+
use_checkpoint: true
|
41 |
+
temporal_conv: false
|
42 |
+
temporal_attention: true
|
43 |
+
temporal_selfatt_only: true
|
44 |
+
use_relative_position: true
|
45 |
+
use_causal_attention: false
|
46 |
+
temporal_length: 16
|
47 |
+
addition_attention: true
|
48 |
+
first_stage_config:
|
49 |
+
target: lvdm.models.autoencoder.AutoencoderKL
|
50 |
+
params:
|
51 |
+
embed_dim: 4
|
52 |
+
monitor: val/rec_loss
|
53 |
+
ddconfig:
|
54 |
+
double_z: true
|
55 |
+
z_channels: 4
|
56 |
+
resolution: 512
|
57 |
+
in_channels: 3
|
58 |
+
out_ch: 3
|
59 |
+
ch: 128
|
60 |
+
ch_mult:
|
61 |
+
- 1
|
62 |
+
- 2
|
63 |
+
- 4
|
64 |
+
- 4
|
65 |
+
num_res_blocks: 2
|
66 |
+
attn_resolutions: []
|
67 |
+
dropout: 0.0
|
68 |
+
lossconfig:
|
69 |
+
target: torch.nn.Identity
|
70 |
+
cond_stage_config:
|
71 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
72 |
+
params:
|
73 |
+
freeze: true
|
74 |
+
layer: penultimate
|
VADER-VideoCrafter/configs/inference_t2v_512_v2.0.yaml
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: lvdm.models.ddpm3d.LatentDiffusion
|
3 |
+
params:
|
4 |
+
linear_start: 0.00085
|
5 |
+
linear_end: 0.012
|
6 |
+
num_timesteps_cond: 1
|
7 |
+
timesteps: 1000
|
8 |
+
first_stage_key: video
|
9 |
+
cond_stage_key: caption
|
10 |
+
cond_stage_trainable: false
|
11 |
+
conditioning_key: crossattn
|
12 |
+
image_size:
|
13 |
+
- 40
|
14 |
+
- 64
|
15 |
+
channels: 4
|
16 |
+
scale_by_std: false
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: false
|
19 |
+
uncond_type: empty_seq
|
20 |
+
use_scale: true
|
21 |
+
scale_b: 0.7
|
22 |
+
unet_config:
|
23 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
24 |
+
params:
|
25 |
+
in_channels: 4
|
26 |
+
out_channels: 4
|
27 |
+
model_channels: 320
|
28 |
+
attention_resolutions:
|
29 |
+
- 4
|
30 |
+
- 2
|
31 |
+
- 1
|
32 |
+
num_res_blocks: 2
|
33 |
+
channel_mult:
|
34 |
+
- 1
|
35 |
+
- 2
|
36 |
+
- 4
|
37 |
+
- 4
|
38 |
+
num_head_channels: 64
|
39 |
+
transformer_depth: 1
|
40 |
+
context_dim: 1024
|
41 |
+
use_linear: true
|
42 |
+
use_checkpoint: true
|
43 |
+
temporal_conv: true
|
44 |
+
temporal_attention: true
|
45 |
+
temporal_selfatt_only: true
|
46 |
+
use_relative_position: false
|
47 |
+
use_causal_attention: false
|
48 |
+
temporal_length: 16
|
49 |
+
addition_attention: true
|
50 |
+
fps_cond: true
|
51 |
+
first_stage_config:
|
52 |
+
target: lvdm.models.autoencoder.AutoencoderKL
|
53 |
+
params:
|
54 |
+
embed_dim: 4
|
55 |
+
monitor: val/rec_loss
|
56 |
+
ddconfig:
|
57 |
+
double_z: true
|
58 |
+
z_channels: 4
|
59 |
+
resolution: 512
|
60 |
+
in_channels: 3
|
61 |
+
out_ch: 3
|
62 |
+
ch: 128
|
63 |
+
ch_mult:
|
64 |
+
- 1
|
65 |
+
- 2
|
66 |
+
- 4
|
67 |
+
- 4
|
68 |
+
num_res_blocks: 2
|
69 |
+
attn_resolutions: []
|
70 |
+
dropout: 0.0
|
71 |
+
lossconfig:
|
72 |
+
target: torch.nn.Identity
|
73 |
+
cond_stage_config:
|
74 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
75 |
+
params:
|
76 |
+
freeze: true
|
77 |
+
layer: penultimate
|
VADER-VideoCrafter/lvdm/basics.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# adopted from
|
2 |
+
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
3 |
+
# and
|
4 |
+
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
5 |
+
# and
|
6 |
+
# https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
|
7 |
+
#
|
8 |
+
# thanks!
|
9 |
+
|
10 |
+
import torch.nn as nn
|
11 |
+
from utils.utils import instantiate_from_config
|
12 |
+
|
13 |
+
|
14 |
+
def disabled_train(self, mode=True):
|
15 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
16 |
+
does not change anymore."""
|
17 |
+
return self
|
18 |
+
|
19 |
+
def zero_module(module):
|
20 |
+
"""
|
21 |
+
Zero out the parameters of a module and return it.
|
22 |
+
"""
|
23 |
+
for p in module.parameters():
|
24 |
+
p.detach().zero_()
|
25 |
+
return module
|
26 |
+
|
27 |
+
def scale_module(module, scale):
|
28 |
+
"""
|
29 |
+
Scale the parameters of a module and return it.
|
30 |
+
"""
|
31 |
+
for p in module.parameters():
|
32 |
+
p.detach().mul_(scale)
|
33 |
+
return module
|
34 |
+
|
35 |
+
|
36 |
+
def conv_nd(dims, *args, **kwargs):
|
37 |
+
"""
|
38 |
+
Create a 1D, 2D, or 3D convolution module.
|
39 |
+
"""
|
40 |
+
if dims == 1:
|
41 |
+
return nn.Conv1d(*args, **kwargs)
|
42 |
+
elif dims == 2:
|
43 |
+
return nn.Conv2d(*args, **kwargs)
|
44 |
+
elif dims == 3:
|
45 |
+
return nn.Conv3d(*args, **kwargs)
|
46 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
47 |
+
|
48 |
+
|
49 |
+
def linear(*args, **kwargs):
|
50 |
+
"""
|
51 |
+
Create a linear module.
|
52 |
+
"""
|
53 |
+
return nn.Linear(*args, **kwargs)
|
54 |
+
|
55 |
+
|
56 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
57 |
+
"""
|
58 |
+
Create a 1D, 2D, or 3D average pooling module.
|
59 |
+
"""
|
60 |
+
if dims == 1:
|
61 |
+
return nn.AvgPool1d(*args, **kwargs)
|
62 |
+
elif dims == 2:
|
63 |
+
return nn.AvgPool2d(*args, **kwargs)
|
64 |
+
elif dims == 3:
|
65 |
+
return nn.AvgPool3d(*args, **kwargs)
|
66 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
67 |
+
|
68 |
+
|
69 |
+
def nonlinearity(type='silu'):
|
70 |
+
if type == 'silu':
|
71 |
+
return nn.SiLU()
|
72 |
+
elif type == 'leaky_relu':
|
73 |
+
return nn.LeakyReLU()
|
74 |
+
|
75 |
+
|
76 |
+
class GroupNormSpecific(nn.GroupNorm):
|
77 |
+
def forward(self, x):
|
78 |
+
return super().forward(x.float()).type(x.dtype)
|
79 |
+
|
80 |
+
|
81 |
+
def normalization(channels, num_groups=32):
|
82 |
+
"""
|
83 |
+
Make a standard normalization layer.
|
84 |
+
:param channels: number of input channels.
|
85 |
+
:return: an nn.Module for normalization.
|
86 |
+
"""
|
87 |
+
return GroupNormSpecific(num_groups, channels)
|
88 |
+
|
89 |
+
|
90 |
+
class HybridConditioner(nn.Module):
|
91 |
+
|
92 |
+
def __init__(self, c_concat_config, c_crossattn_config):
|
93 |
+
super().__init__()
|
94 |
+
self.concat_conditioner = instantiate_from_config(c_concat_config)
|
95 |
+
self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
|
96 |
+
|
97 |
+
def forward(self, c_concat, c_crossattn):
|
98 |
+
c_concat = self.concat_conditioner(c_concat)
|
99 |
+
c_crossattn = self.crossattn_conditioner(c_crossattn)
|
100 |
+
return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
|
VADER-VideoCrafter/lvdm/common.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import math
|
3 |
+
from inspect import isfunction
|
4 |
+
import torch
|
5 |
+
from torch import nn
|
6 |
+
import torch.distributed as dist
|
7 |
+
|
8 |
+
|
9 |
+
def gather_data(data, return_np=True):
|
10 |
+
''' gather data from multiple processes to one list '''
|
11 |
+
data_list = [torch.zeros_like(data) for _ in range(dist.get_world_size())]
|
12 |
+
dist.all_gather(data_list, data) # gather not supported with NCCL
|
13 |
+
if return_np:
|
14 |
+
data_list = [data.cpu().numpy() for data in data_list]
|
15 |
+
return data_list
|
16 |
+
|
17 |
+
def autocast(f):
|
18 |
+
def do_autocast(*args, **kwargs):
|
19 |
+
with torch.cuda.amp.autocast(enabled=True,
|
20 |
+
dtype=torch.get_autocast_gpu_dtype(),
|
21 |
+
cache_enabled=torch.is_autocast_cache_enabled()):
|
22 |
+
return f(*args, **kwargs)
|
23 |
+
return do_autocast
|
24 |
+
|
25 |
+
|
26 |
+
def extract_into_tensor(a, t, x_shape):
|
27 |
+
b, *_ = t.shape
|
28 |
+
out = a.gather(-1, t)
|
29 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
30 |
+
|
31 |
+
|
32 |
+
def noise_like(shape, device, repeat=False):
|
33 |
+
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
34 |
+
noise = lambda: torch.randn(shape, device=device)
|
35 |
+
return repeat_noise() if repeat else noise()
|
36 |
+
|
37 |
+
|
38 |
+
def default(val, d):
|
39 |
+
if exists(val):
|
40 |
+
return val
|
41 |
+
return d() if isfunction(d) else d
|
42 |
+
|
43 |
+
def exists(val):
|
44 |
+
return val is not None
|
45 |
+
|
46 |
+
def identity(*args, **kwargs):
|
47 |
+
return nn.Identity()
|
48 |
+
|
49 |
+
def uniq(arr):
|
50 |
+
return{el: True for el in arr}.keys()
|
51 |
+
|
52 |
+
def mean_flat(tensor):
|
53 |
+
"""
|
54 |
+
Take the mean over all non-batch dimensions.
|
55 |
+
"""
|
56 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
57 |
+
|
58 |
+
def ismap(x):
|
59 |
+
if not isinstance(x, torch.Tensor):
|
60 |
+
return False
|
61 |
+
return (len(x.shape) == 4) and (x.shape[1] > 3)
|
62 |
+
|
63 |
+
def isimage(x):
|
64 |
+
if not isinstance(x,torch.Tensor):
|
65 |
+
return False
|
66 |
+
return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
|
67 |
+
|
68 |
+
def max_neg_value(t):
|
69 |
+
return -torch.finfo(t.dtype).max
|
70 |
+
|
71 |
+
def shape_to_str(x):
|
72 |
+
shape_str = "x".join([str(x) for x in x.shape])
|
73 |
+
return shape_str
|
74 |
+
|
75 |
+
def init_(tensor):
|
76 |
+
dim = tensor.shape[-1]
|
77 |
+
std = 1 / math.sqrt(dim)
|
78 |
+
tensor.uniform_(-std, std)
|
79 |
+
return tensor
|
80 |
+
|
81 |
+
ckpt = torch.utils.checkpoint.checkpoint
|
82 |
+
def checkpoint(func, inputs, params, flag):
|
83 |
+
"""
|
84 |
+
Evaluate a function without caching intermediate activations, allowing for
|
85 |
+
reduced memory at the expense of extra compute in the backward pass.
|
86 |
+
:param func: the function to evaluate.
|
87 |
+
:param inputs: the argument sequence to pass to `func`.
|
88 |
+
:param params: a sequence of parameters `func` depends on but does not
|
89 |
+
explicitly take as arguments.
|
90 |
+
:param flag: if False, disable gradient checkpointing.
|
91 |
+
"""
|
92 |
+
if flag:
|
93 |
+
return ckpt(func, *inputs, use_reentrant=False)
|
94 |
+
else:
|
95 |
+
return func(*inputs)
|
96 |
+
|
VADER-VideoCrafter/lvdm/distributions.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
|
6 |
+
class AbstractDistribution:
|
7 |
+
def sample(self):
|
8 |
+
raise NotImplementedError()
|
9 |
+
|
10 |
+
def mode(self):
|
11 |
+
raise NotImplementedError()
|
12 |
+
|
13 |
+
|
14 |
+
class DiracDistribution(AbstractDistribution):
|
15 |
+
def __init__(self, value):
|
16 |
+
self.value = value
|
17 |
+
|
18 |
+
def sample(self):
|
19 |
+
return self.value
|
20 |
+
|
21 |
+
def mode(self):
|
22 |
+
return self.value
|
23 |
+
|
24 |
+
|
25 |
+
class DiagonalGaussianDistribution(object):
|
26 |
+
def __init__(self, parameters, deterministic=False):
|
27 |
+
self.parameters = parameters
|
28 |
+
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
|
29 |
+
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
|
30 |
+
self.deterministic = deterministic
|
31 |
+
self.std = torch.exp(0.5 * self.logvar)
|
32 |
+
self.var = torch.exp(self.logvar)
|
33 |
+
if self.deterministic:
|
34 |
+
self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
|
35 |
+
|
36 |
+
def sample(self, noise=None):
|
37 |
+
if noise is None:
|
38 |
+
noise = torch.randn(self.mean.shape)
|
39 |
+
|
40 |
+
x = self.mean + self.std * noise.to(device=self.parameters.device)
|
41 |
+
return x
|
42 |
+
|
43 |
+
def kl(self, other=None):
|
44 |
+
if self.deterministic:
|
45 |
+
return torch.Tensor([0.])
|
46 |
+
else:
|
47 |
+
if other is None:
|
48 |
+
return 0.5 * torch.sum(torch.pow(self.mean, 2)
|
49 |
+
+ self.var - 1.0 - self.logvar,
|
50 |
+
dim=[1, 2, 3])
|
51 |
+
else:
|
52 |
+
return 0.5 * torch.sum(
|
53 |
+
torch.pow(self.mean - other.mean, 2) / other.var
|
54 |
+
+ self.var / other.var - 1.0 - self.logvar + other.logvar,
|
55 |
+
dim=[1, 2, 3])
|
56 |
+
|
57 |
+
def nll(self, sample, dims=[1,2,3]):
|
58 |
+
if self.deterministic:
|
59 |
+
return torch.Tensor([0.])
|
60 |
+
logtwopi = np.log(2.0 * np.pi)
|
61 |
+
return 0.5 * torch.sum(
|
62 |
+
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
|
63 |
+
dim=dims)
|
64 |
+
|
65 |
+
def mode(self):
|
66 |
+
return self.mean
|
67 |
+
|
68 |
+
|
69 |
+
def normal_kl(mean1, logvar1, mean2, logvar2):
|
70 |
+
"""
|
71 |
+
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
|
72 |
+
Compute the KL divergence between two gaussians.
|
73 |
+
Shapes are automatically broadcasted, so batches can be compared to
|
74 |
+
scalars, among other use cases.
|
75 |
+
"""
|
76 |
+
tensor = None
|
77 |
+
for obj in (mean1, logvar1, mean2, logvar2):
|
78 |
+
if isinstance(obj, torch.Tensor):
|
79 |
+
tensor = obj
|
80 |
+
break
|
81 |
+
assert tensor is not None, "at least one argument must be a Tensor"
|
82 |
+
|
83 |
+
# Force variances to be Tensors. Broadcasting helps convert scalars to
|
84 |
+
# Tensors, but it does not work for torch.exp().
|
85 |
+
logvar1, logvar2 = [
|
86 |
+
x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
|
87 |
+
for x in (logvar1, logvar2)
|
88 |
+
]
|
89 |
+
|
90 |
+
return 0.5 * (
|
91 |
+
-1.0
|
92 |
+
+ logvar2
|
93 |
+
- logvar1
|
94 |
+
+ torch.exp(logvar1 - logvar2)
|
95 |
+
+ ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
|
96 |
+
)
|
VADER-VideoCrafter/lvdm/ema.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
|
5 |
+
|
6 |
+
class LitEma(nn.Module):
|
7 |
+
def __init__(self, model, decay=0.9999, use_num_upates=True):
|
8 |
+
super().__init__()
|
9 |
+
if decay < 0.0 or decay > 1.0:
|
10 |
+
raise ValueError('Decay must be between 0 and 1')
|
11 |
+
|
12 |
+
self.m_name2s_name = {}
|
13 |
+
self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
|
14 |
+
self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates
|
15 |
+
else torch.tensor(-1,dtype=torch.int))
|
16 |
+
|
17 |
+
for name, p in model.named_parameters():
|
18 |
+
if p.requires_grad:
|
19 |
+
#remove as '.'-character is not allowed in buffers
|
20 |
+
s_name = name.replace('.','')
|
21 |
+
self.m_name2s_name.update({name:s_name})
|
22 |
+
self.register_buffer(s_name,p.clone().detach().data)
|
23 |
+
|
24 |
+
self.collected_params = []
|
25 |
+
|
26 |
+
def forward(self,model):
|
27 |
+
decay = self.decay
|
28 |
+
|
29 |
+
if self.num_updates >= 0:
|
30 |
+
self.num_updates += 1
|
31 |
+
decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))
|
32 |
+
|
33 |
+
one_minus_decay = 1.0 - decay
|
34 |
+
|
35 |
+
with torch.no_grad():
|
36 |
+
m_param = dict(model.named_parameters())
|
37 |
+
shadow_params = dict(self.named_buffers())
|
38 |
+
|
39 |
+
for key in m_param:
|
40 |
+
if m_param[key].requires_grad:
|
41 |
+
sname = self.m_name2s_name[key]
|
42 |
+
shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
|
43 |
+
shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
|
44 |
+
else:
|
45 |
+
assert not key in self.m_name2s_name
|
46 |
+
|
47 |
+
def copy_to(self, model):
|
48 |
+
m_param = dict(model.named_parameters())
|
49 |
+
shadow_params = dict(self.named_buffers())
|
50 |
+
for key in m_param:
|
51 |
+
if m_param[key].requires_grad:
|
52 |
+
m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
|
53 |
+
else:
|
54 |
+
assert not key in self.m_name2s_name
|
55 |
+
|
56 |
+
def store(self, parameters):
|
57 |
+
"""
|
58 |
+
Save the current parameters for restoring later.
|
59 |
+
Args:
|
60 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
61 |
+
temporarily stored.
|
62 |
+
"""
|
63 |
+
self.collected_params = [param.clone() for param in parameters]
|
64 |
+
|
65 |
+
def restore(self, parameters):
|
66 |
+
"""
|
67 |
+
Restore the parameters stored with the `store` method.
|
68 |
+
Useful to validate the model with EMA parameters without affecting the
|
69 |
+
original optimization process. Store the parameters before the
|
70 |
+
`copy_to` method. After validation (or model saving), use this to
|
71 |
+
restore the former parameters.
|
72 |
+
Args:
|
73 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
74 |
+
updated with the stored parameters.
|
75 |
+
"""
|
76 |
+
for c_param, param in zip(self.collected_params, parameters):
|
77 |
+
param.data.copy_(c_param.data)
|
VADER-VideoCrafter/lvdm/models/autoencoder.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import os
|
3 |
+
from contextlib import contextmanager
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
from einops import rearrange
|
7 |
+
import torch.nn.functional as F
|
8 |
+
import pytorch_lightning as pl
|
9 |
+
from lvdm.modules.networks.ae_modules import Encoder, Decoder
|
10 |
+
from lvdm.distributions import DiagonalGaussianDistribution
|
11 |
+
from utils.utils import instantiate_from_config
|
12 |
+
|
13 |
+
|
14 |
+
class AutoencoderKL(pl.LightningModule):
|
15 |
+
def __init__(self,
|
16 |
+
ddconfig,
|
17 |
+
lossconfig,
|
18 |
+
embed_dim,
|
19 |
+
ckpt_path=None,
|
20 |
+
ignore_keys=[],
|
21 |
+
image_key="image",
|
22 |
+
colorize_nlabels=None,
|
23 |
+
monitor=None,
|
24 |
+
test=False,
|
25 |
+
logdir=None,
|
26 |
+
input_dim=4,
|
27 |
+
test_args=None,
|
28 |
+
):
|
29 |
+
super().__init__()
|
30 |
+
self.image_key = image_key
|
31 |
+
self.encoder = Encoder(**ddconfig)
|
32 |
+
self.decoder = Decoder(**ddconfig)
|
33 |
+
self.loss = instantiate_from_config(lossconfig)
|
34 |
+
assert ddconfig["double_z"]
|
35 |
+
self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
|
36 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
37 |
+
self.embed_dim = embed_dim
|
38 |
+
self.input_dim = input_dim
|
39 |
+
self.test = test
|
40 |
+
self.test_args = test_args
|
41 |
+
self.logdir = logdir
|
42 |
+
if colorize_nlabels is not None:
|
43 |
+
assert type(colorize_nlabels)==int
|
44 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
45 |
+
if monitor is not None:
|
46 |
+
self.monitor = monitor
|
47 |
+
if ckpt_path is not None:
|
48 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
49 |
+
if self.test:
|
50 |
+
self.init_test()
|
51 |
+
|
52 |
+
def init_test(self,):
|
53 |
+
self.test = True
|
54 |
+
save_dir = os.path.join(self.logdir, "test")
|
55 |
+
if 'ckpt' in self.test_args:
|
56 |
+
ckpt_name = os.path.basename(self.test_args.ckpt).split('.ckpt')[0] + f'_epoch{self._cur_epoch}'
|
57 |
+
self.root = os.path.join(save_dir, ckpt_name)
|
58 |
+
else:
|
59 |
+
self.root = save_dir
|
60 |
+
if 'test_subdir' in self.test_args:
|
61 |
+
self.root = os.path.join(save_dir, self.test_args.test_subdir)
|
62 |
+
|
63 |
+
self.root_zs = os.path.join(self.root, "zs")
|
64 |
+
self.root_dec = os.path.join(self.root, "reconstructions")
|
65 |
+
self.root_inputs = os.path.join(self.root, "inputs")
|
66 |
+
os.makedirs(self.root, exist_ok=True)
|
67 |
+
|
68 |
+
if self.test_args.save_z:
|
69 |
+
os.makedirs(self.root_zs, exist_ok=True)
|
70 |
+
if self.test_args.save_reconstruction:
|
71 |
+
os.makedirs(self.root_dec, exist_ok=True)
|
72 |
+
if self.test_args.save_input:
|
73 |
+
os.makedirs(self.root_inputs, exist_ok=True)
|
74 |
+
assert(self.test_args is not None)
|
75 |
+
self.test_maximum = getattr(self.test_args, 'test_maximum', None)
|
76 |
+
self.count = 0
|
77 |
+
self.eval_metrics = {}
|
78 |
+
self.decodes = []
|
79 |
+
self.save_decode_samples = 2048
|
80 |
+
|
81 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
82 |
+
sd = torch.load(path, map_location="cpu")
|
83 |
+
try:
|
84 |
+
self._cur_epoch = sd['epoch']
|
85 |
+
sd = sd["state_dict"]
|
86 |
+
except:
|
87 |
+
self._cur_epoch = 'null'
|
88 |
+
keys = list(sd.keys())
|
89 |
+
for k in keys:
|
90 |
+
for ik in ignore_keys:
|
91 |
+
if k.startswith(ik):
|
92 |
+
print("Deleting key {} from state_dict.".format(k))
|
93 |
+
del sd[k]
|
94 |
+
self.load_state_dict(sd, strict=False)
|
95 |
+
# self.load_state_dict(sd, strict=True)
|
96 |
+
print(f"Restored from {path}")
|
97 |
+
|
98 |
+
def encode(self, x, **kwargs):
|
99 |
+
|
100 |
+
h = self.encoder(x)
|
101 |
+
moments = self.quant_conv(h)
|
102 |
+
posterior = DiagonalGaussianDistribution(moments)
|
103 |
+
return posterior
|
104 |
+
|
105 |
+
def decode(self, z, **kwargs):
|
106 |
+
z = self.post_quant_conv(z)
|
107 |
+
dec = self.decoder(z)
|
108 |
+
return dec
|
109 |
+
|
110 |
+
def forward(self, input, sample_posterior=True):
|
111 |
+
posterior = self.encode(input)
|
112 |
+
if sample_posterior:
|
113 |
+
z = posterior.sample()
|
114 |
+
else:
|
115 |
+
z = posterior.mode()
|
116 |
+
dec = self.decode(z)
|
117 |
+
return dec, posterior
|
118 |
+
|
119 |
+
def get_input(self, batch, k):
|
120 |
+
x = batch[k]
|
121 |
+
if x.dim() == 5 and self.input_dim == 4:
|
122 |
+
b,c,t,h,w = x.shape
|
123 |
+
self.b = b
|
124 |
+
self.t = t
|
125 |
+
x = rearrange(x, 'b c t h w -> (b t) c h w')
|
126 |
+
|
127 |
+
return x
|
128 |
+
|
129 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
130 |
+
inputs = self.get_input(batch, self.image_key)
|
131 |
+
reconstructions, posterior = self(inputs)
|
132 |
+
|
133 |
+
if optimizer_idx == 0:
|
134 |
+
# train encoder+decoder+logvar
|
135 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
136 |
+
last_layer=self.get_last_layer(), split="train")
|
137 |
+
self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
138 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
139 |
+
return aeloss
|
140 |
+
|
141 |
+
if optimizer_idx == 1:
|
142 |
+
# train the discriminator
|
143 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
144 |
+
last_layer=self.get_last_layer(), split="train")
|
145 |
+
|
146 |
+
self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
147 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
148 |
+
return discloss
|
149 |
+
|
150 |
+
def validation_step(self, batch, batch_idx):
|
151 |
+
inputs = self.get_input(batch, self.image_key)
|
152 |
+
reconstructions, posterior = self(inputs)
|
153 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
|
154 |
+
last_layer=self.get_last_layer(), split="val")
|
155 |
+
|
156 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
|
157 |
+
last_layer=self.get_last_layer(), split="val")
|
158 |
+
|
159 |
+
self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
|
160 |
+
self.log_dict(log_dict_ae)
|
161 |
+
self.log_dict(log_dict_disc)
|
162 |
+
return self.log_dict
|
163 |
+
|
164 |
+
def configure_optimizers(self):
|
165 |
+
lr = self.learning_rate
|
166 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
167 |
+
list(self.decoder.parameters())+
|
168 |
+
list(self.quant_conv.parameters())+
|
169 |
+
list(self.post_quant_conv.parameters()),
|
170 |
+
lr=lr, betas=(0.5, 0.9))
|
171 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
172 |
+
lr=lr, betas=(0.5, 0.9))
|
173 |
+
return [opt_ae, opt_disc], []
|
174 |
+
|
175 |
+
def get_last_layer(self):
|
176 |
+
return self.decoder.conv_out.weight
|
177 |
+
|
178 |
+
@torch.no_grad()
|
179 |
+
def log_images(self, batch, only_inputs=False, **kwargs):
|
180 |
+
log = dict()
|
181 |
+
x = self.get_input(batch, self.image_key)
|
182 |
+
x = x.to(self.device)
|
183 |
+
if not only_inputs:
|
184 |
+
xrec, posterior = self(x)
|
185 |
+
if x.shape[1] > 3:
|
186 |
+
# colorize with random projection
|
187 |
+
assert xrec.shape[1] > 3
|
188 |
+
x = self.to_rgb(x)
|
189 |
+
xrec = self.to_rgb(xrec)
|
190 |
+
log["samples"] = self.decode(torch.randn_like(posterior.sample()))
|
191 |
+
log["reconstructions"] = xrec
|
192 |
+
log["inputs"] = x
|
193 |
+
return log
|
194 |
+
|
195 |
+
def to_rgb(self, x):
|
196 |
+
assert self.image_key == "segmentation"
|
197 |
+
if not hasattr(self, "colorize"):
|
198 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
199 |
+
x = F.conv2d(x, weight=self.colorize)
|
200 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
201 |
+
return x
|
202 |
+
|
203 |
+
class IdentityFirstStage(torch.nn.Module):
|
204 |
+
def __init__(self, *args, vq_interface=False, **kwargs):
|
205 |
+
self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
|
206 |
+
super().__init__()
|
207 |
+
|
208 |
+
def encode(self, x, *args, **kwargs):
|
209 |
+
return x
|
210 |
+
|
211 |
+
def decode(self, x, *args, **kwargs):
|
212 |
+
return x
|
213 |
+
|
214 |
+
def quantize(self, x, *args, **kwargs):
|
215 |
+
if self.vq_interface:
|
216 |
+
return x, None, [None, None, None]
|
217 |
+
return x
|
218 |
+
|
219 |
+
def forward(self, x, *args, **kwargs):
|
220 |
+
return x
|
VADER-VideoCrafter/lvdm/models/ddpm3d.py
ADDED
@@ -0,0 +1,765 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
"""
|
3 |
+
wild mixture of
|
4 |
+
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
|
5 |
+
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
6 |
+
https://github.com/CompVis/taming-transformers
|
7 |
+
-- merci
|
8 |
+
"""
|
9 |
+
|
10 |
+
from functools import partial
|
11 |
+
from contextlib import contextmanager
|
12 |
+
import numpy as np
|
13 |
+
from tqdm import tqdm
|
14 |
+
from einops import rearrange, repeat
|
15 |
+
import logging
|
16 |
+
mainlogger = logging.getLogger('mainlogger')
|
17 |
+
import torch
|
18 |
+
import torch.nn as nn
|
19 |
+
from torchvision.utils import make_grid
|
20 |
+
import pytorch_lightning as pl
|
21 |
+
from utils.utils import instantiate_from_config
|
22 |
+
from lvdm.ema import LitEma
|
23 |
+
from lvdm.distributions import DiagonalGaussianDistribution
|
24 |
+
from lvdm.models.utils_diffusion import make_beta_schedule
|
25 |
+
from lvdm.modules.encoders.ip_resampler import ImageProjModel, Resampler
|
26 |
+
from lvdm.basics import disabled_train
|
27 |
+
from lvdm.common import (
|
28 |
+
extract_into_tensor,
|
29 |
+
noise_like,
|
30 |
+
exists,
|
31 |
+
default
|
32 |
+
)
|
33 |
+
# import ipdb
|
34 |
+
# st = ipdb.set_trace
|
35 |
+
|
36 |
+
__conditioning_keys__ = {'concat': 'c_concat',
|
37 |
+
'crossattn': 'c_crossattn',
|
38 |
+
'adm': 'y'}
|
39 |
+
|
40 |
+
class DDPM(pl.LightningModule):
|
41 |
+
# classic DDPM with Gaussian diffusion, in image space
|
42 |
+
def __init__(self,
|
43 |
+
unet_config,
|
44 |
+
timesteps=1000,
|
45 |
+
beta_schedule="linear",
|
46 |
+
loss_type="l2",
|
47 |
+
ckpt_path=None,
|
48 |
+
ignore_keys=[],
|
49 |
+
load_only_unet=False,
|
50 |
+
monitor=None,
|
51 |
+
use_ema=True,
|
52 |
+
first_stage_key="image",
|
53 |
+
image_size=256,
|
54 |
+
channels=3,
|
55 |
+
log_every_t=100,
|
56 |
+
clip_denoised=True,
|
57 |
+
linear_start=1e-4,
|
58 |
+
linear_end=2e-2,
|
59 |
+
cosine_s=8e-3,
|
60 |
+
given_betas=None,
|
61 |
+
original_elbo_weight=0.,
|
62 |
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
63 |
+
l_simple_weight=1.,
|
64 |
+
conditioning_key=None,
|
65 |
+
parameterization="eps", # all assuming fixed variance schedules
|
66 |
+
scheduler_config=None,
|
67 |
+
use_positional_encodings=False,
|
68 |
+
learn_logvar=False,
|
69 |
+
logvar_init=0.
|
70 |
+
):
|
71 |
+
super().__init__()
|
72 |
+
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
|
73 |
+
self.parameterization = parameterization
|
74 |
+
mainlogger.info(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
|
75 |
+
self.cond_stage_model = None
|
76 |
+
self.clip_denoised = clip_denoised
|
77 |
+
self.log_every_t = log_every_t
|
78 |
+
self.first_stage_key = first_stage_key
|
79 |
+
self.channels = channels
|
80 |
+
self.temporal_length = unet_config.params.temporal_length
|
81 |
+
self.image_size = image_size
|
82 |
+
if isinstance(self.image_size, int):
|
83 |
+
self.image_size = [self.image_size, self.image_size]
|
84 |
+
self.use_positional_encodings = use_positional_encodings
|
85 |
+
self.model = DiffusionWrapper(unet_config, conditioning_key)
|
86 |
+
self.use_ema = use_ema
|
87 |
+
if self.use_ema:
|
88 |
+
self.model_ema = LitEma(self.model)
|
89 |
+
mainlogger.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
90 |
+
|
91 |
+
self.use_scheduler = scheduler_config is not None
|
92 |
+
if self.use_scheduler:
|
93 |
+
self.scheduler_config = scheduler_config
|
94 |
+
|
95 |
+
self.v_posterior = v_posterior
|
96 |
+
self.original_elbo_weight = original_elbo_weight
|
97 |
+
self.l_simple_weight = l_simple_weight
|
98 |
+
|
99 |
+
if monitor is not None:
|
100 |
+
self.monitor = monitor
|
101 |
+
if ckpt_path is not None:
|
102 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
103 |
+
|
104 |
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
105 |
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
106 |
+
|
107 |
+
self.loss_type = loss_type
|
108 |
+
|
109 |
+
self.learn_logvar = learn_logvar
|
110 |
+
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
111 |
+
if self.learn_logvar:
|
112 |
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
113 |
+
|
114 |
+
|
115 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
116 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
117 |
+
if exists(given_betas):
|
118 |
+
betas = given_betas
|
119 |
+
else:
|
120 |
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
121 |
+
cosine_s=cosine_s)
|
122 |
+
alphas = 1. - betas
|
123 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
124 |
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
125 |
+
|
126 |
+
timesteps, = betas.shape
|
127 |
+
self.num_timesteps = int(timesteps)
|
128 |
+
self.linear_start = linear_start
|
129 |
+
self.linear_end = linear_end
|
130 |
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
131 |
+
|
132 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
133 |
+
|
134 |
+
self.register_buffer('betas', to_torch(betas))
|
135 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
136 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
137 |
+
|
138 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
139 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
140 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
141 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
142 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
143 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
144 |
+
|
145 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
146 |
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
147 |
+
1. - alphas_cumprod) + self.v_posterior * betas
|
148 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
149 |
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
150 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
151 |
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
152 |
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
153 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
154 |
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
155 |
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
156 |
+
|
157 |
+
if self.parameterization == "eps":
|
158 |
+
lvlb_weights = self.betas ** 2 / (
|
159 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
160 |
+
elif self.parameterization == "x0":
|
161 |
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
162 |
+
else:
|
163 |
+
raise NotImplementedError("mu not supported")
|
164 |
+
# TODO how to choose this term
|
165 |
+
lvlb_weights[0] = lvlb_weights[1]
|
166 |
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
167 |
+
assert not torch.isnan(self.lvlb_weights).all()
|
168 |
+
|
169 |
+
@contextmanager
|
170 |
+
def ema_scope(self, context=None):
|
171 |
+
if self.use_ema:
|
172 |
+
self.model_ema.store(self.model.parameters())
|
173 |
+
self.model_ema.copy_to(self.model)
|
174 |
+
if context is not None:
|
175 |
+
mainlogger.info(f"{context}: Switched to EMA weights")
|
176 |
+
try:
|
177 |
+
yield None
|
178 |
+
finally:
|
179 |
+
if self.use_ema:
|
180 |
+
self.model_ema.restore(self.model.parameters())
|
181 |
+
if context is not None:
|
182 |
+
mainlogger.info(f"{context}: Restored training weights")
|
183 |
+
|
184 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
185 |
+
sd = torch.load(path, map_location="cpu")
|
186 |
+
if "state_dict" in list(sd.keys()):
|
187 |
+
sd = sd["state_dict"]
|
188 |
+
keys = list(sd.keys())
|
189 |
+
for k in keys:
|
190 |
+
for ik in ignore_keys:
|
191 |
+
if k.startswith(ik):
|
192 |
+
mainlogger.info("Deleting key {} from state_dict.".format(k))
|
193 |
+
del sd[k]
|
194 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
195 |
+
sd, strict=False)
|
196 |
+
mainlogger.info(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
197 |
+
if len(missing) > 0:
|
198 |
+
mainlogger.info(f"Missing Keys: {missing}")
|
199 |
+
if len(unexpected) > 0:
|
200 |
+
mainlogger.info(f"Unexpected Keys: {unexpected}")
|
201 |
+
|
202 |
+
def q_mean_variance(self, x_start, t):
|
203 |
+
"""
|
204 |
+
Get the distribution q(x_t | x_0).
|
205 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
206 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
207 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
208 |
+
"""
|
209 |
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
210 |
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
211 |
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
212 |
+
return mean, variance, log_variance
|
213 |
+
|
214 |
+
def predict_start_from_noise(self, x_t, t, noise):
|
215 |
+
return (
|
216 |
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
217 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
218 |
+
)
|
219 |
+
|
220 |
+
def q_posterior(self, x_start, x_t, t):
|
221 |
+
posterior_mean = (
|
222 |
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
223 |
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
224 |
+
)
|
225 |
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
226 |
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
227 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
228 |
+
|
229 |
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
230 |
+
model_out = self.model(x, t)
|
231 |
+
if self.parameterization == "eps":
|
232 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
233 |
+
elif self.parameterization == "x0":
|
234 |
+
x_recon = model_out
|
235 |
+
if clip_denoised:
|
236 |
+
x_recon.clamp_(-1., 1.)
|
237 |
+
|
238 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
239 |
+
return model_mean, posterior_variance, posterior_log_variance
|
240 |
+
|
241 |
+
@torch.no_grad()
|
242 |
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
243 |
+
b, *_, device = *x.shape, x.device
|
244 |
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
245 |
+
noise = noise_like(x.shape, device, repeat_noise)
|
246 |
+
# no noise when t == 0
|
247 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
248 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
249 |
+
|
250 |
+
@torch.no_grad()
|
251 |
+
def p_sample_loop(self, shape, return_intermediates=False):
|
252 |
+
device = self.betas.device
|
253 |
+
b = shape[0]
|
254 |
+
img = torch.randn(shape, device=device)
|
255 |
+
intermediates = [img]
|
256 |
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
257 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
258 |
+
clip_denoised=self.clip_denoised)
|
259 |
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
260 |
+
intermediates.append(img)
|
261 |
+
if return_intermediates:
|
262 |
+
return img, intermediates
|
263 |
+
return img
|
264 |
+
|
265 |
+
@torch.no_grad()
|
266 |
+
def sample(self, batch_size=16, return_intermediates=False):
|
267 |
+
image_size = self.image_size
|
268 |
+
channels = self.channels
|
269 |
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
270 |
+
return_intermediates=return_intermediates)
|
271 |
+
|
272 |
+
def q_sample(self, x_start, t, noise=None):
|
273 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
274 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start *
|
275 |
+
extract_into_tensor(self.scale_arr, t, x_start.shape) +
|
276 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
277 |
+
|
278 |
+
def get_input(self, batch, k):
|
279 |
+
x = batch[k]
|
280 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
281 |
+
return x
|
282 |
+
|
283 |
+
def _get_rows_from_list(self, samples):
|
284 |
+
n_imgs_per_row = len(samples)
|
285 |
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
286 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
287 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
288 |
+
return denoise_grid
|
289 |
+
|
290 |
+
@torch.no_grad()
|
291 |
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
292 |
+
log = dict()
|
293 |
+
x = self.get_input(batch, self.first_stage_key)
|
294 |
+
N = min(x.shape[0], N)
|
295 |
+
n_row = min(x.shape[0], n_row)
|
296 |
+
x = x.to(self.device)[:N]
|
297 |
+
log["inputs"] = x
|
298 |
+
|
299 |
+
# get diffusion row
|
300 |
+
diffusion_row = list()
|
301 |
+
x_start = x[:n_row]
|
302 |
+
|
303 |
+
for t in range(self.num_timesteps):
|
304 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
305 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
306 |
+
t = t.to(self.device).long()
|
307 |
+
noise = torch.randn_like(x_start)
|
308 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
309 |
+
diffusion_row.append(x_noisy)
|
310 |
+
|
311 |
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
312 |
+
|
313 |
+
if sample:
|
314 |
+
# get denoise row
|
315 |
+
with self.ema_scope("Plotting"):
|
316 |
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
317 |
+
|
318 |
+
log["samples"] = samples
|
319 |
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
320 |
+
|
321 |
+
if return_keys:
|
322 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
323 |
+
return log
|
324 |
+
else:
|
325 |
+
return {key: log[key] for key in return_keys}
|
326 |
+
return log
|
327 |
+
|
328 |
+
|
329 |
+
class LatentDiffusion(DDPM):
|
330 |
+
"""main class"""
|
331 |
+
def __init__(self,
|
332 |
+
first_stage_config,
|
333 |
+
cond_stage_config,
|
334 |
+
num_timesteps_cond=None,
|
335 |
+
cond_stage_key="caption",
|
336 |
+
cond_stage_trainable=False,
|
337 |
+
cond_stage_forward=None,
|
338 |
+
conditioning_key=None,
|
339 |
+
uncond_prob=0.2,
|
340 |
+
uncond_type="empty_seq",
|
341 |
+
scale_factor=1.0,
|
342 |
+
scale_by_std=False,
|
343 |
+
encoder_type="2d",
|
344 |
+
only_model=False,
|
345 |
+
use_scale=False,
|
346 |
+
scale_a=1,
|
347 |
+
scale_b=0.3,
|
348 |
+
mid_step=400,
|
349 |
+
fix_scale_bug=False,
|
350 |
+
*args, **kwargs):
|
351 |
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
352 |
+
self.scale_by_std = scale_by_std
|
353 |
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
354 |
+
# for backwards compatibility after implementation of DiffusionWrapper
|
355 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
356 |
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
357 |
+
conditioning_key = default(conditioning_key, 'crossattn')
|
358 |
+
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
359 |
+
|
360 |
+
self.cond_stage_trainable = cond_stage_trainable
|
361 |
+
self.cond_stage_key = cond_stage_key
|
362 |
+
|
363 |
+
# scale factor
|
364 |
+
self.use_scale=use_scale
|
365 |
+
if self.use_scale:
|
366 |
+
self.scale_a=scale_a
|
367 |
+
self.scale_b=scale_b
|
368 |
+
if fix_scale_bug:
|
369 |
+
scale_step=self.num_timesteps-mid_step
|
370 |
+
else: #bug
|
371 |
+
scale_step = self.num_timesteps
|
372 |
+
|
373 |
+
scale_arr1 = np.linspace(scale_a, scale_b, mid_step)
|
374 |
+
scale_arr2 = np.full(scale_step, scale_b)
|
375 |
+
scale_arr = np.concatenate((scale_arr1, scale_arr2))
|
376 |
+
scale_arr_prev = np.append(scale_a, scale_arr[:-1])
|
377 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
378 |
+
self.register_buffer('scale_arr', to_torch(scale_arr))
|
379 |
+
|
380 |
+
try:
|
381 |
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
382 |
+
except:
|
383 |
+
self.num_downs = 0
|
384 |
+
if not scale_by_std:
|
385 |
+
self.scale_factor = scale_factor
|
386 |
+
else:
|
387 |
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
388 |
+
self.instantiate_first_stage(first_stage_config)
|
389 |
+
self.instantiate_cond_stage(cond_stage_config)
|
390 |
+
self.first_stage_config = first_stage_config
|
391 |
+
self.cond_stage_config = cond_stage_config
|
392 |
+
self.clip_denoised = False
|
393 |
+
|
394 |
+
self.cond_stage_forward = cond_stage_forward
|
395 |
+
self.encoder_type = encoder_type
|
396 |
+
assert(encoder_type in ["2d", "3d"])
|
397 |
+
self.uncond_prob = uncond_prob
|
398 |
+
self.classifier_free_guidance = True if uncond_prob > 0 else False
|
399 |
+
assert(uncond_type in ["zero_embed", "empty_seq"])
|
400 |
+
self.uncond_type = uncond_type
|
401 |
+
|
402 |
+
|
403 |
+
self.restarted_from_ckpt = False
|
404 |
+
if ckpt_path is not None:
|
405 |
+
self.init_from_ckpt(ckpt_path, ignore_keys, only_model=only_model)
|
406 |
+
self.restarted_from_ckpt = True
|
407 |
+
|
408 |
+
|
409 |
+
def make_cond_schedule(self, ):
|
410 |
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
411 |
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
412 |
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
413 |
+
|
414 |
+
def q_sample(self, x_start, t, noise=None):
|
415 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
416 |
+
if self.use_scale:
|
417 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start *
|
418 |
+
extract_into_tensor(self.scale_arr, t, x_start.shape) +
|
419 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
420 |
+
else:
|
421 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
422 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
423 |
+
|
424 |
+
|
425 |
+
def _freeze_model(self):
|
426 |
+
for name, para in self.model.diffusion_model.named_parameters():
|
427 |
+
para.requires_grad = False
|
428 |
+
|
429 |
+
def instantiate_first_stage(self, config):
|
430 |
+
model = instantiate_from_config(config)
|
431 |
+
self.first_stage_model = model.eval()
|
432 |
+
self.first_stage_model.train = disabled_train
|
433 |
+
for param in self.first_stage_model.parameters():
|
434 |
+
param.requires_grad = False
|
435 |
+
|
436 |
+
def instantiate_cond_stage(self, config):
|
437 |
+
if not self.cond_stage_trainable:
|
438 |
+
model = instantiate_from_config(config)
|
439 |
+
self.cond_stage_model = model.eval()
|
440 |
+
self.cond_stage_model.train = disabled_train
|
441 |
+
for param in self.cond_stage_model.parameters():
|
442 |
+
param.requires_grad = False
|
443 |
+
else:
|
444 |
+
model = instantiate_from_config(config)
|
445 |
+
self.cond_stage_model = model
|
446 |
+
|
447 |
+
def get_learned_conditioning(self, c):
|
448 |
+
if self.cond_stage_forward is None:
|
449 |
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
450 |
+
c = self.cond_stage_model.encode(c)
|
451 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
452 |
+
c = c.mode()
|
453 |
+
else:
|
454 |
+
c = self.cond_stage_model(c)
|
455 |
+
else:
|
456 |
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
457 |
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
458 |
+
return c
|
459 |
+
|
460 |
+
def get_first_stage_encoding(self, encoder_posterior, noise=None):
|
461 |
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
462 |
+
z = encoder_posterior.sample(noise=noise)
|
463 |
+
elif isinstance(encoder_posterior, torch.Tensor):
|
464 |
+
z = encoder_posterior
|
465 |
+
else:
|
466 |
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
467 |
+
return self.scale_factor * z
|
468 |
+
|
469 |
+
@torch.no_grad()
|
470 |
+
def encode_first_stage(self, x):
|
471 |
+
if self.encoder_type == "2d" and x.dim() == 5:
|
472 |
+
b, _, t, _, _ = x.shape
|
473 |
+
x = rearrange(x, 'b c t h w -> (b t) c h w')
|
474 |
+
reshape_back = True
|
475 |
+
else:
|
476 |
+
reshape_back = False
|
477 |
+
|
478 |
+
encoder_posterior = self.first_stage_model.encode(x)
|
479 |
+
results = self.get_first_stage_encoding(encoder_posterior).detach()
|
480 |
+
|
481 |
+
if reshape_back:
|
482 |
+
results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
|
483 |
+
|
484 |
+
return results
|
485 |
+
|
486 |
+
@torch.no_grad()
|
487 |
+
def encode_first_stage_2DAE(self, x):
|
488 |
+
|
489 |
+
b, _, t, _, _ = x.shape
|
490 |
+
results = torch.cat([self.get_first_stage_encoding(self.first_stage_model.encode(x[:,:,i])).detach().unsqueeze(2) for i in range(t)], dim=2)
|
491 |
+
|
492 |
+
return results
|
493 |
+
|
494 |
+
def decode_core(self, z, **kwargs):
|
495 |
+
if self.encoder_type == "2d" and z.dim() == 5:
|
496 |
+
b, _, t, _, _ = z.shape
|
497 |
+
z = rearrange(z, 'b c t h w -> (b t) c h w')
|
498 |
+
reshape_back = True
|
499 |
+
else:
|
500 |
+
reshape_back = False
|
501 |
+
|
502 |
+
z = 1. / self.scale_factor * z
|
503 |
+
|
504 |
+
results = self.first_stage_model.decode(z, **kwargs)
|
505 |
+
|
506 |
+
if reshape_back:
|
507 |
+
results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
|
508 |
+
return results
|
509 |
+
|
510 |
+
@torch.no_grad()
|
511 |
+
def decode_first_stage(self, z, **kwargs):
|
512 |
+
return self.decode_core(z, **kwargs)
|
513 |
+
|
514 |
+
def apply_model(self, x_noisy, t, cond, **kwargs):
|
515 |
+
if isinstance(cond, dict):
|
516 |
+
# hybrid case, cond is exptected to be a dict
|
517 |
+
pass
|
518 |
+
else:
|
519 |
+
if not isinstance(cond, list):
|
520 |
+
cond = [cond]
|
521 |
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
522 |
+
cond = {key: cond}
|
523 |
+
|
524 |
+
x_recon = self.model(x_noisy, t, **cond, **kwargs)
|
525 |
+
|
526 |
+
if isinstance(x_recon, tuple):
|
527 |
+
return x_recon[0]
|
528 |
+
else:
|
529 |
+
return x_recon
|
530 |
+
|
531 |
+
def _get_denoise_row_from_list(self, samples, desc=''):
|
532 |
+
denoise_row = []
|
533 |
+
for zd in tqdm(samples, desc=desc):
|
534 |
+
denoise_row.append(self.decode_first_stage(zd.to(self.device)))
|
535 |
+
n_log_timesteps = len(denoise_row)
|
536 |
+
|
537 |
+
denoise_row = torch.stack(denoise_row) # n_log_timesteps, b, C, H, W
|
538 |
+
|
539 |
+
if denoise_row.dim() == 5:
|
540 |
+
# img, num_imgs= n_log_timesteps * bs, grid_size=[bs,n_log_timesteps]
|
541 |
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
542 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
543 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_log_timesteps)
|
544 |
+
elif denoise_row.dim() == 6:
|
545 |
+
# video, grid_size=[n_log_timesteps*bs, t]
|
546 |
+
video_length = denoise_row.shape[3]
|
547 |
+
denoise_grid = rearrange(denoise_row, 'n b c t h w -> b n c t h w')
|
548 |
+
denoise_grid = rearrange(denoise_grid, 'b n c t h w -> (b n) c t h w')
|
549 |
+
denoise_grid = rearrange(denoise_grid, 'n c t h w -> (n t) c h w')
|
550 |
+
denoise_grid = make_grid(denoise_grid, nrow=video_length)
|
551 |
+
else:
|
552 |
+
raise ValueError
|
553 |
+
|
554 |
+
return denoise_grid
|
555 |
+
|
556 |
+
|
557 |
+
# @torch.no_grad()
|
558 |
+
def decode_first_stage_2DAE(self, z, **kwargs):
|
559 |
+
|
560 |
+
b, _, t, _, _ = z.shape
|
561 |
+
z = 1. / self.scale_factor * z
|
562 |
+
results = torch.cat([self.first_stage_model.decode(z[:,:,i], **kwargs).unsqueeze(2) for i in range(t)], dim=2)
|
563 |
+
|
564 |
+
return results
|
565 |
+
|
566 |
+
|
567 |
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_x0=False, score_corrector=None, corrector_kwargs=None, **kwargs):
|
568 |
+
t_in = t
|
569 |
+
model_out = self.apply_model(x, t_in, c, **kwargs)
|
570 |
+
|
571 |
+
if score_corrector is not None:
|
572 |
+
assert self.parameterization == "eps"
|
573 |
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
574 |
+
|
575 |
+
if self.parameterization == "eps":
|
576 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
577 |
+
elif self.parameterization == "x0":
|
578 |
+
x_recon = model_out
|
579 |
+
else:
|
580 |
+
raise NotImplementedError()
|
581 |
+
|
582 |
+
if clip_denoised:
|
583 |
+
x_recon.clamp_(-1., 1.)
|
584 |
+
|
585 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
586 |
+
|
587 |
+
if return_x0:
|
588 |
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
589 |
+
else:
|
590 |
+
return model_mean, posterior_variance, posterior_log_variance
|
591 |
+
|
592 |
+
@torch.no_grad()
|
593 |
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_x0=False, \
|
594 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, **kwargs):
|
595 |
+
b, *_, device = *x.shape, x.device
|
596 |
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_x0=return_x0, \
|
597 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, **kwargs)
|
598 |
+
if return_x0:
|
599 |
+
model_mean, _, model_log_variance, x0 = outputs
|
600 |
+
else:
|
601 |
+
model_mean, _, model_log_variance = outputs
|
602 |
+
|
603 |
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
604 |
+
if noise_dropout > 0.:
|
605 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
606 |
+
# no noise when t == 0
|
607 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
608 |
+
|
609 |
+
if return_x0:
|
610 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
611 |
+
else:
|
612 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
613 |
+
|
614 |
+
@torch.no_grad()
|
615 |
+
def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, \
|
616 |
+
timesteps=None, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None, **kwargs):
|
617 |
+
|
618 |
+
if not log_every_t:
|
619 |
+
log_every_t = self.log_every_t
|
620 |
+
device = self.betas.device
|
621 |
+
b = shape[0]
|
622 |
+
# sample an initial noise
|
623 |
+
if x_T is None:
|
624 |
+
img = torch.randn(shape, device=device)
|
625 |
+
else:
|
626 |
+
img = x_T
|
627 |
+
|
628 |
+
intermediates = [img]
|
629 |
+
if timesteps is None:
|
630 |
+
timesteps = self.num_timesteps
|
631 |
+
if start_T is not None:
|
632 |
+
timesteps = min(timesteps, start_T)
|
633 |
+
|
634 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(range(0, timesteps))
|
635 |
+
|
636 |
+
if mask is not None:
|
637 |
+
assert x0 is not None
|
638 |
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
639 |
+
|
640 |
+
for i in iterator:
|
641 |
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
642 |
+
if self.shorten_cond_schedule:
|
643 |
+
assert self.model.conditioning_key != 'hybrid'
|
644 |
+
tc = self.cond_ids[ts].to(cond.device)
|
645 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
646 |
+
|
647 |
+
img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, **kwargs)
|
648 |
+
if mask is not None:
|
649 |
+
img_orig = self.q_sample(x0, ts)
|
650 |
+
img = img_orig * mask + (1. - mask) * img
|
651 |
+
|
652 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
653 |
+
intermediates.append(img)
|
654 |
+
if callback: callback(i)
|
655 |
+
if img_callback: img_callback(img, i)
|
656 |
+
|
657 |
+
if return_intermediates:
|
658 |
+
return img, intermediates
|
659 |
+
return img
|
660 |
+
|
661 |
+
|
662 |
+
class LatentVisualDiffusion(LatentDiffusion):
|
663 |
+
def __init__(self, cond_img_config, finegrained=False, random_cond=False, *args, **kwargs):
|
664 |
+
super().__init__(*args, **kwargs)
|
665 |
+
self.random_cond = random_cond
|
666 |
+
self.instantiate_img_embedder(cond_img_config, freeze=True)
|
667 |
+
num_tokens = 16 if finegrained else 4
|
668 |
+
self.image_proj_model = self.init_projector(use_finegrained=finegrained, num_tokens=num_tokens, input_dim=1024,\
|
669 |
+
cross_attention_dim=1024, dim=1280)
|
670 |
+
|
671 |
+
def instantiate_img_embedder(self, config, freeze=True):
|
672 |
+
embedder = instantiate_from_config(config)
|
673 |
+
if freeze:
|
674 |
+
self.embedder = embedder.eval()
|
675 |
+
self.embedder.train = disabled_train
|
676 |
+
for param in self.embedder.parameters():
|
677 |
+
param.requires_grad = False
|
678 |
+
|
679 |
+
def init_projector(self, use_finegrained, num_tokens, input_dim, cross_attention_dim, dim):
|
680 |
+
if not use_finegrained:
|
681 |
+
image_proj_model = ImageProjModel(clip_extra_context_tokens=num_tokens, cross_attention_dim=cross_attention_dim,
|
682 |
+
clip_embeddings_dim=input_dim
|
683 |
+
)
|
684 |
+
else:
|
685 |
+
image_proj_model = Resampler(dim=input_dim, depth=4, dim_head=64, heads=12, num_queries=num_tokens,
|
686 |
+
embedding_dim=dim, output_dim=cross_attention_dim, ff_mult=4
|
687 |
+
)
|
688 |
+
return image_proj_model
|
689 |
+
|
690 |
+
## Never delete this func: it is used in log_images() and inference stage
|
691 |
+
def get_image_embeds(self, batch_imgs):
|
692 |
+
## img: b c h w
|
693 |
+
img_token = self.embedder(batch_imgs)
|
694 |
+
img_emb = self.image_proj_model(img_token)
|
695 |
+
return img_emb
|
696 |
+
|
697 |
+
|
698 |
+
class DiffusionWrapper(pl.LightningModule):
|
699 |
+
def __init__(self, diff_model_config, conditioning_key):
|
700 |
+
super().__init__()
|
701 |
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
702 |
+
self.conditioning_key = conditioning_key
|
703 |
+
|
704 |
+
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None,
|
705 |
+
c_adm=None, s=None, mask=None, **kwargs):
|
706 |
+
# temporal_context = fps is foNone
|
707 |
+
if self.conditioning_key is None:
|
708 |
+
out = self.diffusion_model(x, t)
|
709 |
+
elif self.conditioning_key == 'concat':
|
710 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
711 |
+
out = self.diffusion_model(xc, t, **kwargs)
|
712 |
+
elif self.conditioning_key == 'crossattn':
|
713 |
+
cc = torch.cat(c_crossattn, 1)
|
714 |
+
out = self.diffusion_model(x, t, context=cc, **kwargs)
|
715 |
+
elif self.conditioning_key == 'hybrid':
|
716 |
+
## it is just right [b,c,t,h,w]: concatenate in channel dim
|
717 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
718 |
+
cc = torch.cat(c_crossattn, 1)
|
719 |
+
out = self.diffusion_model(xc, t, context=cc)
|
720 |
+
elif self.conditioning_key == 'resblockcond':
|
721 |
+
cc = c_crossattn[0]
|
722 |
+
out = self.diffusion_model(x, t, context=cc)
|
723 |
+
elif self.conditioning_key == 'adm':
|
724 |
+
cc = c_crossattn[0]
|
725 |
+
out = self.diffusion_model(x, t, y=cc)
|
726 |
+
elif self.conditioning_key == 'hybrid-adm':
|
727 |
+
assert c_adm is not None
|
728 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
729 |
+
cc = torch.cat(c_crossattn, 1)
|
730 |
+
out = self.diffusion_model(xc, t, context=cc, y=c_adm)
|
731 |
+
elif self.conditioning_key == 'hybrid-time':
|
732 |
+
assert s is not None
|
733 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
734 |
+
cc = torch.cat(c_crossattn, 1)
|
735 |
+
out = self.diffusion_model(xc, t, context=cc, s=s)
|
736 |
+
elif self.conditioning_key == 'concat-time-mask':
|
737 |
+
# assert s is not None
|
738 |
+
# mainlogger.info('x & mask:',x.shape,c_concat[0].shape)
|
739 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
740 |
+
out = self.diffusion_model(xc, t, context=None, s=s, mask=mask)
|
741 |
+
elif self.conditioning_key == 'concat-adm-mask':
|
742 |
+
# assert s is not None
|
743 |
+
# mainlogger.info('x & mask:',x.shape,c_concat[0].shape)
|
744 |
+
if c_concat is not None:
|
745 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
746 |
+
else:
|
747 |
+
xc = x
|
748 |
+
out = self.diffusion_model(xc, t, context=None, y=s, mask=mask)
|
749 |
+
elif self.conditioning_key == 'hybrid-adm-mask':
|
750 |
+
cc = torch.cat(c_crossattn, 1)
|
751 |
+
if c_concat is not None:
|
752 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
753 |
+
else:
|
754 |
+
xc = x
|
755 |
+
out = self.diffusion_model(xc, t, context=cc, y=s, mask=mask)
|
756 |
+
elif self.conditioning_key == 'hybrid-time-adm': # adm means y, e.g., class index
|
757 |
+
# assert s is not None
|
758 |
+
assert c_adm is not None
|
759 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
760 |
+
cc = torch.cat(c_crossattn, 1)
|
761 |
+
out = self.diffusion_model(xc, t, context=cc, s=s, y=c_adm)
|
762 |
+
else:
|
763 |
+
raise NotImplementedError()
|
764 |
+
|
765 |
+
return out
|
VADER-VideoCrafter/lvdm/models/samplers/ddim.py
ADDED
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import numpy as np
|
3 |
+
from tqdm import tqdm
|
4 |
+
import torch
|
5 |
+
from lvdm.models.utils_diffusion import make_ddim_sampling_parameters, make_ddim_timesteps
|
6 |
+
from lvdm.common import noise_like
|
7 |
+
import random
|
8 |
+
# import ipdb
|
9 |
+
# st = ipdb.set_trace
|
10 |
+
|
11 |
+
|
12 |
+
class DDIMSampler(object):
|
13 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
14 |
+
super().__init__()
|
15 |
+
self.model = model
|
16 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
17 |
+
self.schedule = schedule
|
18 |
+
self.counter = 0
|
19 |
+
self.backprop_mode = 'last' # default
|
20 |
+
self.training_mode = False # default
|
21 |
+
|
22 |
+
def register_buffer(self, name, attr):
|
23 |
+
if type(attr) == torch.Tensor:
|
24 |
+
if attr.device != torch.device("cuda"):
|
25 |
+
attr = attr.to(torch.device("cuda"))
|
26 |
+
setattr(self, name, attr)
|
27 |
+
|
28 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
29 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
30 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
31 |
+
alphas_cumprod = self.model.alphas_cumprod
|
32 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
33 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
34 |
+
|
35 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
36 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
37 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
38 |
+
self.use_scale = self.model.use_scale
|
39 |
+
# print('DDIM scale', self.use_scale)
|
40 |
+
|
41 |
+
if self.use_scale:
|
42 |
+
self.register_buffer('scale_arr', to_torch(self.model.scale_arr))
|
43 |
+
ddim_scale_arr = self.scale_arr.cpu()[self.ddim_timesteps]
|
44 |
+
self.register_buffer('ddim_scale_arr', ddim_scale_arr)
|
45 |
+
ddim_scale_arr = np.asarray([self.scale_arr.cpu()[0]] + self.scale_arr.cpu()[self.ddim_timesteps[:-1]].tolist())
|
46 |
+
self.register_buffer('ddim_scale_arr_prev', ddim_scale_arr)
|
47 |
+
|
48 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
49 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
50 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
51 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
52 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
53 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
54 |
+
|
55 |
+
# ddim sampling parameters
|
56 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
57 |
+
ddim_timesteps=self.ddim_timesteps,
|
58 |
+
eta=ddim_eta,verbose=verbose)
|
59 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
60 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
61 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
62 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
63 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
64 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
65 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
66 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
67 |
+
|
68 |
+
# @torch.no_grad()
|
69 |
+
def sample(self,
|
70 |
+
S,
|
71 |
+
batch_size,
|
72 |
+
shape,
|
73 |
+
conditioning=None,
|
74 |
+
callback=None,
|
75 |
+
normals_sequence=None,
|
76 |
+
img_callback=None,
|
77 |
+
quantize_x0=False,
|
78 |
+
eta=0.,
|
79 |
+
mask=None,
|
80 |
+
x0=None,
|
81 |
+
temperature=1.,
|
82 |
+
noise_dropout=0.,
|
83 |
+
score_corrector=None,
|
84 |
+
corrector_kwargs=None,
|
85 |
+
verbose=True,
|
86 |
+
schedule_verbose=False,
|
87 |
+
x_T=None,
|
88 |
+
log_every_t=100,
|
89 |
+
unconditional_guidance_scale=1.,
|
90 |
+
unconditional_conditioning=None,
|
91 |
+
# this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
92 |
+
**kwargs
|
93 |
+
):
|
94 |
+
|
95 |
+
# check condition bs
|
96 |
+
if conditioning is not None:
|
97 |
+
if isinstance(conditioning, dict):
|
98 |
+
try:
|
99 |
+
cbs = conditioning[list(conditioning.keys())[0]].shape[0]
|
100 |
+
except:
|
101 |
+
cbs = conditioning[list(conditioning.keys())[0]][0].shape[0]
|
102 |
+
|
103 |
+
if cbs != batch_size:
|
104 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
105 |
+
else:
|
106 |
+
if conditioning.shape[0] != batch_size:
|
107 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
108 |
+
|
109 |
+
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=schedule_verbose)
|
110 |
+
self.ddim_num_steps = S # for ddim_sampling
|
111 |
+
|
112 |
+
# make shape
|
113 |
+
if len(shape) == 3:
|
114 |
+
C, H, W = shape
|
115 |
+
size = (batch_size, C, H, W)
|
116 |
+
elif len(shape) == 4:
|
117 |
+
C, T, H, W = shape
|
118 |
+
size = (batch_size, C, T, H, W)
|
119 |
+
# print(f'Data shape for DDIM sampling is {size}, eta {eta}')
|
120 |
+
|
121 |
+
samples, intermediates = self.ddim_sampling(conditioning, size, # samples: batch, c, t, h, w
|
122 |
+
callback=callback,
|
123 |
+
img_callback=img_callback,
|
124 |
+
quantize_denoised=quantize_x0,
|
125 |
+
mask=mask, x0=x0,
|
126 |
+
ddim_use_original_steps=False,
|
127 |
+
noise_dropout=noise_dropout,
|
128 |
+
temperature=temperature,
|
129 |
+
score_corrector=score_corrector,
|
130 |
+
corrector_kwargs=corrector_kwargs,
|
131 |
+
x_T=x_T,
|
132 |
+
log_every_t=log_every_t,
|
133 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
134 |
+
unconditional_conditioning=unconditional_conditioning,
|
135 |
+
verbose=verbose,
|
136 |
+
**kwargs)
|
137 |
+
return samples, intermediates
|
138 |
+
|
139 |
+
# @torch.no_grad()
|
140 |
+
def ddim_sampling(self, cond, shape,
|
141 |
+
x_T=None, ddim_use_original_steps=False,
|
142 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
143 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
144 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
145 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, verbose=True,
|
146 |
+
cond_tau=1., target_size=None, start_timesteps=None,
|
147 |
+
**kwargs):
|
148 |
+
device = self.model.betas.device
|
149 |
+
# print('ddim device', device)
|
150 |
+
b = shape[0]
|
151 |
+
if x_T is None:
|
152 |
+
img = torch.randn(shape, device=device)
|
153 |
+
else:
|
154 |
+
img = x_T
|
155 |
+
|
156 |
+
if timesteps is None:
|
157 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
158 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
159 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
160 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
161 |
+
|
162 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
163 |
+
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
|
164 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
165 |
+
if verbose:
|
166 |
+
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
|
167 |
+
else:
|
168 |
+
iterator = time_range
|
169 |
+
|
170 |
+
init_x0 = False
|
171 |
+
clean_cond = kwargs.pop("clean_cond", False)
|
172 |
+
|
173 |
+
if self.training_mode == True:
|
174 |
+
if self.backprop_mode == 'last':
|
175 |
+
backprop_cutoff_idx = self.ddim_num_steps - 1
|
176 |
+
elif self.backprop_mode == 'rand':
|
177 |
+
backprop_cutoff_idx = random.randint(0, self.ddim_num_steps - 1)
|
178 |
+
elif self.backprop_mode == 'specific':
|
179 |
+
backprop_cutoff_idx = 15
|
180 |
+
|
181 |
+
for i, step in enumerate(iterator):
|
182 |
+
index = total_steps - i - 1
|
183 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
184 |
+
|
185 |
+
if self.training_mode == True:
|
186 |
+
if i >= backprop_cutoff_idx:
|
187 |
+
for name, param in self.model.named_parameters():
|
188 |
+
if "lora" in name:
|
189 |
+
param.requires_grad = True
|
190 |
+
else:
|
191 |
+
for name, param in self.model.named_parameters():
|
192 |
+
param.requires_grad = False
|
193 |
+
|
194 |
+
|
195 |
+
if start_timesteps is not None:
|
196 |
+
assert x0 is not None
|
197 |
+
if step > start_timesteps*time_range[0]:
|
198 |
+
continue
|
199 |
+
elif not init_x0:
|
200 |
+
img = self.model.q_sample(x0, ts)
|
201 |
+
init_x0 = True
|
202 |
+
|
203 |
+
# use mask to blend noised original latent (img_orig) & new sampled latent (img)
|
204 |
+
if mask is not None:
|
205 |
+
assert x0 is not None
|
206 |
+
if clean_cond:
|
207 |
+
img_orig = x0
|
208 |
+
else:
|
209 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? <ddim inversion>
|
210 |
+
img = img_orig * mask + (1. - mask) * img # keep original & modify use img
|
211 |
+
|
212 |
+
index_clip = int((1 - cond_tau) * total_steps)
|
213 |
+
if index <= index_clip and target_size is not None:
|
214 |
+
target_size_ = [target_size[0], target_size[1]//8, target_size[2]//8]
|
215 |
+
img = torch.nn.functional.interpolate(
|
216 |
+
img,
|
217 |
+
size=target_size_,
|
218 |
+
mode="nearest",
|
219 |
+
)
|
220 |
+
|
221 |
+
forward_context = torch.autograd.graph.save_on_cpu
|
222 |
+
with forward_context():
|
223 |
+
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
224 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
225 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
226 |
+
corrector_kwargs=corrector_kwargs,
|
227 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
228 |
+
unconditional_conditioning=unconditional_conditioning,
|
229 |
+
x0=x0,
|
230 |
+
**kwargs)
|
231 |
+
|
232 |
+
img, pred_x0 = outs
|
233 |
+
|
234 |
+
if callback: callback(i)
|
235 |
+
if img_callback: img_callback(pred_x0, i)
|
236 |
+
|
237 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
238 |
+
intermediates['x_inter'].append(img)
|
239 |
+
intermediates['pred_x0'].append(pred_x0)
|
240 |
+
|
241 |
+
return img, intermediates
|
242 |
+
|
243 |
+
# @torch.no_grad()
|
244 |
+
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
245 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
246 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
247 |
+
uc_type=None, conditional_guidance_scale_temporal=None, **kwargs):
|
248 |
+
b, *_, device = *x.shape, x.device
|
249 |
+
|
250 |
+
if x.dim() == 5:
|
251 |
+
is_video = True
|
252 |
+
else:
|
253 |
+
is_video = False
|
254 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
255 |
+
e_t = self.model.apply_model(x, t, c, **kwargs) # unet denoiser
|
256 |
+
else:
|
257 |
+
# with unconditional condition
|
258 |
+
if isinstance(c, torch.Tensor):
|
259 |
+
e_t = self.model.apply_model(x, t, c, **kwargs) # unet denoiser
|
260 |
+
e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **kwargs)
|
261 |
+
elif isinstance(c, dict):
|
262 |
+
e_t = self.model.apply_model(x, t, c, **kwargs) # unet denoiser
|
263 |
+
e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **kwargs) # unet denoiser
|
264 |
+
else:
|
265 |
+
raise NotImplementedError
|
266 |
+
|
267 |
+
if uc_type is None:
|
268 |
+
e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
|
269 |
+
else:
|
270 |
+
if uc_type == 'cfg_original':
|
271 |
+
e_t = e_t + unconditional_guidance_scale * (e_t - e_t_uncond)
|
272 |
+
elif uc_type == 'cfg_ours':
|
273 |
+
e_t = e_t + unconditional_guidance_scale * (e_t_uncond - e_t)
|
274 |
+
else:
|
275 |
+
raise NotImplementedError
|
276 |
+
|
277 |
+
# temporal guidance
|
278 |
+
if conditional_guidance_scale_temporal is not None:
|
279 |
+
e_t_temporal = self.model.apply_model(x, t, c, **kwargs)
|
280 |
+
e_t_image = self.model.apply_model(x, t, c, no_temporal_attn=True, **kwargs)
|
281 |
+
e_t = e_t + conditional_guidance_scale_temporal * (e_t_temporal - e_t_image)
|
282 |
+
|
283 |
+
if score_corrector is not None:
|
284 |
+
assert self.model.parameterization == "eps"
|
285 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
286 |
+
|
287 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
288 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
289 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
290 |
+
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
291 |
+
# select parameters corresponding to the currently considered timestep
|
292 |
+
|
293 |
+
if is_video:
|
294 |
+
size = (b, 1, 1, 1, 1)
|
295 |
+
else:
|
296 |
+
size = (b, 1, 1, 1)
|
297 |
+
a_t = torch.full(size, alphas[index], device=device)
|
298 |
+
a_prev = torch.full(size, alphas_prev[index], device=device)
|
299 |
+
sigma_t = torch.full(size, sigmas[index], device=device)
|
300 |
+
sqrt_one_minus_at = torch.full(size, sqrt_one_minus_alphas[index],device=device)
|
301 |
+
|
302 |
+
# current prediction for x_0
|
303 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
304 |
+
if quantize_denoised:
|
305 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
306 |
+
# direction pointing to x_t
|
307 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
308 |
+
|
309 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
310 |
+
if noise_dropout > 0.:
|
311 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
312 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
313 |
+
if self.use_scale:
|
314 |
+
scale_arr = self.model.scale_arr if use_original_steps else self.ddim_scale_arr
|
315 |
+
scale_t = torch.full(size, scale_arr[index], device=device)
|
316 |
+
scale_arr_prev = self.model.scale_arr_prev if use_original_steps else self.ddim_scale_arr_prev
|
317 |
+
scale_t_prev = torch.full(size, scale_arr_prev[index], device=device)
|
318 |
+
pred_x0 /= scale_t
|
319 |
+
x_prev = a_prev.sqrt() * scale_t_prev * pred_x0 + dir_xt + noise
|
320 |
+
else:
|
321 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
322 |
+
|
323 |
+
return x_prev, pred_x0
|
324 |
+
|
325 |
+
|
326 |
+
@torch.no_grad()
|
327 |
+
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
|
328 |
+
# fast, but does not allow for exact reconstruction
|
329 |
+
# t serves as an index to gather the correct alphas
|
330 |
+
if use_original_steps:
|
331 |
+
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
|
332 |
+
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
|
333 |
+
else:
|
334 |
+
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
|
335 |
+
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
|
336 |
+
|
337 |
+
if noise is None:
|
338 |
+
noise = torch.randn_like(x0)
|
339 |
+
|
340 |
+
def extract_into_tensor(a, t, x_shape):
|
341 |
+
b, *_ = t.shape
|
342 |
+
out = a.gather(-1, t)
|
343 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
344 |
+
|
345 |
+
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
|
346 |
+
extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
|
347 |
+
|
348 |
+
@torch.no_grad()
|
349 |
+
def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
|
350 |
+
use_original_steps=False):
|
351 |
+
|
352 |
+
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
353 |
+
timesteps = timesteps[:t_start]
|
354 |
+
|
355 |
+
time_range = np.flip(timesteps)
|
356 |
+
total_steps = timesteps.shape[0]
|
357 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
358 |
+
|
359 |
+
iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
|
360 |
+
x_dec = x_latent
|
361 |
+
for i, step in enumerate(iterator):
|
362 |
+
index = total_steps - i - 1
|
363 |
+
ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
|
364 |
+
x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
|
365 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
366 |
+
unconditional_conditioning=unconditional_conditioning)
|
367 |
+
return x_dec
|
368 |
+
|
VADER-VideoCrafter/lvdm/models/utils_diffusion.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import math
|
3 |
+
import numpy as np
|
4 |
+
from einops import repeat
|
5 |
+
import torch
|
6 |
+
import torch.nn.functional as F
|
7 |
+
|
8 |
+
|
9 |
+
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
|
10 |
+
"""
|
11 |
+
Create sinusoidal timestep embeddings.
|
12 |
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
13 |
+
These may be fractional.
|
14 |
+
:param dim: the dimension of the output.
|
15 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
16 |
+
:return: an [N x dim] Tensor of positional embeddings.
|
17 |
+
"""
|
18 |
+
if not repeat_only:
|
19 |
+
half = dim // 2
|
20 |
+
freqs = torch.exp(
|
21 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
22 |
+
).to(device=timesteps.device)
|
23 |
+
args = timesteps[:, None].float() * freqs[None]
|
24 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
25 |
+
if dim % 2:
|
26 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
27 |
+
else:
|
28 |
+
embedding = repeat(timesteps, 'b -> b d', d=dim)
|
29 |
+
return embedding
|
30 |
+
|
31 |
+
|
32 |
+
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
33 |
+
if schedule == "linear":
|
34 |
+
betas = (
|
35 |
+
torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
|
36 |
+
)
|
37 |
+
|
38 |
+
elif schedule == "cosine":
|
39 |
+
timesteps = (
|
40 |
+
torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
|
41 |
+
)
|
42 |
+
alphas = timesteps / (1 + cosine_s) * np.pi / 2
|
43 |
+
alphas = torch.cos(alphas).pow(2)
|
44 |
+
alphas = alphas / alphas[0]
|
45 |
+
betas = 1 - alphas[1:] / alphas[:-1]
|
46 |
+
betas = np.clip(betas, a_min=0, a_max=0.999)
|
47 |
+
|
48 |
+
elif schedule == "sqrt_linear":
|
49 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
|
50 |
+
elif schedule == "sqrt":
|
51 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
|
52 |
+
else:
|
53 |
+
raise ValueError(f"schedule '{schedule}' unknown.")
|
54 |
+
return betas.numpy()
|
55 |
+
|
56 |
+
|
57 |
+
def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
|
58 |
+
if ddim_discr_method == 'uniform':
|
59 |
+
c = num_ddpm_timesteps // num_ddim_timesteps
|
60 |
+
ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
|
61 |
+
elif ddim_discr_method == 'quad':
|
62 |
+
ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
|
63 |
+
else:
|
64 |
+
raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
|
65 |
+
|
66 |
+
# assert ddim_timesteps.shape[0] == num_ddim_timesteps
|
67 |
+
# add one to get the final alpha values right (the ones from first scale to data during sampling)
|
68 |
+
steps_out = ddim_timesteps + 1
|
69 |
+
if verbose:
|
70 |
+
print(f'Selected timesteps for ddim sampler: {steps_out}')
|
71 |
+
return steps_out
|
72 |
+
|
73 |
+
|
74 |
+
def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
|
75 |
+
# select alphas for computing the variance schedule
|
76 |
+
# print(f'ddim_timesteps={ddim_timesteps}, len_alphacums={len(alphacums)}')
|
77 |
+
alphas = alphacums[ddim_timesteps]
|
78 |
+
alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
|
79 |
+
|
80 |
+
# according the the formula provided in https://arxiv.org/abs/2010.02502
|
81 |
+
sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
|
82 |
+
if verbose:
|
83 |
+
print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
|
84 |
+
print(f'For the chosen value of eta, which is {eta}, '
|
85 |
+
f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
|
86 |
+
return sigmas, alphas, alphas_prev
|
87 |
+
|
88 |
+
|
89 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
90 |
+
"""
|
91 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
92 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
93 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
94 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
95 |
+
produces the cumulative product of (1-beta) up to that
|
96 |
+
part of the diffusion process.
|
97 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
98 |
+
prevent singularities.
|
99 |
+
"""
|
100 |
+
betas = []
|
101 |
+
for i in range(num_diffusion_timesteps):
|
102 |
+
t1 = i / num_diffusion_timesteps
|
103 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
104 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
105 |
+
return np.array(betas)
|
VADER-VideoCrafter/lvdm/modules/attention.py
ADDED
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
from functools import partial
|
3 |
+
import torch
|
4 |
+
from torch import nn, einsum
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from einops import rearrange, repeat
|
7 |
+
try:
|
8 |
+
import xformers
|
9 |
+
import xformers.ops
|
10 |
+
XFORMERS_IS_AVAILBLE = True
|
11 |
+
except:
|
12 |
+
XFORMERS_IS_AVAILBLE = False
|
13 |
+
from lvdm.common import (
|
14 |
+
checkpoint,
|
15 |
+
exists,
|
16 |
+
default,
|
17 |
+
)
|
18 |
+
from lvdm.basics import (
|
19 |
+
zero_module,
|
20 |
+
)
|
21 |
+
|
22 |
+
class RelativePosition(nn.Module):
|
23 |
+
""" https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
|
24 |
+
|
25 |
+
def __init__(self, num_units, max_relative_position):
|
26 |
+
super().__init__()
|
27 |
+
self.num_units = num_units
|
28 |
+
self.max_relative_position = max_relative_position
|
29 |
+
self.embeddings_table = nn.Parameter(torch.Tensor(max_relative_position * 2 + 1, num_units))
|
30 |
+
nn.init.xavier_uniform_(self.embeddings_table)
|
31 |
+
|
32 |
+
def forward(self, length_q, length_k):
|
33 |
+
device = self.embeddings_table.device
|
34 |
+
range_vec_q = torch.arange(length_q, device=device)
|
35 |
+
range_vec_k = torch.arange(length_k, device=device)
|
36 |
+
distance_mat = range_vec_k[None, :] - range_vec_q[:, None]
|
37 |
+
distance_mat_clipped = torch.clamp(distance_mat, -self.max_relative_position, self.max_relative_position)
|
38 |
+
final_mat = distance_mat_clipped + self.max_relative_position
|
39 |
+
final_mat = final_mat.long()
|
40 |
+
embeddings = self.embeddings_table[final_mat]
|
41 |
+
return embeddings
|
42 |
+
|
43 |
+
|
44 |
+
class CrossAttention(nn.Module):
|
45 |
+
|
46 |
+
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.,
|
47 |
+
relative_position=False, temporal_length=None, img_cross_attention=False):
|
48 |
+
super().__init__()
|
49 |
+
inner_dim = dim_head * heads
|
50 |
+
context_dim = default(context_dim, query_dim)
|
51 |
+
|
52 |
+
self.scale = dim_head**-0.5
|
53 |
+
self.heads = heads
|
54 |
+
self.dim_head = dim_head
|
55 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
56 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
57 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
58 |
+
self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
|
59 |
+
|
60 |
+
self.image_cross_attention_scale = 1.0
|
61 |
+
self.text_context_len = 77
|
62 |
+
self.img_cross_attention = img_cross_attention
|
63 |
+
if self.img_cross_attention:
|
64 |
+
self.to_k_ip = nn.Linear(context_dim, inner_dim, bias=False)
|
65 |
+
self.to_v_ip = nn.Linear(context_dim, inner_dim, bias=False)
|
66 |
+
|
67 |
+
self.relative_position = relative_position
|
68 |
+
if self.relative_position:
|
69 |
+
assert(temporal_length is not None)
|
70 |
+
self.relative_position_k = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
|
71 |
+
self.relative_position_v = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
|
72 |
+
else:
|
73 |
+
## only used for spatial attention, while NOT for temporal attention
|
74 |
+
if XFORMERS_IS_AVAILBLE and temporal_length is None:
|
75 |
+
self.forward = self.efficient_forward
|
76 |
+
|
77 |
+
def forward(self, x, context=None, mask=None):
|
78 |
+
h = self.heads
|
79 |
+
|
80 |
+
q = self.to_q(x)
|
81 |
+
context = default(context, x)
|
82 |
+
## considering image token additionally
|
83 |
+
if context is not None and self.img_cross_attention:
|
84 |
+
context, context_img = context[:,:self.text_context_len,:], context[:,self.text_context_len:,:]
|
85 |
+
k = self.to_k(context)
|
86 |
+
v = self.to_v(context)
|
87 |
+
k_ip = self.to_k_ip(context_img)
|
88 |
+
v_ip = self.to_v_ip(context_img)
|
89 |
+
else:
|
90 |
+
k = self.to_k(context)
|
91 |
+
v = self.to_v(context)
|
92 |
+
|
93 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
94 |
+
sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale
|
95 |
+
if self.relative_position:
|
96 |
+
len_q, len_k, len_v = q.shape[1], k.shape[1], v.shape[1]
|
97 |
+
k2 = self.relative_position_k(len_q, len_k)
|
98 |
+
sim2 = einsum('b t d, t s d -> b t s', q, k2) * self.scale # TODO check
|
99 |
+
sim += sim2
|
100 |
+
del k
|
101 |
+
|
102 |
+
if exists(mask):
|
103 |
+
## feasible for causal attention mask only
|
104 |
+
max_neg_value = -torch.finfo(sim.dtype).max
|
105 |
+
mask = repeat(mask, 'b i j -> (b h) i j', h=h)
|
106 |
+
sim.masked_fill_(~(mask>0.5), max_neg_value)
|
107 |
+
|
108 |
+
# attention, what we cannot get enough of
|
109 |
+
sim = sim.softmax(dim=-1)
|
110 |
+
out = torch.einsum('b i j, b j d -> b i d', sim, v)
|
111 |
+
if self.relative_position:
|
112 |
+
v2 = self.relative_position_v(len_q, len_v)
|
113 |
+
out2 = einsum('b t s, t s d -> b t d', sim, v2) # TODO check
|
114 |
+
out += out2
|
115 |
+
out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
|
116 |
+
|
117 |
+
## considering image token additionally
|
118 |
+
if context is not None and self.img_cross_attention:
|
119 |
+
k_ip, v_ip = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (k_ip, v_ip))
|
120 |
+
sim_ip = torch.einsum('b i d, b j d -> b i j', q, k_ip) * self.scale
|
121 |
+
del k_ip
|
122 |
+
sim_ip = sim_ip.softmax(dim=-1)
|
123 |
+
out_ip = torch.einsum('b i j, b j d -> b i d', sim_ip, v_ip)
|
124 |
+
out_ip = rearrange(out_ip, '(b h) n d -> b n (h d)', h=h)
|
125 |
+
out = out + self.image_cross_attention_scale * out_ip
|
126 |
+
del q
|
127 |
+
|
128 |
+
return self.to_out(out)
|
129 |
+
|
130 |
+
def efficient_forward(self, x, context=None, mask=None):
|
131 |
+
q = self.to_q(x)
|
132 |
+
context = default(context, x)
|
133 |
+
|
134 |
+
## considering image token additionally
|
135 |
+
if context is not None and self.img_cross_attention:
|
136 |
+
context, context_img = context[:,:self.text_context_len,:], context[:,self.text_context_len:,:]
|
137 |
+
k = self.to_k(context)
|
138 |
+
v = self.to_v(context)
|
139 |
+
k_ip = self.to_k_ip(context_img)
|
140 |
+
v_ip = self.to_v_ip(context_img)
|
141 |
+
else:
|
142 |
+
k = self.to_k(context)
|
143 |
+
v = self.to_v(context)
|
144 |
+
|
145 |
+
b, _, _ = q.shape
|
146 |
+
q, k, v = map(
|
147 |
+
lambda t: t.unsqueeze(3)
|
148 |
+
.reshape(b, t.shape[1], self.heads, self.dim_head)
|
149 |
+
.permute(0, 2, 1, 3)
|
150 |
+
.reshape(b * self.heads, t.shape[1], self.dim_head)
|
151 |
+
.contiguous(),
|
152 |
+
(q, k, v),
|
153 |
+
)
|
154 |
+
# actually compute the attention, what we cannot get enough of
|
155 |
+
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=None)
|
156 |
+
|
157 |
+
## considering image token additionally
|
158 |
+
if context is not None and self.img_cross_attention:
|
159 |
+
k_ip, v_ip = map(
|
160 |
+
lambda t: t.unsqueeze(3)
|
161 |
+
.reshape(b, t.shape[1], self.heads, self.dim_head)
|
162 |
+
.permute(0, 2, 1, 3)
|
163 |
+
.reshape(b * self.heads, t.shape[1], self.dim_head)
|
164 |
+
.contiguous(),
|
165 |
+
(k_ip, v_ip),
|
166 |
+
)
|
167 |
+
out_ip = xformers.ops.memory_efficient_attention(q, k_ip, v_ip, attn_bias=None, op=None)
|
168 |
+
out_ip = (
|
169 |
+
out_ip.unsqueeze(0)
|
170 |
+
.reshape(b, self.heads, out.shape[1], self.dim_head)
|
171 |
+
.permute(0, 2, 1, 3)
|
172 |
+
.reshape(b, out.shape[1], self.heads * self.dim_head)
|
173 |
+
)
|
174 |
+
|
175 |
+
if exists(mask):
|
176 |
+
raise NotImplementedError
|
177 |
+
out = (
|
178 |
+
out.unsqueeze(0)
|
179 |
+
.reshape(b, self.heads, out.shape[1], self.dim_head)
|
180 |
+
.permute(0, 2, 1, 3)
|
181 |
+
.reshape(b, out.shape[1], self.heads * self.dim_head)
|
182 |
+
)
|
183 |
+
if context is not None and self.img_cross_attention:
|
184 |
+
out = out + self.image_cross_attention_scale * out_ip
|
185 |
+
return self.to_out(out)
|
186 |
+
|
187 |
+
|
188 |
+
class BasicTransformerBlock(nn.Module):
|
189 |
+
|
190 |
+
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
|
191 |
+
disable_self_attn=False, attention_cls=None, img_cross_attention=False):
|
192 |
+
super().__init__()
|
193 |
+
attn_cls = CrossAttention if attention_cls is None else attention_cls
|
194 |
+
self.disable_self_attn = disable_self_attn
|
195 |
+
self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
|
196 |
+
context_dim=context_dim if self.disable_self_attn else None)
|
197 |
+
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
|
198 |
+
self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim, heads=n_heads, dim_head=d_head, dropout=dropout,
|
199 |
+
img_cross_attention=img_cross_attention)
|
200 |
+
self.norm1 = nn.LayerNorm(dim)
|
201 |
+
self.norm2 = nn.LayerNorm(dim)
|
202 |
+
self.norm3 = nn.LayerNorm(dim)
|
203 |
+
self.checkpoint = checkpoint
|
204 |
+
|
205 |
+
def forward(self, x, context=None, mask=None):
|
206 |
+
## implementation tricks: because checkpointing doesn't support non-tensor (e.g. None or scalar) arguments
|
207 |
+
input_tuple = (x,) ## should not be (x), otherwise *input_tuple will decouple x into multiple arguments
|
208 |
+
if context is not None:
|
209 |
+
input_tuple = (x, context)
|
210 |
+
if mask is not None:
|
211 |
+
forward_mask = partial(self._forward, mask=mask)
|
212 |
+
return checkpoint(forward_mask, (x,), self.parameters(), self.checkpoint)
|
213 |
+
if context is not None and mask is not None:
|
214 |
+
input_tuple = (x, context, mask)
|
215 |
+
return checkpoint(self._forward, input_tuple, self.parameters(), self.checkpoint)
|
216 |
+
|
217 |
+
def _forward(self, x, context=None, mask=None):
|
218 |
+
x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None, mask=mask) + x
|
219 |
+
x = self.attn2(self.norm2(x), context=context, mask=mask) + x
|
220 |
+
x = self.ff(self.norm3(x)) + x
|
221 |
+
return x
|
222 |
+
|
223 |
+
|
224 |
+
class SpatialTransformer(nn.Module):
|
225 |
+
"""
|
226 |
+
Transformer block for image-like data in spatial axis.
|
227 |
+
First, project the input (aka embedding)
|
228 |
+
and reshape to b, t, d.
|
229 |
+
Then apply standard transformer action.
|
230 |
+
Finally, reshape to image
|
231 |
+
NEW: use_linear for more efficiency instead of the 1x1 convs
|
232 |
+
"""
|
233 |
+
|
234 |
+
def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None,
|
235 |
+
use_checkpoint=True, disable_self_attn=False, use_linear=False, img_cross_attention=False):
|
236 |
+
super().__init__()
|
237 |
+
self.in_channels = in_channels
|
238 |
+
inner_dim = n_heads * d_head
|
239 |
+
self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
240 |
+
if not use_linear:
|
241 |
+
self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
242 |
+
else:
|
243 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
244 |
+
|
245 |
+
self.transformer_blocks = nn.ModuleList([
|
246 |
+
BasicTransformerBlock(
|
247 |
+
inner_dim,
|
248 |
+
n_heads,
|
249 |
+
d_head,
|
250 |
+
dropout=dropout,
|
251 |
+
context_dim=context_dim,
|
252 |
+
img_cross_attention=img_cross_attention,
|
253 |
+
disable_self_attn=disable_self_attn,
|
254 |
+
checkpoint=use_checkpoint) for d in range(depth)
|
255 |
+
])
|
256 |
+
if not use_linear:
|
257 |
+
self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
|
258 |
+
else:
|
259 |
+
self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
|
260 |
+
self.use_linear = use_linear
|
261 |
+
|
262 |
+
|
263 |
+
def forward(self, x, context=None):
|
264 |
+
b, c, h, w = x.shape
|
265 |
+
x_in = x
|
266 |
+
x = self.norm(x)
|
267 |
+
if not self.use_linear:
|
268 |
+
x = self.proj_in(x)
|
269 |
+
x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
|
270 |
+
if self.use_linear:
|
271 |
+
x = self.proj_in(x)
|
272 |
+
for i, block in enumerate(self.transformer_blocks):
|
273 |
+
x = block(x, context=context)
|
274 |
+
if self.use_linear:
|
275 |
+
x = self.proj_out(x)
|
276 |
+
x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
|
277 |
+
if not self.use_linear:
|
278 |
+
x = self.proj_out(x)
|
279 |
+
return x + x_in
|
280 |
+
|
281 |
+
|
282 |
+
class TemporalTransformer(nn.Module):
|
283 |
+
"""
|
284 |
+
Transformer block for image-like data in temporal axis.
|
285 |
+
First, reshape to b, t, d.
|
286 |
+
Then apply standard transformer action.
|
287 |
+
Finally, reshape to image
|
288 |
+
"""
|
289 |
+
def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None,
|
290 |
+
use_checkpoint=True, use_linear=False, only_self_att=True, causal_attention=False,
|
291 |
+
relative_position=False, temporal_length=None):
|
292 |
+
super().__init__()
|
293 |
+
self.only_self_att = only_self_att
|
294 |
+
self.relative_position = relative_position
|
295 |
+
self.causal_attention = causal_attention
|
296 |
+
self.in_channels = in_channels
|
297 |
+
inner_dim = n_heads * d_head
|
298 |
+
self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
299 |
+
self.proj_in = nn.Conv1d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
300 |
+
if not use_linear:
|
301 |
+
self.proj_in = nn.Conv1d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
302 |
+
else:
|
303 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
304 |
+
|
305 |
+
if relative_position:
|
306 |
+
assert(temporal_length is not None)
|
307 |
+
attention_cls = partial(CrossAttention, relative_position=True, temporal_length=temporal_length)
|
308 |
+
else:
|
309 |
+
attention_cls = None
|
310 |
+
if self.causal_attention:
|
311 |
+
assert(temporal_length is not None)
|
312 |
+
self.mask = torch.tril(torch.ones([1, temporal_length, temporal_length]))
|
313 |
+
|
314 |
+
if self.only_self_att:
|
315 |
+
context_dim = None
|
316 |
+
self.transformer_blocks = nn.ModuleList([
|
317 |
+
BasicTransformerBlock(
|
318 |
+
inner_dim,
|
319 |
+
n_heads,
|
320 |
+
d_head,
|
321 |
+
dropout=dropout,
|
322 |
+
context_dim=context_dim,
|
323 |
+
attention_cls=attention_cls,
|
324 |
+
checkpoint=use_checkpoint) for d in range(depth)
|
325 |
+
])
|
326 |
+
if not use_linear:
|
327 |
+
self.proj_out = zero_module(nn.Conv1d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
|
328 |
+
else:
|
329 |
+
self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
|
330 |
+
self.use_linear = use_linear
|
331 |
+
|
332 |
+
def forward(self, x, context=None):
|
333 |
+
b, c, t, h, w = x.shape
|
334 |
+
x_in = x
|
335 |
+
x = self.norm(x)
|
336 |
+
x = rearrange(x, 'b c t h w -> (b h w) c t').contiguous()
|
337 |
+
if not self.use_linear:
|
338 |
+
x = self.proj_in(x)
|
339 |
+
x = rearrange(x, 'bhw c t -> bhw t c').contiguous()
|
340 |
+
if self.use_linear:
|
341 |
+
x = self.proj_in(x)
|
342 |
+
|
343 |
+
if self.causal_attention:
|
344 |
+
mask = self.mask.to(x.device)
|
345 |
+
mask = repeat(mask, 'l i j -> (l bhw) i j', bhw=b*h*w)
|
346 |
+
else:
|
347 |
+
mask = None
|
348 |
+
|
349 |
+
if self.only_self_att:
|
350 |
+
## note: if no context is given, cross-attention defaults to self-attention
|
351 |
+
for i, block in enumerate(self.transformer_blocks):
|
352 |
+
x = block(x, mask=mask)
|
353 |
+
x = rearrange(x, '(b hw) t c -> b hw t c', b=b).contiguous()
|
354 |
+
else:
|
355 |
+
x = rearrange(x, '(b hw) t c -> b hw t c', b=b).contiguous()
|
356 |
+
context = rearrange(context, '(b t) l con -> b t l con', t=t).contiguous()
|
357 |
+
for i, block in enumerate(self.transformer_blocks):
|
358 |
+
# calculate each batch one by one (since number in shape could not greater then 65,535 for some package)
|
359 |
+
for j in range(b):
|
360 |
+
context_j = repeat(
|
361 |
+
context[j],
|
362 |
+
't l con -> (t r) l con', r=(h * w) // t, t=t).contiguous()
|
363 |
+
## note: causal mask will not applied in cross-attention case
|
364 |
+
x[j] = block(x[j], context=context_j)
|
365 |
+
|
366 |
+
if self.use_linear:
|
367 |
+
x = self.proj_out(x)
|
368 |
+
x = rearrange(x, 'b (h w) t c -> b c t h w', h=h, w=w).contiguous()
|
369 |
+
if not self.use_linear:
|
370 |
+
x = rearrange(x, 'b hw t c -> (b hw) c t').contiguous()
|
371 |
+
x = self.proj_out(x)
|
372 |
+
x = rearrange(x, '(b h w) c t -> b c t h w', b=b, h=h, w=w).contiguous()
|
373 |
+
|
374 |
+
return x + x_in
|
375 |
+
|
376 |
+
|
377 |
+
class GEGLU(nn.Module):
|
378 |
+
def __init__(self, dim_in, dim_out):
|
379 |
+
super().__init__()
|
380 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
381 |
+
|
382 |
+
def forward(self, x):
|
383 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
384 |
+
return x * F.gelu(gate)
|
385 |
+
|
386 |
+
|
387 |
+
class FeedForward(nn.Module):
|
388 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
389 |
+
super().__init__()
|
390 |
+
inner_dim = int(dim * mult)
|
391 |
+
dim_out = default(dim_out, dim)
|
392 |
+
project_in = nn.Sequential(
|
393 |
+
nn.Linear(dim, inner_dim),
|
394 |
+
nn.GELU()
|
395 |
+
) if not glu else GEGLU(dim, inner_dim)
|
396 |
+
|
397 |
+
self.net = nn.Sequential(
|
398 |
+
project_in,
|
399 |
+
nn.Dropout(dropout),
|
400 |
+
nn.Linear(inner_dim, dim_out)
|
401 |
+
)
|
402 |
+
|
403 |
+
def forward(self, x):
|
404 |
+
return self.net(x)
|
405 |
+
|
406 |
+
|
407 |
+
class LinearAttention(nn.Module):
|
408 |
+
def __init__(self, dim, heads=4, dim_head=32):
|
409 |
+
super().__init__()
|
410 |
+
self.heads = heads
|
411 |
+
hidden_dim = dim_head * heads
|
412 |
+
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
|
413 |
+
self.to_out = nn.Conv2d(hidden_dim, dim, 1)
|
414 |
+
|
415 |
+
def forward(self, x):
|
416 |
+
b, c, h, w = x.shape
|
417 |
+
qkv = self.to_qkv(x)
|
418 |
+
q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
|
419 |
+
k = k.softmax(dim=-1)
|
420 |
+
context = torch.einsum('bhdn,bhen->bhde', k, v)
|
421 |
+
out = torch.einsum('bhde,bhdn->bhen', context, q)
|
422 |
+
out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
|
423 |
+
return self.to_out(out)
|
424 |
+
|
425 |
+
|
426 |
+
class SpatialSelfAttention(nn.Module):
|
427 |
+
def __init__(self, in_channels):
|
428 |
+
super().__init__()
|
429 |
+
self.in_channels = in_channels
|
430 |
+
|
431 |
+
self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
432 |
+
self.q = torch.nn.Conv2d(in_channels,
|
433 |
+
in_channels,
|
434 |
+
kernel_size=1,
|
435 |
+
stride=1,
|
436 |
+
padding=0)
|
437 |
+
self.k = torch.nn.Conv2d(in_channels,
|
438 |
+
in_channels,
|
439 |
+
kernel_size=1,
|
440 |
+
stride=1,
|
441 |
+
padding=0)
|
442 |
+
self.v = torch.nn.Conv2d(in_channels,
|
443 |
+
in_channels,
|
444 |
+
kernel_size=1,
|
445 |
+
stride=1,
|
446 |
+
padding=0)
|
447 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
448 |
+
in_channels,
|
449 |
+
kernel_size=1,
|
450 |
+
stride=1,
|
451 |
+
padding=0)
|
452 |
+
|
453 |
+
def forward(self, x):
|
454 |
+
h_ = x
|
455 |
+
h_ = self.norm(h_)
|
456 |
+
q = self.q(h_)
|
457 |
+
k = self.k(h_)
|
458 |
+
v = self.v(h_)
|
459 |
+
|
460 |
+
# compute attention
|
461 |
+
b,c,h,w = q.shape
|
462 |
+
q = rearrange(q, 'b c h w -> b (h w) c')
|
463 |
+
k = rearrange(k, 'b c h w -> b c (h w)')
|
464 |
+
w_ = torch.einsum('bij,bjk->bik', q, k)
|
465 |
+
|
466 |
+
w_ = w_ * (int(c)**(-0.5))
|
467 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
468 |
+
|
469 |
+
# attend to values
|
470 |
+
v = rearrange(v, 'b c h w -> b c (h w)')
|
471 |
+
w_ = rearrange(w_, 'b i j -> b j i')
|
472 |
+
h_ = torch.einsum('bij,bjk->bik', v, w_)
|
473 |
+
h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
|
474 |
+
h_ = self.proj_out(h_)
|
475 |
+
|
476 |
+
return x+h_
|
VADER-VideoCrafter/lvdm/modules/encoders/condition.py
ADDED
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from torch.utils.checkpoint import checkpoint
|
5 |
+
import kornia
|
6 |
+
import open_clip
|
7 |
+
from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel
|
8 |
+
from lvdm.common import autocast
|
9 |
+
from utils.utils import count_params
|
10 |
+
|
11 |
+
class AbstractEncoder(nn.Module):
|
12 |
+
def __init__(self):
|
13 |
+
super().__init__()
|
14 |
+
|
15 |
+
def encode(self, *args, **kwargs):
|
16 |
+
raise NotImplementedError
|
17 |
+
|
18 |
+
|
19 |
+
class IdentityEncoder(AbstractEncoder):
|
20 |
+
|
21 |
+
def encode(self, x):
|
22 |
+
return x
|
23 |
+
|
24 |
+
|
25 |
+
class ClassEmbedder(nn.Module):
|
26 |
+
def __init__(self, embed_dim, n_classes=1000, key='class', ucg_rate=0.1):
|
27 |
+
super().__init__()
|
28 |
+
self.key = key
|
29 |
+
self.embedding = nn.Embedding(n_classes, embed_dim)
|
30 |
+
self.n_classes = n_classes
|
31 |
+
self.ucg_rate = ucg_rate
|
32 |
+
|
33 |
+
def forward(self, batch, key=None, disable_dropout=False):
|
34 |
+
if key is None:
|
35 |
+
key = self.key
|
36 |
+
# this is for use in crossattn
|
37 |
+
c = batch[key][:, None]
|
38 |
+
if self.ucg_rate > 0. and not disable_dropout:
|
39 |
+
mask = 1. - torch.bernoulli(torch.ones_like(c) * self.ucg_rate)
|
40 |
+
c = mask * c + (1 - mask) * torch.ones_like(c) * (self.n_classes - 1)
|
41 |
+
c = c.long()
|
42 |
+
c = self.embedding(c)
|
43 |
+
return c
|
44 |
+
|
45 |
+
def get_unconditional_conditioning(self, bs, device="cuda"):
|
46 |
+
uc_class = self.n_classes - 1 # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000)
|
47 |
+
uc = torch.ones((bs,), device=device) * uc_class
|
48 |
+
uc = {self.key: uc}
|
49 |
+
return uc
|
50 |
+
|
51 |
+
|
52 |
+
def disabled_train(self, mode=True):
|
53 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
54 |
+
does not change anymore."""
|
55 |
+
return self
|
56 |
+
|
57 |
+
|
58 |
+
class FrozenT5Embedder(AbstractEncoder):
|
59 |
+
"""Uses the T5 transformer encoder for text"""
|
60 |
+
|
61 |
+
def __init__(self, version="google/t5-v1_1-large", device="cuda", max_length=77,
|
62 |
+
freeze=True): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
|
63 |
+
super().__init__()
|
64 |
+
self.tokenizer = T5Tokenizer.from_pretrained(version)
|
65 |
+
self.transformer = T5EncoderModel.from_pretrained(version)
|
66 |
+
self.device = device
|
67 |
+
self.max_length = max_length # TODO: typical value?
|
68 |
+
if freeze:
|
69 |
+
self.freeze()
|
70 |
+
|
71 |
+
def freeze(self):
|
72 |
+
self.transformer = self.transformer.eval()
|
73 |
+
# self.train = disabled_train
|
74 |
+
for param in self.parameters():
|
75 |
+
param.requires_grad = False
|
76 |
+
|
77 |
+
def forward(self, text):
|
78 |
+
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
|
79 |
+
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
|
80 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
81 |
+
outputs = self.transformer(input_ids=tokens)
|
82 |
+
|
83 |
+
z = outputs.last_hidden_state
|
84 |
+
return z
|
85 |
+
|
86 |
+
def encode(self, text):
|
87 |
+
return self(text)
|
88 |
+
|
89 |
+
|
90 |
+
class FrozenCLIPEmbedder(AbstractEncoder):
|
91 |
+
"""Uses the CLIP transformer encoder for text (from huggingface)"""
|
92 |
+
LAYERS = [
|
93 |
+
"last",
|
94 |
+
"pooled",
|
95 |
+
"hidden"
|
96 |
+
]
|
97 |
+
|
98 |
+
def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77,
|
99 |
+
freeze=True, layer="last", layer_idx=None): # clip-vit-base-patch32
|
100 |
+
super().__init__()
|
101 |
+
assert layer in self.LAYERS
|
102 |
+
self.tokenizer = CLIPTokenizer.from_pretrained(version)
|
103 |
+
self.transformer = CLIPTextModel.from_pretrained(version)
|
104 |
+
self.device = device
|
105 |
+
self.max_length = max_length
|
106 |
+
if freeze:
|
107 |
+
self.freeze()
|
108 |
+
self.layer = layer
|
109 |
+
self.layer_idx = layer_idx
|
110 |
+
if layer == "hidden":
|
111 |
+
assert layer_idx is not None
|
112 |
+
assert 0 <= abs(layer_idx) <= 12
|
113 |
+
|
114 |
+
def freeze(self):
|
115 |
+
self.transformer = self.transformer.eval()
|
116 |
+
# self.train = disabled_train
|
117 |
+
for param in self.parameters():
|
118 |
+
param.requires_grad = False
|
119 |
+
|
120 |
+
def forward(self, text):
|
121 |
+
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
|
122 |
+
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
|
123 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
124 |
+
outputs = self.transformer(input_ids=tokens, output_hidden_states=self.layer == "hidden")
|
125 |
+
if self.layer == "last":
|
126 |
+
z = outputs.last_hidden_state
|
127 |
+
elif self.layer == "pooled":
|
128 |
+
z = outputs.pooler_output[:, None, :]
|
129 |
+
else:
|
130 |
+
z = outputs.hidden_states[self.layer_idx]
|
131 |
+
return z
|
132 |
+
|
133 |
+
def encode(self, text):
|
134 |
+
return self(text)
|
135 |
+
|
136 |
+
|
137 |
+
class ClipImageEmbedder(nn.Module):
|
138 |
+
def __init__(
|
139 |
+
self,
|
140 |
+
model,
|
141 |
+
jit=False,
|
142 |
+
device='cuda' if torch.cuda.is_available() else 'cpu',
|
143 |
+
antialias=True,
|
144 |
+
ucg_rate=0.
|
145 |
+
):
|
146 |
+
super().__init__()
|
147 |
+
from clip import load as load_clip
|
148 |
+
self.model, _ = load_clip(name=model, device=device, jit=jit)
|
149 |
+
|
150 |
+
self.antialias = antialias
|
151 |
+
|
152 |
+
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
|
153 |
+
self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
|
154 |
+
self.ucg_rate = ucg_rate
|
155 |
+
|
156 |
+
def preprocess(self, x):
|
157 |
+
# normalize to [0,1]
|
158 |
+
x = kornia.geometry.resize(x, (224, 224),
|
159 |
+
interpolation='bicubic', align_corners=True,
|
160 |
+
antialias=self.antialias)
|
161 |
+
x = (x + 1.) / 2.
|
162 |
+
# re-normalize according to clip
|
163 |
+
x = kornia.enhance.normalize(x, self.mean, self.std)
|
164 |
+
return x
|
165 |
+
|
166 |
+
def forward(self, x, no_dropout=False):
|
167 |
+
# x is assumed to be in range [-1,1]
|
168 |
+
out = self.model.encode_image(self.preprocess(x))
|
169 |
+
out = out.to(x.dtype)
|
170 |
+
if self.ucg_rate > 0. and not no_dropout:
|
171 |
+
out = torch.bernoulli((1. - self.ucg_rate) * torch.ones(out.shape[0], device=out.device))[:, None] * out
|
172 |
+
return out
|
173 |
+
|
174 |
+
|
175 |
+
class FrozenOpenCLIPEmbedder(AbstractEncoder):
|
176 |
+
"""
|
177 |
+
Uses the OpenCLIP transformer encoder for text
|
178 |
+
"""
|
179 |
+
LAYERS = [
|
180 |
+
# "pooled",
|
181 |
+
"last",
|
182 |
+
"penultimate"
|
183 |
+
]
|
184 |
+
|
185 |
+
def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda", max_length=77,
|
186 |
+
freeze=True, layer="last"):
|
187 |
+
super().__init__()
|
188 |
+
assert layer in self.LAYERS
|
189 |
+
model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'))
|
190 |
+
del model.visual
|
191 |
+
self.model = model
|
192 |
+
|
193 |
+
self.device = device
|
194 |
+
self.max_length = max_length
|
195 |
+
if freeze:
|
196 |
+
self.freeze()
|
197 |
+
self.layer = layer
|
198 |
+
if self.layer == "last":
|
199 |
+
self.layer_idx = 0
|
200 |
+
elif self.layer == "penultimate":
|
201 |
+
self.layer_idx = 1
|
202 |
+
else:
|
203 |
+
raise NotImplementedError()
|
204 |
+
|
205 |
+
def freeze(self):
|
206 |
+
self.model = self.model.eval()
|
207 |
+
for param in self.parameters():
|
208 |
+
param.requires_grad = False
|
209 |
+
|
210 |
+
def forward(self, text):
|
211 |
+
self.device = self.model.positional_embedding.device
|
212 |
+
tokens = open_clip.tokenize(text)
|
213 |
+
z = self.encode_with_transformer(tokens.to(self.device))
|
214 |
+
return z
|
215 |
+
|
216 |
+
def encode_with_transformer(self, text):
|
217 |
+
x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
|
218 |
+
x = x + self.model.positional_embedding
|
219 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
220 |
+
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
|
221 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
222 |
+
x = self.model.ln_final(x)
|
223 |
+
return x
|
224 |
+
|
225 |
+
def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
|
226 |
+
for i, r in enumerate(self.model.transformer.resblocks):
|
227 |
+
if i == len(self.model.transformer.resblocks) - self.layer_idx:
|
228 |
+
break
|
229 |
+
if self.model.transformer.grad_checkpointing and not torch.jit.is_scripting():
|
230 |
+
x = checkpoint(r, x, attn_mask)
|
231 |
+
else:
|
232 |
+
x = r(x, attn_mask=attn_mask)
|
233 |
+
return x
|
234 |
+
|
235 |
+
def encode(self, text):
|
236 |
+
return self(text)
|
237 |
+
|
238 |
+
|
239 |
+
class FrozenOpenCLIPImageEmbedder(AbstractEncoder):
|
240 |
+
"""
|
241 |
+
Uses the OpenCLIP vision transformer encoder for images
|
242 |
+
"""
|
243 |
+
|
244 |
+
def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda", max_length=77,
|
245 |
+
freeze=True, layer="pooled", antialias=True, ucg_rate=0.):
|
246 |
+
super().__init__()
|
247 |
+
model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'),
|
248 |
+
pretrained=version, )
|
249 |
+
del model.transformer
|
250 |
+
self.model = model
|
251 |
+
|
252 |
+
self.device = device
|
253 |
+
self.max_length = max_length
|
254 |
+
if freeze:
|
255 |
+
self.freeze()
|
256 |
+
self.layer = layer
|
257 |
+
if self.layer == "penultimate":
|
258 |
+
raise NotImplementedError()
|
259 |
+
self.layer_idx = 1
|
260 |
+
|
261 |
+
self.antialias = antialias
|
262 |
+
|
263 |
+
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
|
264 |
+
self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
|
265 |
+
self.ucg_rate = ucg_rate
|
266 |
+
|
267 |
+
def preprocess(self, x):
|
268 |
+
# normalize to [0,1]
|
269 |
+
x = kornia.geometry.resize(x, (224, 224),
|
270 |
+
interpolation='bicubic', align_corners=True,
|
271 |
+
antialias=self.antialias)
|
272 |
+
x = (x + 1.) / 2.
|
273 |
+
# renormalize according to clip
|
274 |
+
x = kornia.enhance.normalize(x, self.mean, self.std)
|
275 |
+
return x
|
276 |
+
|
277 |
+
def freeze(self):
|
278 |
+
self.model = self.model.eval()
|
279 |
+
for param in self.parameters():
|
280 |
+
param.requires_grad = False
|
281 |
+
|
282 |
+
@autocast
|
283 |
+
def forward(self, image, no_dropout=False):
|
284 |
+
z = self.encode_with_vision_transformer(image)
|
285 |
+
if self.ucg_rate > 0. and not no_dropout:
|
286 |
+
z = torch.bernoulli((1. - self.ucg_rate) * torch.ones(z.shape[0], device=z.device))[:, None] * z
|
287 |
+
return z
|
288 |
+
|
289 |
+
def encode_with_vision_transformer(self, img):
|
290 |
+
img = self.preprocess(img)
|
291 |
+
x = self.model.visual(img)
|
292 |
+
return x
|
293 |
+
|
294 |
+
def encode(self, text):
|
295 |
+
return self(text)
|
296 |
+
|
297 |
+
|
298 |
+
|
299 |
+
class FrozenOpenCLIPImageEmbedderV2(AbstractEncoder):
|
300 |
+
"""
|
301 |
+
Uses the OpenCLIP vision transformer encoder for images
|
302 |
+
"""
|
303 |
+
|
304 |
+
def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda",
|
305 |
+
freeze=True, layer="pooled", antialias=True):
|
306 |
+
super().__init__()
|
307 |
+
model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'),
|
308 |
+
pretrained=version, )
|
309 |
+
del model.transformer
|
310 |
+
self.model = model
|
311 |
+
self.device = device
|
312 |
+
|
313 |
+
if freeze:
|
314 |
+
self.freeze()
|
315 |
+
self.layer = layer
|
316 |
+
if self.layer == "penultimate":
|
317 |
+
raise NotImplementedError()
|
318 |
+
self.layer_idx = 1
|
319 |
+
|
320 |
+
self.antialias = antialias
|
321 |
+
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
|
322 |
+
self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
|
323 |
+
|
324 |
+
|
325 |
+
def preprocess(self, x):
|
326 |
+
# normalize to [0,1]
|
327 |
+
x = kornia.geometry.resize(x, (224, 224),
|
328 |
+
interpolation='bicubic', align_corners=True,
|
329 |
+
antialias=self.antialias)
|
330 |
+
x = (x + 1.) / 2.
|
331 |
+
# renormalize according to clip
|
332 |
+
x = kornia.enhance.normalize(x, self.mean, self.std)
|
333 |
+
return x
|
334 |
+
|
335 |
+
def freeze(self):
|
336 |
+
self.model = self.model.eval()
|
337 |
+
for param in self.model.parameters():
|
338 |
+
param.requires_grad = False
|
339 |
+
|
340 |
+
def forward(self, image, no_dropout=False):
|
341 |
+
## image: b c h w
|
342 |
+
z = self.encode_with_vision_transformer(image)
|
343 |
+
return z
|
344 |
+
|
345 |
+
def encode_with_vision_transformer(self, x):
|
346 |
+
x = self.preprocess(x)
|
347 |
+
|
348 |
+
# to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1
|
349 |
+
if self.model.visual.input_patchnorm:
|
350 |
+
# einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')
|
351 |
+
x = x.reshape(x.shape[0], x.shape[1], self.model.visual.grid_size[0], self.model.visual.patch_size[0], self.model.visual.grid_size[1], self.model.visual.patch_size[1])
|
352 |
+
x = x.permute(0, 2, 4, 1, 3, 5)
|
353 |
+
x = x.reshape(x.shape[0], self.model.visual.grid_size[0] * self.model.visual.grid_size[1], -1)
|
354 |
+
x = self.model.visual.patchnorm_pre_ln(x)
|
355 |
+
x = self.model.visual.conv1(x)
|
356 |
+
else:
|
357 |
+
x = self.model.visual.conv1(x) # shape = [*, width, grid, grid]
|
358 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
359 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
360 |
+
|
361 |
+
# class embeddings and positional embeddings
|
362 |
+
x = torch.cat(
|
363 |
+
[self.model.visual.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
|
364 |
+
x], dim=1) # shape = [*, grid ** 2 + 1, width]
|
365 |
+
x = x + self.model.visual.positional_embedding.to(x.dtype)
|
366 |
+
|
367 |
+
# a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
|
368 |
+
x = self.model.visual.patch_dropout(x)
|
369 |
+
x = self.model.visual.ln_pre(x)
|
370 |
+
|
371 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
372 |
+
x = self.model.visual.transformer(x)
|
373 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
374 |
+
|
375 |
+
return x
|
376 |
+
|
377 |
+
|
378 |
+
class FrozenCLIPT5Encoder(AbstractEncoder):
|
379 |
+
def __init__(self, clip_version="openai/clip-vit-large-patch14", t5_version="google/t5-v1_1-xl", device="cuda",
|
380 |
+
clip_max_length=77, t5_max_length=77):
|
381 |
+
super().__init__()
|
382 |
+
self.clip_encoder = FrozenCLIPEmbedder(clip_version, device, max_length=clip_max_length)
|
383 |
+
self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length)
|
384 |
+
print(f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder) * 1.e-6:.2f} M parameters, "
|
385 |
+
f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder) * 1.e-6:.2f} M params.")
|
386 |
+
|
387 |
+
def encode(self, text):
|
388 |
+
return self(text)
|
389 |
+
|
390 |
+
def forward(self, text):
|
391 |
+
clip_z = self.clip_encoder.encode(text)
|
392 |
+
t5_z = self.t5_encoder.encode(text)
|
393 |
+
return [clip_z, t5_z]
|
VADER-VideoCrafter/lvdm/modules/encoders/ip_resampler.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
# modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
|
3 |
+
import math
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
|
7 |
+
|
8 |
+
class ImageProjModel(nn.Module):
|
9 |
+
"""Projection Model"""
|
10 |
+
def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
|
11 |
+
super().__init__()
|
12 |
+
self.cross_attention_dim = cross_attention_dim
|
13 |
+
self.clip_extra_context_tokens = clip_extra_context_tokens
|
14 |
+
self.proj = nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
|
15 |
+
self.norm = nn.LayerNorm(cross_attention_dim)
|
16 |
+
|
17 |
+
def forward(self, image_embeds):
|
18 |
+
#embeds = image_embeds
|
19 |
+
embeds = image_embeds.type(list(self.proj.parameters())[0].dtype)
|
20 |
+
clip_extra_context_tokens = self.proj(embeds).reshape(-1, self.clip_extra_context_tokens, self.cross_attention_dim)
|
21 |
+
clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
|
22 |
+
return clip_extra_context_tokens
|
23 |
+
|
24 |
+
# FFN
|
25 |
+
def FeedForward(dim, mult=4):
|
26 |
+
inner_dim = int(dim * mult)
|
27 |
+
return nn.Sequential(
|
28 |
+
nn.LayerNorm(dim),
|
29 |
+
nn.Linear(dim, inner_dim, bias=False),
|
30 |
+
nn.GELU(),
|
31 |
+
nn.Linear(inner_dim, dim, bias=False),
|
32 |
+
)
|
33 |
+
|
34 |
+
|
35 |
+
def reshape_tensor(x, heads):
|
36 |
+
bs, length, width = x.shape
|
37 |
+
#(bs, length, width) --> (bs, length, n_heads, dim_per_head)
|
38 |
+
x = x.view(bs, length, heads, -1)
|
39 |
+
# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
|
40 |
+
x = x.transpose(1, 2)
|
41 |
+
# (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
|
42 |
+
x = x.reshape(bs, heads, length, -1)
|
43 |
+
return x
|
44 |
+
|
45 |
+
|
46 |
+
class PerceiverAttention(nn.Module):
|
47 |
+
def __init__(self, *, dim, dim_head=64, heads=8):
|
48 |
+
super().__init__()
|
49 |
+
self.scale = dim_head**-0.5
|
50 |
+
self.dim_head = dim_head
|
51 |
+
self.heads = heads
|
52 |
+
inner_dim = dim_head * heads
|
53 |
+
|
54 |
+
self.norm1 = nn.LayerNorm(dim)
|
55 |
+
self.norm2 = nn.LayerNorm(dim)
|
56 |
+
|
57 |
+
self.to_q = nn.Linear(dim, inner_dim, bias=False)
|
58 |
+
self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
|
59 |
+
self.to_out = nn.Linear(inner_dim, dim, bias=False)
|
60 |
+
|
61 |
+
|
62 |
+
def forward(self, x, latents):
|
63 |
+
"""
|
64 |
+
Args:
|
65 |
+
x (torch.Tensor): image features
|
66 |
+
shape (b, n1, D)
|
67 |
+
latent (torch.Tensor): latent features
|
68 |
+
shape (b, n2, D)
|
69 |
+
"""
|
70 |
+
x = self.norm1(x)
|
71 |
+
latents = self.norm2(latents)
|
72 |
+
|
73 |
+
b, l, _ = latents.shape
|
74 |
+
|
75 |
+
q = self.to_q(latents)
|
76 |
+
kv_input = torch.cat((x, latents), dim=-2)
|
77 |
+
k, v = self.to_kv(kv_input).chunk(2, dim=-1)
|
78 |
+
|
79 |
+
q = reshape_tensor(q, self.heads)
|
80 |
+
k = reshape_tensor(k, self.heads)
|
81 |
+
v = reshape_tensor(v, self.heads)
|
82 |
+
|
83 |
+
# attention
|
84 |
+
scale = 1 / math.sqrt(math.sqrt(self.dim_head))
|
85 |
+
weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
|
86 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
87 |
+
out = weight @ v
|
88 |
+
|
89 |
+
out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
|
90 |
+
|
91 |
+
return self.to_out(out)
|
92 |
+
|
93 |
+
|
94 |
+
class Resampler(nn.Module):
|
95 |
+
def __init__(
|
96 |
+
self,
|
97 |
+
dim=1024,
|
98 |
+
depth=8,
|
99 |
+
dim_head=64,
|
100 |
+
heads=16,
|
101 |
+
num_queries=8,
|
102 |
+
embedding_dim=768,
|
103 |
+
output_dim=1024,
|
104 |
+
ff_mult=4,
|
105 |
+
):
|
106 |
+
super().__init__()
|
107 |
+
|
108 |
+
self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
|
109 |
+
|
110 |
+
self.proj_in = nn.Linear(embedding_dim, dim)
|
111 |
+
|
112 |
+
self.proj_out = nn.Linear(dim, output_dim)
|
113 |
+
self.norm_out = nn.LayerNorm(output_dim)
|
114 |
+
|
115 |
+
self.layers = nn.ModuleList([])
|
116 |
+
for _ in range(depth):
|
117 |
+
self.layers.append(
|
118 |
+
nn.ModuleList(
|
119 |
+
[
|
120 |
+
PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
|
121 |
+
FeedForward(dim=dim, mult=ff_mult),
|
122 |
+
]
|
123 |
+
)
|
124 |
+
)
|
125 |
+
|
126 |
+
def forward(self, x):
|
127 |
+
|
128 |
+
latents = self.latents.repeat(x.size(0), 1, 1)
|
129 |
+
|
130 |
+
x = self.proj_in(x)
|
131 |
+
|
132 |
+
for attn, ff in self.layers:
|
133 |
+
latents = attn(x, latents) + latents
|
134 |
+
latents = ff(latents) + latents
|
135 |
+
|
136 |
+
latents = self.proj_out(latents)
|
137 |
+
return self.norm_out(latents)
|
VADER-VideoCrafter/lvdm/modules/networks/ae_modules.py
ADDED
@@ -0,0 +1,846 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
# pytorch_diffusion + derived encoder decoder
|
3 |
+
import math
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
import torch.nn as nn
|
7 |
+
from einops import rearrange
|
8 |
+
from utils.utils import instantiate_from_config
|
9 |
+
from lvdm.modules.attention import LinearAttention
|
10 |
+
|
11 |
+
def nonlinearity(x):
|
12 |
+
# swish
|
13 |
+
return x*torch.sigmoid(x)
|
14 |
+
|
15 |
+
|
16 |
+
def Normalize(in_channels, num_groups=32):
|
17 |
+
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
+
class LinAttnBlock(LinearAttention):
|
22 |
+
"""to match AttnBlock usage"""
|
23 |
+
def __init__(self, in_channels):
|
24 |
+
super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
|
25 |
+
|
26 |
+
|
27 |
+
class AttnBlock(nn.Module):
|
28 |
+
def __init__(self, in_channels):
|
29 |
+
super().__init__()
|
30 |
+
self.in_channels = in_channels
|
31 |
+
|
32 |
+
self.norm = Normalize(in_channels)
|
33 |
+
self.q = torch.nn.Conv2d(in_channels,
|
34 |
+
in_channels,
|
35 |
+
kernel_size=1,
|
36 |
+
stride=1,
|
37 |
+
padding=0)
|
38 |
+
self.k = torch.nn.Conv2d(in_channels,
|
39 |
+
in_channels,
|
40 |
+
kernel_size=1,
|
41 |
+
stride=1,
|
42 |
+
padding=0)
|
43 |
+
self.v = torch.nn.Conv2d(in_channels,
|
44 |
+
in_channels,
|
45 |
+
kernel_size=1,
|
46 |
+
stride=1,
|
47 |
+
padding=0)
|
48 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
49 |
+
in_channels,
|
50 |
+
kernel_size=1,
|
51 |
+
stride=1,
|
52 |
+
padding=0)
|
53 |
+
|
54 |
+
def forward(self, x):
|
55 |
+
h_ = x
|
56 |
+
h_ = self.norm(h_)
|
57 |
+
q = self.q(h_)
|
58 |
+
k = self.k(h_)
|
59 |
+
v = self.v(h_)
|
60 |
+
|
61 |
+
# compute attention
|
62 |
+
b,c,h,w = q.shape
|
63 |
+
q = q.reshape(b,c,h*w) # bcl
|
64 |
+
q = q.permute(0,2,1) # bcl -> blc l=hw
|
65 |
+
k = k.reshape(b,c,h*w) # bcl
|
66 |
+
|
67 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
68 |
+
w_ = w_ * (int(c)**(-0.5))
|
69 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
70 |
+
|
71 |
+
# attend to values
|
72 |
+
v = v.reshape(b,c,h*w)
|
73 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
74 |
+
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
75 |
+
h_ = h_.reshape(b,c,h,w)
|
76 |
+
|
77 |
+
h_ = self.proj_out(h_)
|
78 |
+
|
79 |
+
return x+h_
|
80 |
+
|
81 |
+
def make_attn(in_channels, attn_type="vanilla"):
|
82 |
+
assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
|
83 |
+
#print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
|
84 |
+
if attn_type == "vanilla":
|
85 |
+
return AttnBlock(in_channels)
|
86 |
+
elif attn_type == "none":
|
87 |
+
return nn.Identity(in_channels)
|
88 |
+
else:
|
89 |
+
return LinAttnBlock(in_channels)
|
90 |
+
|
91 |
+
class Downsample(nn.Module):
|
92 |
+
def __init__(self, in_channels, with_conv):
|
93 |
+
super().__init__()
|
94 |
+
self.with_conv = with_conv
|
95 |
+
self.in_channels = in_channels
|
96 |
+
if self.with_conv:
|
97 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
98 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
99 |
+
in_channels,
|
100 |
+
kernel_size=3,
|
101 |
+
stride=2,
|
102 |
+
padding=0)
|
103 |
+
def forward(self, x):
|
104 |
+
if self.with_conv:
|
105 |
+
pad = (0,1,0,1)
|
106 |
+
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
107 |
+
x = self.conv(x)
|
108 |
+
else:
|
109 |
+
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
110 |
+
return x
|
111 |
+
|
112 |
+
class Upsample(nn.Module):
|
113 |
+
def __init__(self, in_channels, with_conv):
|
114 |
+
super().__init__()
|
115 |
+
self.with_conv = with_conv
|
116 |
+
self.in_channels = in_channels
|
117 |
+
if self.with_conv:
|
118 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
119 |
+
in_channels,
|
120 |
+
kernel_size=3,
|
121 |
+
stride=1,
|
122 |
+
padding=1)
|
123 |
+
|
124 |
+
def forward(self, x):
|
125 |
+
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
126 |
+
if self.with_conv:
|
127 |
+
x = self.conv(x)
|
128 |
+
return x
|
129 |
+
|
130 |
+
def get_timestep_embedding(timesteps, embedding_dim):
|
131 |
+
"""
|
132 |
+
This matches the implementation in Denoising Diffusion Probabilistic Models:
|
133 |
+
From Fairseq.
|
134 |
+
Build sinusoidal embeddings.
|
135 |
+
This matches the implementation in tensor2tensor, but differs slightly
|
136 |
+
from the description in Section 3.5 of "Attention Is All You Need".
|
137 |
+
"""
|
138 |
+
assert len(timesteps.shape) == 1
|
139 |
+
|
140 |
+
half_dim = embedding_dim // 2
|
141 |
+
emb = math.log(10000) / (half_dim - 1)
|
142 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
|
143 |
+
emb = emb.to(device=timesteps.device)
|
144 |
+
emb = timesteps.float()[:, None] * emb[None, :]
|
145 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
146 |
+
if embedding_dim % 2 == 1: # zero pad
|
147 |
+
emb = torch.nn.functional.pad(emb, (0,1,0,0))
|
148 |
+
return emb
|
149 |
+
|
150 |
+
|
151 |
+
|
152 |
+
class ResnetBlock(nn.Module):
|
153 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
154 |
+
dropout, temb_channels=512):
|
155 |
+
super().__init__()
|
156 |
+
self.in_channels = in_channels
|
157 |
+
out_channels = in_channels if out_channels is None else out_channels
|
158 |
+
self.out_channels = out_channels
|
159 |
+
self.use_conv_shortcut = conv_shortcut
|
160 |
+
|
161 |
+
self.norm1 = Normalize(in_channels)
|
162 |
+
self.conv1 = torch.nn.Conv2d(in_channels,
|
163 |
+
out_channels,
|
164 |
+
kernel_size=3,
|
165 |
+
stride=1,
|
166 |
+
padding=1)
|
167 |
+
if temb_channels > 0:
|
168 |
+
self.temb_proj = torch.nn.Linear(temb_channels,
|
169 |
+
out_channels)
|
170 |
+
self.norm2 = Normalize(out_channels)
|
171 |
+
self.dropout = torch.nn.Dropout(dropout)
|
172 |
+
self.conv2 = torch.nn.Conv2d(out_channels,
|
173 |
+
out_channels,
|
174 |
+
kernel_size=3,
|
175 |
+
stride=1,
|
176 |
+
padding=1)
|
177 |
+
if self.in_channels != self.out_channels:
|
178 |
+
if self.use_conv_shortcut:
|
179 |
+
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
180 |
+
out_channels,
|
181 |
+
kernel_size=3,
|
182 |
+
stride=1,
|
183 |
+
padding=1)
|
184 |
+
else:
|
185 |
+
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
186 |
+
out_channels,
|
187 |
+
kernel_size=1,
|
188 |
+
stride=1,
|
189 |
+
padding=0)
|
190 |
+
|
191 |
+
def forward(self, x, temb):
|
192 |
+
h = x
|
193 |
+
h = self.norm1(h)
|
194 |
+
h = nonlinearity(h)
|
195 |
+
h = self.conv1(h)
|
196 |
+
|
197 |
+
if temb is not None:
|
198 |
+
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
|
199 |
+
|
200 |
+
h = self.norm2(h)
|
201 |
+
h = nonlinearity(h)
|
202 |
+
h = self.dropout(h)
|
203 |
+
h = self.conv2(h)
|
204 |
+
|
205 |
+
if self.in_channels != self.out_channels:
|
206 |
+
if self.use_conv_shortcut:
|
207 |
+
x = self.conv_shortcut(x)
|
208 |
+
else:
|
209 |
+
x = self.nin_shortcut(x)
|
210 |
+
|
211 |
+
return x+h
|
212 |
+
|
213 |
+
class Model(nn.Module):
|
214 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
215 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
216 |
+
resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
|
217 |
+
super().__init__()
|
218 |
+
if use_linear_attn: attn_type = "linear"
|
219 |
+
self.ch = ch
|
220 |
+
self.temb_ch = self.ch*4
|
221 |
+
self.num_resolutions = len(ch_mult)
|
222 |
+
self.num_res_blocks = num_res_blocks
|
223 |
+
self.resolution = resolution
|
224 |
+
self.in_channels = in_channels
|
225 |
+
|
226 |
+
self.use_timestep = use_timestep
|
227 |
+
if self.use_timestep:
|
228 |
+
# timestep embedding
|
229 |
+
self.temb = nn.Module()
|
230 |
+
self.temb.dense = nn.ModuleList([
|
231 |
+
torch.nn.Linear(self.ch,
|
232 |
+
self.temb_ch),
|
233 |
+
torch.nn.Linear(self.temb_ch,
|
234 |
+
self.temb_ch),
|
235 |
+
])
|
236 |
+
|
237 |
+
# downsampling
|
238 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
239 |
+
self.ch,
|
240 |
+
kernel_size=3,
|
241 |
+
stride=1,
|
242 |
+
padding=1)
|
243 |
+
|
244 |
+
curr_res = resolution
|
245 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
246 |
+
self.down = nn.ModuleList()
|
247 |
+
for i_level in range(self.num_resolutions):
|
248 |
+
block = nn.ModuleList()
|
249 |
+
attn = nn.ModuleList()
|
250 |
+
block_in = ch*in_ch_mult[i_level]
|
251 |
+
block_out = ch*ch_mult[i_level]
|
252 |
+
for i_block in range(self.num_res_blocks):
|
253 |
+
block.append(ResnetBlock(in_channels=block_in,
|
254 |
+
out_channels=block_out,
|
255 |
+
temb_channels=self.temb_ch,
|
256 |
+
dropout=dropout))
|
257 |
+
block_in = block_out
|
258 |
+
if curr_res in attn_resolutions:
|
259 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
260 |
+
down = nn.Module()
|
261 |
+
down.block = block
|
262 |
+
down.attn = attn
|
263 |
+
if i_level != self.num_resolutions-1:
|
264 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
265 |
+
curr_res = curr_res // 2
|
266 |
+
self.down.append(down)
|
267 |
+
|
268 |
+
# middle
|
269 |
+
self.mid = nn.Module()
|
270 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
271 |
+
out_channels=block_in,
|
272 |
+
temb_channels=self.temb_ch,
|
273 |
+
dropout=dropout)
|
274 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
275 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
276 |
+
out_channels=block_in,
|
277 |
+
temb_channels=self.temb_ch,
|
278 |
+
dropout=dropout)
|
279 |
+
|
280 |
+
# upsampling
|
281 |
+
self.up = nn.ModuleList()
|
282 |
+
for i_level in reversed(range(self.num_resolutions)):
|
283 |
+
block = nn.ModuleList()
|
284 |
+
attn = nn.ModuleList()
|
285 |
+
block_out = ch*ch_mult[i_level]
|
286 |
+
skip_in = ch*ch_mult[i_level]
|
287 |
+
for i_block in range(self.num_res_blocks+1):
|
288 |
+
if i_block == self.num_res_blocks:
|
289 |
+
skip_in = ch*in_ch_mult[i_level]
|
290 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
291 |
+
out_channels=block_out,
|
292 |
+
temb_channels=self.temb_ch,
|
293 |
+
dropout=dropout))
|
294 |
+
block_in = block_out
|
295 |
+
if curr_res in attn_resolutions:
|
296 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
297 |
+
up = nn.Module()
|
298 |
+
up.block = block
|
299 |
+
up.attn = attn
|
300 |
+
if i_level != 0:
|
301 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
302 |
+
curr_res = curr_res * 2
|
303 |
+
self.up.insert(0, up) # prepend to get consistent order
|
304 |
+
|
305 |
+
# end
|
306 |
+
self.norm_out = Normalize(block_in)
|
307 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
308 |
+
out_ch,
|
309 |
+
kernel_size=3,
|
310 |
+
stride=1,
|
311 |
+
padding=1)
|
312 |
+
|
313 |
+
def forward(self, x, t=None, context=None):
|
314 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
315 |
+
if context is not None:
|
316 |
+
# assume aligned context, cat along channel axis
|
317 |
+
x = torch.cat((x, context), dim=1)
|
318 |
+
if self.use_timestep:
|
319 |
+
# timestep embedding
|
320 |
+
assert t is not None
|
321 |
+
temb = get_timestep_embedding(t, self.ch)
|
322 |
+
temb = self.temb.dense[0](temb)
|
323 |
+
temb = nonlinearity(temb)
|
324 |
+
temb = self.temb.dense[1](temb)
|
325 |
+
else:
|
326 |
+
temb = None
|
327 |
+
|
328 |
+
# downsampling
|
329 |
+
hs = [self.conv_in(x)]
|
330 |
+
for i_level in range(self.num_resolutions):
|
331 |
+
for i_block in range(self.num_res_blocks):
|
332 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
333 |
+
if len(self.down[i_level].attn) > 0:
|
334 |
+
h = self.down[i_level].attn[i_block](h)
|
335 |
+
hs.append(h)
|
336 |
+
if i_level != self.num_resolutions-1:
|
337 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
338 |
+
|
339 |
+
# middle
|
340 |
+
h = hs[-1]
|
341 |
+
h = self.mid.block_1(h, temb)
|
342 |
+
h = self.mid.attn_1(h)
|
343 |
+
h = self.mid.block_2(h, temb)
|
344 |
+
|
345 |
+
# upsampling
|
346 |
+
for i_level in reversed(range(self.num_resolutions)):
|
347 |
+
for i_block in range(self.num_res_blocks+1):
|
348 |
+
h = self.up[i_level].block[i_block](
|
349 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
350 |
+
if len(self.up[i_level].attn) > 0:
|
351 |
+
h = self.up[i_level].attn[i_block](h)
|
352 |
+
if i_level != 0:
|
353 |
+
h = self.up[i_level].upsample(h)
|
354 |
+
|
355 |
+
# end
|
356 |
+
h = self.norm_out(h)
|
357 |
+
h = nonlinearity(h)
|
358 |
+
h = self.conv_out(h)
|
359 |
+
return h
|
360 |
+
|
361 |
+
def get_last_layer(self):
|
362 |
+
return self.conv_out.weight
|
363 |
+
|
364 |
+
|
365 |
+
class Encoder(nn.Module):
|
366 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
367 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
368 |
+
resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
|
369 |
+
**ignore_kwargs):
|
370 |
+
super().__init__()
|
371 |
+
if use_linear_attn: attn_type = "linear"
|
372 |
+
self.ch = ch
|
373 |
+
self.temb_ch = 0
|
374 |
+
self.num_resolutions = len(ch_mult)
|
375 |
+
self.num_res_blocks = num_res_blocks
|
376 |
+
self.resolution = resolution
|
377 |
+
self.in_channels = in_channels
|
378 |
+
|
379 |
+
# downsampling
|
380 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
381 |
+
self.ch,
|
382 |
+
kernel_size=3,
|
383 |
+
stride=1,
|
384 |
+
padding=1)
|
385 |
+
|
386 |
+
curr_res = resolution
|
387 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
388 |
+
self.in_ch_mult = in_ch_mult
|
389 |
+
self.down = nn.ModuleList()
|
390 |
+
for i_level in range(self.num_resolutions):
|
391 |
+
block = nn.ModuleList()
|
392 |
+
attn = nn.ModuleList()
|
393 |
+
block_in = ch*in_ch_mult[i_level]
|
394 |
+
block_out = ch*ch_mult[i_level]
|
395 |
+
for i_block in range(self.num_res_blocks):
|
396 |
+
block.append(ResnetBlock(in_channels=block_in,
|
397 |
+
out_channels=block_out,
|
398 |
+
temb_channels=self.temb_ch,
|
399 |
+
dropout=dropout))
|
400 |
+
block_in = block_out
|
401 |
+
if curr_res in attn_resolutions:
|
402 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
403 |
+
down = nn.Module()
|
404 |
+
down.block = block
|
405 |
+
down.attn = attn
|
406 |
+
if i_level != self.num_resolutions-1:
|
407 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
408 |
+
curr_res = curr_res // 2
|
409 |
+
self.down.append(down)
|
410 |
+
|
411 |
+
# middle
|
412 |
+
self.mid = nn.Module()
|
413 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
414 |
+
out_channels=block_in,
|
415 |
+
temb_channels=self.temb_ch,
|
416 |
+
dropout=dropout)
|
417 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
418 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
419 |
+
out_channels=block_in,
|
420 |
+
temb_channels=self.temb_ch,
|
421 |
+
dropout=dropout)
|
422 |
+
|
423 |
+
# end
|
424 |
+
self.norm_out = Normalize(block_in)
|
425 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
426 |
+
2*z_channels if double_z else z_channels,
|
427 |
+
kernel_size=3,
|
428 |
+
stride=1,
|
429 |
+
padding=1)
|
430 |
+
|
431 |
+
def forward(self, x):
|
432 |
+
# timestep embedding
|
433 |
+
temb = None
|
434 |
+
|
435 |
+
# print(f'encoder-input={x.shape}')
|
436 |
+
# downsampling
|
437 |
+
hs = [self.conv_in(x)]
|
438 |
+
# print(f'encoder-conv in feat={hs[0].shape}')
|
439 |
+
for i_level in range(self.num_resolutions):
|
440 |
+
for i_block in range(self.num_res_blocks):
|
441 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
442 |
+
# print(f'encoder-down feat={h.shape}')
|
443 |
+
if len(self.down[i_level].attn) > 0:
|
444 |
+
h = self.down[i_level].attn[i_block](h)
|
445 |
+
hs.append(h)
|
446 |
+
if i_level != self.num_resolutions-1:
|
447 |
+
# print(f'encoder-downsample (input)={hs[-1].shape}')
|
448 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
449 |
+
# print(f'encoder-downsample (output)={hs[-1].shape}')
|
450 |
+
|
451 |
+
# middle
|
452 |
+
h = hs[-1]
|
453 |
+
h = self.mid.block_1(h, temb)
|
454 |
+
# print(f'encoder-mid1 feat={h.shape}')
|
455 |
+
h = self.mid.attn_1(h)
|
456 |
+
h = self.mid.block_2(h, temb)
|
457 |
+
# print(f'encoder-mid2 feat={h.shape}')
|
458 |
+
|
459 |
+
# end
|
460 |
+
h = self.norm_out(h)
|
461 |
+
h = nonlinearity(h)
|
462 |
+
h = self.conv_out(h)
|
463 |
+
# print(f'end feat={h.shape}')
|
464 |
+
return h
|
465 |
+
|
466 |
+
|
467 |
+
class Decoder(nn.Module):
|
468 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
469 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
470 |
+
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
|
471 |
+
attn_type="vanilla", **ignorekwargs):
|
472 |
+
super().__init__()
|
473 |
+
if use_linear_attn: attn_type = "linear"
|
474 |
+
self.ch = ch
|
475 |
+
self.temb_ch = 0
|
476 |
+
self.num_resolutions = len(ch_mult)
|
477 |
+
self.num_res_blocks = num_res_blocks
|
478 |
+
self.resolution = resolution
|
479 |
+
self.in_channels = in_channels
|
480 |
+
self.give_pre_end = give_pre_end
|
481 |
+
self.tanh_out = tanh_out
|
482 |
+
|
483 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
484 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
485 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
486 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
487 |
+
self.z_shape = (1,z_channels,curr_res,curr_res)
|
488 |
+
print("AE working on z of shape {} = {} dimensions.".format(
|
489 |
+
self.z_shape, np.prod(self.z_shape)))
|
490 |
+
|
491 |
+
# z to block_in
|
492 |
+
self.conv_in = torch.nn.Conv2d(z_channels,
|
493 |
+
block_in,
|
494 |
+
kernel_size=3,
|
495 |
+
stride=1,
|
496 |
+
padding=1)
|
497 |
+
|
498 |
+
# middle
|
499 |
+
self.mid = nn.Module()
|
500 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
501 |
+
out_channels=block_in,
|
502 |
+
temb_channels=self.temb_ch,
|
503 |
+
dropout=dropout)
|
504 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
505 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
506 |
+
out_channels=block_in,
|
507 |
+
temb_channels=self.temb_ch,
|
508 |
+
dropout=dropout)
|
509 |
+
|
510 |
+
# upsampling
|
511 |
+
self.up = nn.ModuleList()
|
512 |
+
for i_level in reversed(range(self.num_resolutions)):
|
513 |
+
block = nn.ModuleList()
|
514 |
+
attn = nn.ModuleList()
|
515 |
+
block_out = ch*ch_mult[i_level]
|
516 |
+
for i_block in range(self.num_res_blocks+1):
|
517 |
+
block.append(ResnetBlock(in_channels=block_in,
|
518 |
+
out_channels=block_out,
|
519 |
+
temb_channels=self.temb_ch,
|
520 |
+
dropout=dropout))
|
521 |
+
block_in = block_out
|
522 |
+
if curr_res in attn_resolutions:
|
523 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
524 |
+
up = nn.Module()
|
525 |
+
up.block = block
|
526 |
+
up.attn = attn
|
527 |
+
if i_level != 0:
|
528 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
529 |
+
curr_res = curr_res * 2
|
530 |
+
self.up.insert(0, up) # prepend to get consistent order
|
531 |
+
|
532 |
+
# end
|
533 |
+
self.norm_out = Normalize(block_in)
|
534 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
535 |
+
out_ch,
|
536 |
+
kernel_size=3,
|
537 |
+
stride=1,
|
538 |
+
padding=1)
|
539 |
+
|
540 |
+
def forward(self, z):
|
541 |
+
#assert z.shape[1:] == self.z_shape[1:]
|
542 |
+
self.last_z_shape = z.shape
|
543 |
+
|
544 |
+
# print(f'decoder-input={z.shape}')
|
545 |
+
# timestep embedding
|
546 |
+
temb = None
|
547 |
+
|
548 |
+
# z to block_in
|
549 |
+
h = self.conv_in(z)
|
550 |
+
# print(f'decoder-conv in feat={h.shape}')
|
551 |
+
|
552 |
+
# middle
|
553 |
+
h = self.mid.block_1(h, temb)
|
554 |
+
h = self.mid.attn_1(h)
|
555 |
+
h = self.mid.block_2(h, temb)
|
556 |
+
# print(f'decoder-mid feat={h.shape}')
|
557 |
+
|
558 |
+
# upsampling
|
559 |
+
for i_level in reversed(range(self.num_resolutions)):
|
560 |
+
for i_block in range(self.num_res_blocks+1):
|
561 |
+
h = self.up[i_level].block[i_block](h, temb)
|
562 |
+
if len(self.up[i_level].attn) > 0:
|
563 |
+
h = self.up[i_level].attn[i_block](h)
|
564 |
+
# print(f'decoder-up feat={h.shape}')
|
565 |
+
if i_level != 0:
|
566 |
+
h = self.up[i_level].upsample(h)
|
567 |
+
# print(f'decoder-upsample feat={h.shape}')
|
568 |
+
|
569 |
+
# end
|
570 |
+
if self.give_pre_end:
|
571 |
+
return h
|
572 |
+
|
573 |
+
h = self.norm_out(h)
|
574 |
+
h = nonlinearity(h)
|
575 |
+
h = self.conv_out(h)
|
576 |
+
# print(f'decoder-conv_out feat={h.shape}')
|
577 |
+
if self.tanh_out:
|
578 |
+
h = torch.tanh(h)
|
579 |
+
return h
|
580 |
+
|
581 |
+
|
582 |
+
class SimpleDecoder(nn.Module):
|
583 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
584 |
+
super().__init__()
|
585 |
+
self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
|
586 |
+
ResnetBlock(in_channels=in_channels,
|
587 |
+
out_channels=2 * in_channels,
|
588 |
+
temb_channels=0, dropout=0.0),
|
589 |
+
ResnetBlock(in_channels=2 * in_channels,
|
590 |
+
out_channels=4 * in_channels,
|
591 |
+
temb_channels=0, dropout=0.0),
|
592 |
+
ResnetBlock(in_channels=4 * in_channels,
|
593 |
+
out_channels=2 * in_channels,
|
594 |
+
temb_channels=0, dropout=0.0),
|
595 |
+
nn.Conv2d(2*in_channels, in_channels, 1),
|
596 |
+
Upsample(in_channels, with_conv=True)])
|
597 |
+
# end
|
598 |
+
self.norm_out = Normalize(in_channels)
|
599 |
+
self.conv_out = torch.nn.Conv2d(in_channels,
|
600 |
+
out_channels,
|
601 |
+
kernel_size=3,
|
602 |
+
stride=1,
|
603 |
+
padding=1)
|
604 |
+
|
605 |
+
def forward(self, x):
|
606 |
+
for i, layer in enumerate(self.model):
|
607 |
+
if i in [1,2,3]:
|
608 |
+
x = layer(x, None)
|
609 |
+
else:
|
610 |
+
x = layer(x)
|
611 |
+
|
612 |
+
h = self.norm_out(x)
|
613 |
+
h = nonlinearity(h)
|
614 |
+
x = self.conv_out(h)
|
615 |
+
return x
|
616 |
+
|
617 |
+
|
618 |
+
class UpsampleDecoder(nn.Module):
|
619 |
+
def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
|
620 |
+
ch_mult=(2,2), dropout=0.0):
|
621 |
+
super().__init__()
|
622 |
+
# upsampling
|
623 |
+
self.temb_ch = 0
|
624 |
+
self.num_resolutions = len(ch_mult)
|
625 |
+
self.num_res_blocks = num_res_blocks
|
626 |
+
block_in = in_channels
|
627 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
628 |
+
self.res_blocks = nn.ModuleList()
|
629 |
+
self.upsample_blocks = nn.ModuleList()
|
630 |
+
for i_level in range(self.num_resolutions):
|
631 |
+
res_block = []
|
632 |
+
block_out = ch * ch_mult[i_level]
|
633 |
+
for i_block in range(self.num_res_blocks + 1):
|
634 |
+
res_block.append(ResnetBlock(in_channels=block_in,
|
635 |
+
out_channels=block_out,
|
636 |
+
temb_channels=self.temb_ch,
|
637 |
+
dropout=dropout))
|
638 |
+
block_in = block_out
|
639 |
+
self.res_blocks.append(nn.ModuleList(res_block))
|
640 |
+
if i_level != self.num_resolutions - 1:
|
641 |
+
self.upsample_blocks.append(Upsample(block_in, True))
|
642 |
+
curr_res = curr_res * 2
|
643 |
+
|
644 |
+
# end
|
645 |
+
self.norm_out = Normalize(block_in)
|
646 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
647 |
+
out_channels,
|
648 |
+
kernel_size=3,
|
649 |
+
stride=1,
|
650 |
+
padding=1)
|
651 |
+
|
652 |
+
def forward(self, x):
|
653 |
+
# upsampling
|
654 |
+
h = x
|
655 |
+
for k, i_level in enumerate(range(self.num_resolutions)):
|
656 |
+
for i_block in range(self.num_res_blocks + 1):
|
657 |
+
h = self.res_blocks[i_level][i_block](h, None)
|
658 |
+
if i_level != self.num_resolutions - 1:
|
659 |
+
h = self.upsample_blocks[k](h)
|
660 |
+
h = self.norm_out(h)
|
661 |
+
h = nonlinearity(h)
|
662 |
+
h = self.conv_out(h)
|
663 |
+
return h
|
664 |
+
|
665 |
+
|
666 |
+
class LatentRescaler(nn.Module):
|
667 |
+
def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
|
668 |
+
super().__init__()
|
669 |
+
# residual block, interpolate, residual block
|
670 |
+
self.factor = factor
|
671 |
+
self.conv_in = nn.Conv2d(in_channels,
|
672 |
+
mid_channels,
|
673 |
+
kernel_size=3,
|
674 |
+
stride=1,
|
675 |
+
padding=1)
|
676 |
+
self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
677 |
+
out_channels=mid_channels,
|
678 |
+
temb_channels=0,
|
679 |
+
dropout=0.0) for _ in range(depth)])
|
680 |
+
self.attn = AttnBlock(mid_channels)
|
681 |
+
self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
682 |
+
out_channels=mid_channels,
|
683 |
+
temb_channels=0,
|
684 |
+
dropout=0.0) for _ in range(depth)])
|
685 |
+
|
686 |
+
self.conv_out = nn.Conv2d(mid_channels,
|
687 |
+
out_channels,
|
688 |
+
kernel_size=1,
|
689 |
+
)
|
690 |
+
|
691 |
+
def forward(self, x):
|
692 |
+
x = self.conv_in(x)
|
693 |
+
for block in self.res_block1:
|
694 |
+
x = block(x, None)
|
695 |
+
x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
|
696 |
+
x = self.attn(x)
|
697 |
+
for block in self.res_block2:
|
698 |
+
x = block(x, None)
|
699 |
+
x = self.conv_out(x)
|
700 |
+
return x
|
701 |
+
|
702 |
+
|
703 |
+
class MergedRescaleEncoder(nn.Module):
|
704 |
+
def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
|
705 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True,
|
706 |
+
ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
|
707 |
+
super().__init__()
|
708 |
+
intermediate_chn = ch * ch_mult[-1]
|
709 |
+
self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
|
710 |
+
z_channels=intermediate_chn, double_z=False, resolution=resolution,
|
711 |
+
attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
|
712 |
+
out_ch=None)
|
713 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
|
714 |
+
mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
|
715 |
+
|
716 |
+
def forward(self, x):
|
717 |
+
x = self.encoder(x)
|
718 |
+
x = self.rescaler(x)
|
719 |
+
return x
|
720 |
+
|
721 |
+
|
722 |
+
class MergedRescaleDecoder(nn.Module):
|
723 |
+
def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
|
724 |
+
dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
|
725 |
+
super().__init__()
|
726 |
+
tmp_chn = z_channels*ch_mult[-1]
|
727 |
+
self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
|
728 |
+
resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
|
729 |
+
ch_mult=ch_mult, resolution=resolution, ch=ch)
|
730 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
|
731 |
+
out_channels=tmp_chn, depth=rescale_module_depth)
|
732 |
+
|
733 |
+
def forward(self, x):
|
734 |
+
x = self.rescaler(x)
|
735 |
+
x = self.decoder(x)
|
736 |
+
return x
|
737 |
+
|
738 |
+
|
739 |
+
class Upsampler(nn.Module):
|
740 |
+
def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
|
741 |
+
super().__init__()
|
742 |
+
assert out_size >= in_size
|
743 |
+
num_blocks = int(np.log2(out_size//in_size))+1
|
744 |
+
factor_up = 1.+ (out_size % in_size)
|
745 |
+
print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
|
746 |
+
self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
|
747 |
+
out_channels=in_channels)
|
748 |
+
self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
|
749 |
+
attn_resolutions=[], in_channels=None, ch=in_channels,
|
750 |
+
ch_mult=[ch_mult for _ in range(num_blocks)])
|
751 |
+
|
752 |
+
def forward(self, x):
|
753 |
+
x = self.rescaler(x)
|
754 |
+
x = self.decoder(x)
|
755 |
+
return x
|
756 |
+
|
757 |
+
|
758 |
+
class Resize(nn.Module):
|
759 |
+
def __init__(self, in_channels=None, learned=False, mode="bilinear"):
|
760 |
+
super().__init__()
|
761 |
+
self.with_conv = learned
|
762 |
+
self.mode = mode
|
763 |
+
if self.with_conv:
|
764 |
+
print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
|
765 |
+
raise NotImplementedError()
|
766 |
+
assert in_channels is not None
|
767 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
768 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
769 |
+
in_channels,
|
770 |
+
kernel_size=4,
|
771 |
+
stride=2,
|
772 |
+
padding=1)
|
773 |
+
|
774 |
+
def forward(self, x, scale_factor=1.0):
|
775 |
+
if scale_factor==1.0:
|
776 |
+
return x
|
777 |
+
else:
|
778 |
+
x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
|
779 |
+
return x
|
780 |
+
|
781 |
+
class FirstStagePostProcessor(nn.Module):
|
782 |
+
|
783 |
+
def __init__(self, ch_mult:list, in_channels,
|
784 |
+
pretrained_model:nn.Module=None,
|
785 |
+
reshape=False,
|
786 |
+
n_channels=None,
|
787 |
+
dropout=0.,
|
788 |
+
pretrained_config=None):
|
789 |
+
super().__init__()
|
790 |
+
if pretrained_config is None:
|
791 |
+
assert pretrained_model is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
792 |
+
self.pretrained_model = pretrained_model
|
793 |
+
else:
|
794 |
+
assert pretrained_config is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
795 |
+
self.instantiate_pretrained(pretrained_config)
|
796 |
+
|
797 |
+
self.do_reshape = reshape
|
798 |
+
|
799 |
+
if n_channels is None:
|
800 |
+
n_channels = self.pretrained_model.encoder.ch
|
801 |
+
|
802 |
+
self.proj_norm = Normalize(in_channels,num_groups=in_channels//2)
|
803 |
+
self.proj = nn.Conv2d(in_channels,n_channels,kernel_size=3,
|
804 |
+
stride=1,padding=1)
|
805 |
+
|
806 |
+
blocks = []
|
807 |
+
downs = []
|
808 |
+
ch_in = n_channels
|
809 |
+
for m in ch_mult:
|
810 |
+
blocks.append(ResnetBlock(in_channels=ch_in,out_channels=m*n_channels,dropout=dropout))
|
811 |
+
ch_in = m * n_channels
|
812 |
+
downs.append(Downsample(ch_in, with_conv=False))
|
813 |
+
|
814 |
+
self.model = nn.ModuleList(blocks)
|
815 |
+
self.downsampler = nn.ModuleList(downs)
|
816 |
+
|
817 |
+
|
818 |
+
def instantiate_pretrained(self, config):
|
819 |
+
model = instantiate_from_config(config)
|
820 |
+
self.pretrained_model = model.eval()
|
821 |
+
# self.pretrained_model.train = False
|
822 |
+
for param in self.pretrained_model.parameters():
|
823 |
+
param.requires_grad = False
|
824 |
+
|
825 |
+
|
826 |
+
@torch.no_grad()
|
827 |
+
def encode_with_pretrained(self,x):
|
828 |
+
c = self.pretrained_model.encode(x)
|
829 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
830 |
+
c = c.mode()
|
831 |
+
return c
|
832 |
+
|
833 |
+
def forward(self,x):
|
834 |
+
z_fs = self.encode_with_pretrained(x)
|
835 |
+
z = self.proj_norm(z_fs)
|
836 |
+
z = self.proj(z)
|
837 |
+
z = nonlinearity(z)
|
838 |
+
|
839 |
+
for submodel, downmodel in zip(self.model,self.downsampler):
|
840 |
+
z = submodel(z,temb=None)
|
841 |
+
z = downmodel(z)
|
842 |
+
|
843 |
+
if self.do_reshape:
|
844 |
+
z = rearrange(z,'b c h w -> b (h w) c')
|
845 |
+
return z
|
846 |
+
|
VADER-VideoCrafter/lvdm/modules/networks/openaimodel3d.py
ADDED
@@ -0,0 +1,578 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
from functools import partial
|
3 |
+
from abc import abstractmethod
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
from einops import rearrange
|
7 |
+
import torch.nn.functional as F
|
8 |
+
from lvdm.models.utils_diffusion import timestep_embedding
|
9 |
+
from lvdm.common import checkpoint
|
10 |
+
from lvdm.basics import (
|
11 |
+
zero_module,
|
12 |
+
conv_nd,
|
13 |
+
linear,
|
14 |
+
avg_pool_nd,
|
15 |
+
normalization
|
16 |
+
)
|
17 |
+
from lvdm.modules.attention import SpatialTransformer, TemporalTransformer
|
18 |
+
|
19 |
+
|
20 |
+
class TimestepBlock(nn.Module):
|
21 |
+
"""
|
22 |
+
Any module where forward() takes timestep embeddings as a second argument.
|
23 |
+
"""
|
24 |
+
@abstractmethod
|
25 |
+
def forward(self, x, emb):
|
26 |
+
"""
|
27 |
+
Apply the module to `x` given `emb` timestep embeddings.
|
28 |
+
"""
|
29 |
+
|
30 |
+
|
31 |
+
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
|
32 |
+
"""
|
33 |
+
A sequential module that passes timestep embeddings to the children that
|
34 |
+
support it as an extra input.
|
35 |
+
"""
|
36 |
+
|
37 |
+
def forward(self, x, emb, context=None, batch_size=None):
|
38 |
+
for layer in self:
|
39 |
+
if isinstance(layer, TimestepBlock):
|
40 |
+
x = layer(x, emb, batch_size)
|
41 |
+
elif isinstance(layer, SpatialTransformer):
|
42 |
+
x = layer(x, context)
|
43 |
+
elif isinstance(layer, TemporalTransformer):
|
44 |
+
x = rearrange(x, '(b f) c h w -> b c f h w', b=batch_size)
|
45 |
+
x = layer(x, context)
|
46 |
+
x = rearrange(x, 'b c f h w -> (b f) c h w')
|
47 |
+
else:
|
48 |
+
x = layer(x,)
|
49 |
+
return x
|
50 |
+
|
51 |
+
|
52 |
+
class Downsample(nn.Module):
|
53 |
+
"""
|
54 |
+
A downsampling layer with an optional convolution.
|
55 |
+
:param channels: channels in the inputs and outputs.
|
56 |
+
:param use_conv: a bool determining if a convolution is applied.
|
57 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
58 |
+
downsampling occurs in the inner-two dimensions.
|
59 |
+
"""
|
60 |
+
|
61 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
|
62 |
+
super().__init__()
|
63 |
+
self.channels = channels
|
64 |
+
self.out_channels = out_channels or channels
|
65 |
+
self.use_conv = use_conv
|
66 |
+
self.dims = dims
|
67 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
68 |
+
if use_conv:
|
69 |
+
self.op = conv_nd(
|
70 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
|
71 |
+
)
|
72 |
+
else:
|
73 |
+
assert self.channels == self.out_channels
|
74 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
75 |
+
|
76 |
+
def forward(self, x):
|
77 |
+
assert x.shape[1] == self.channels
|
78 |
+
return self.op(x)
|
79 |
+
|
80 |
+
|
81 |
+
class Upsample(nn.Module):
|
82 |
+
"""
|
83 |
+
An upsampling layer with an optional convolution.
|
84 |
+
:param channels: channels in the inputs and outputs.
|
85 |
+
:param use_conv: a bool determining if a convolution is applied.
|
86 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
87 |
+
upsampling occurs in the inner-two dimensions.
|
88 |
+
"""
|
89 |
+
|
90 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
|
91 |
+
super().__init__()
|
92 |
+
self.channels = channels
|
93 |
+
self.out_channels = out_channels or channels
|
94 |
+
self.use_conv = use_conv
|
95 |
+
self.dims = dims
|
96 |
+
if use_conv:
|
97 |
+
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
|
98 |
+
|
99 |
+
def forward(self, x):
|
100 |
+
assert x.shape[1] == self.channels
|
101 |
+
if self.dims == 3:
|
102 |
+
x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode='nearest')
|
103 |
+
else:
|
104 |
+
x = F.interpolate(x, scale_factor=2, mode='nearest')
|
105 |
+
if self.use_conv:
|
106 |
+
x = self.conv(x)
|
107 |
+
return x
|
108 |
+
|
109 |
+
|
110 |
+
class ResBlock(TimestepBlock):
|
111 |
+
"""
|
112 |
+
A residual block that can optionally change the number of channels.
|
113 |
+
:param channels: the number of input channels.
|
114 |
+
:param emb_channels: the number of timestep embedding channels.
|
115 |
+
:param dropout: the rate of dropout.
|
116 |
+
:param out_channels: if specified, the number of out channels.
|
117 |
+
:param use_conv: if True and out_channels is specified, use a spatial
|
118 |
+
convolution instead of a smaller 1x1 convolution to change the
|
119 |
+
channels in the skip connection.
|
120 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
121 |
+
:param up: if True, use this block for upsampling.
|
122 |
+
:param down: if True, use this block for downsampling.
|
123 |
+
"""
|
124 |
+
|
125 |
+
def __init__(
|
126 |
+
self,
|
127 |
+
channels,
|
128 |
+
emb_channels,
|
129 |
+
dropout,
|
130 |
+
out_channels=None,
|
131 |
+
use_scale_shift_norm=False,
|
132 |
+
dims=2,
|
133 |
+
use_checkpoint=False,
|
134 |
+
use_conv=False,
|
135 |
+
up=False,
|
136 |
+
down=False,
|
137 |
+
use_temporal_conv=False,
|
138 |
+
tempspatial_aware=False
|
139 |
+
):
|
140 |
+
super().__init__()
|
141 |
+
self.channels = channels
|
142 |
+
self.emb_channels = emb_channels
|
143 |
+
self.dropout = dropout
|
144 |
+
self.out_channels = out_channels or channels
|
145 |
+
self.use_conv = use_conv
|
146 |
+
self.use_checkpoint = use_checkpoint
|
147 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
148 |
+
self.use_temporal_conv = use_temporal_conv
|
149 |
+
|
150 |
+
self.in_layers = nn.Sequential(
|
151 |
+
normalization(channels),
|
152 |
+
nn.SiLU(),
|
153 |
+
conv_nd(dims, channels, self.out_channels, 3, padding=1),
|
154 |
+
)
|
155 |
+
|
156 |
+
self.updown = up or down
|
157 |
+
|
158 |
+
if up:
|
159 |
+
self.h_upd = Upsample(channels, False, dims)
|
160 |
+
self.x_upd = Upsample(channels, False, dims)
|
161 |
+
elif down:
|
162 |
+
self.h_upd = Downsample(channels, False, dims)
|
163 |
+
self.x_upd = Downsample(channels, False, dims)
|
164 |
+
else:
|
165 |
+
self.h_upd = self.x_upd = nn.Identity()
|
166 |
+
|
167 |
+
self.emb_layers = nn.Sequential(
|
168 |
+
nn.SiLU(),
|
169 |
+
nn.Linear(
|
170 |
+
emb_channels,
|
171 |
+
2 * self.out_channels if use_scale_shift_norm else self.out_channels,
|
172 |
+
),
|
173 |
+
)
|
174 |
+
self.out_layers = nn.Sequential(
|
175 |
+
normalization(self.out_channels),
|
176 |
+
nn.SiLU(),
|
177 |
+
nn.Dropout(p=dropout),
|
178 |
+
zero_module(nn.Conv2d(self.out_channels, self.out_channels, 3, padding=1)),
|
179 |
+
)
|
180 |
+
|
181 |
+
if self.out_channels == channels:
|
182 |
+
self.skip_connection = nn.Identity()
|
183 |
+
elif use_conv:
|
184 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)
|
185 |
+
else:
|
186 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
187 |
+
|
188 |
+
if self.use_temporal_conv:
|
189 |
+
self.temopral_conv = TemporalConvBlock(
|
190 |
+
self.out_channels,
|
191 |
+
self.out_channels,
|
192 |
+
dropout=0.1,
|
193 |
+
spatial_aware=tempspatial_aware
|
194 |
+
)
|
195 |
+
|
196 |
+
def forward(self, x, emb, batch_size=None):
|
197 |
+
"""
|
198 |
+
Apply the block to a Tensor, conditioned on a timestep embedding.
|
199 |
+
:param x: an [N x C x ...] Tensor of features.
|
200 |
+
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
|
201 |
+
:return: an [N x C x ...] Tensor of outputs.
|
202 |
+
"""
|
203 |
+
input_tuple = (x, emb,)
|
204 |
+
if batch_size:
|
205 |
+
forward_batchsize = partial(self._forward, batch_size=batch_size)
|
206 |
+
return checkpoint(forward_batchsize, input_tuple, self.parameters(), self.use_checkpoint)
|
207 |
+
return checkpoint(self._forward, input_tuple, self.parameters(), self.use_checkpoint)
|
208 |
+
|
209 |
+
def _forward(self, x, emb, batch_size=None,):
|
210 |
+
if self.updown:
|
211 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
212 |
+
h = in_rest(x)
|
213 |
+
h = self.h_upd(h)
|
214 |
+
x = self.x_upd(x)
|
215 |
+
h = in_conv(h)
|
216 |
+
else:
|
217 |
+
h = self.in_layers(x)
|
218 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
219 |
+
while len(emb_out.shape) < len(h.shape):
|
220 |
+
emb_out = emb_out[..., None]
|
221 |
+
if self.use_scale_shift_norm:
|
222 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
223 |
+
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
224 |
+
h = out_norm(h) * (1 + scale) + shift
|
225 |
+
h = out_rest(h)
|
226 |
+
else:
|
227 |
+
h = h + emb_out
|
228 |
+
h = self.out_layers(h)
|
229 |
+
h = self.skip_connection(x) + h
|
230 |
+
|
231 |
+
if self.use_temporal_conv and batch_size:
|
232 |
+
h = rearrange(h, '(b t) c h w -> b c t h w', b=batch_size)
|
233 |
+
h = self.temopral_conv(h)
|
234 |
+
h = rearrange(h, 'b c t h w -> (b t) c h w')
|
235 |
+
return h
|
236 |
+
|
237 |
+
|
238 |
+
class TemporalConvBlock(nn.Module):
|
239 |
+
"""
|
240 |
+
Adapted from modelscope: https://github.com/modelscope/modelscope/blob/master/modelscope/models/multi_modal/video_synthesis/unet_sd.py
|
241 |
+
"""
|
242 |
+
|
243 |
+
def __init__(self, in_channels, out_channels=None, dropout=0.0, spatial_aware=False):
|
244 |
+
super(TemporalConvBlock, self).__init__()
|
245 |
+
if out_channels is None:
|
246 |
+
out_channels = in_channels
|
247 |
+
self.in_channels = in_channels
|
248 |
+
self.out_channels = out_channels
|
249 |
+
kernel_shape = (3, 1, 1) if not spatial_aware else (3, 3, 3)
|
250 |
+
padding_shape = (1, 0, 0) if not spatial_aware else (1, 1, 1)
|
251 |
+
|
252 |
+
# conv layers
|
253 |
+
self.conv1 = nn.Sequential(
|
254 |
+
nn.GroupNorm(32, in_channels), nn.SiLU(),
|
255 |
+
nn.Conv3d(in_channels, out_channels, kernel_shape, padding=padding_shape))
|
256 |
+
self.conv2 = nn.Sequential(
|
257 |
+
nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
|
258 |
+
nn.Conv3d(out_channels, in_channels, kernel_shape, padding=padding_shape))
|
259 |
+
self.conv3 = nn.Sequential(
|
260 |
+
nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
|
261 |
+
nn.Conv3d(out_channels, in_channels, (3, 1, 1), padding=(1, 0, 0)))
|
262 |
+
self.conv4 = nn.Sequential(
|
263 |
+
nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
|
264 |
+
nn.Conv3d(out_channels, in_channels, (3, 1, 1), padding=(1, 0, 0)))
|
265 |
+
|
266 |
+
# zero out the last layer params,so the conv block is identity
|
267 |
+
nn.init.zeros_(self.conv4[-1].weight)
|
268 |
+
nn.init.zeros_(self.conv4[-1].bias)
|
269 |
+
|
270 |
+
def forward(self, x):
|
271 |
+
identity = x
|
272 |
+
x = self.conv1(x)
|
273 |
+
x = self.conv2(x)
|
274 |
+
x = self.conv3(x)
|
275 |
+
x = self.conv4(x)
|
276 |
+
|
277 |
+
return x + identity
|
278 |
+
|
279 |
+
|
280 |
+
class UNetModel(nn.Module):
|
281 |
+
"""
|
282 |
+
The full UNet model with attention and timestep embedding.
|
283 |
+
:param in_channels: in_channels in the input Tensor.
|
284 |
+
:param model_channels: base channel count for the model.
|
285 |
+
:param out_channels: channels in the output Tensor.
|
286 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
287 |
+
:param attention_resolutions: a collection of downsample rates at which
|
288 |
+
attention will take place. May be a set, list, or tuple.
|
289 |
+
For example, if this contains 4, then at 4x downsampling, attention
|
290 |
+
will be used.
|
291 |
+
:param dropout: the dropout probability.
|
292 |
+
:param channel_mult: channel multiplier for each level of the UNet.
|
293 |
+
:param conv_resample: if True, use learned convolutions for upsampling and
|
294 |
+
downsampling.
|
295 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
296 |
+
:param num_classes: if specified (as an int), then this model will be
|
297 |
+
class-conditional with `num_classes` classes.
|
298 |
+
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
|
299 |
+
:param num_heads: the number of attention heads in each attention layer.
|
300 |
+
:param num_heads_channels: if specified, ignore num_heads and instead use
|
301 |
+
a fixed channel width per attention head.
|
302 |
+
:param num_heads_upsample: works with num_heads to set a different number
|
303 |
+
of heads for upsampling. Deprecated.
|
304 |
+
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
|
305 |
+
:param resblock_updown: use residual blocks for up/downsampling.
|
306 |
+
"""
|
307 |
+
|
308 |
+
def __init__(self,
|
309 |
+
in_channels,
|
310 |
+
model_channels,
|
311 |
+
out_channels,
|
312 |
+
num_res_blocks,
|
313 |
+
attention_resolutions,
|
314 |
+
dropout=0.0,
|
315 |
+
channel_mult=(1, 2, 4, 8),
|
316 |
+
conv_resample=True,
|
317 |
+
dims=2,
|
318 |
+
context_dim=None,
|
319 |
+
use_scale_shift_norm=False,
|
320 |
+
resblock_updown=False,
|
321 |
+
num_heads=-1,
|
322 |
+
num_head_channels=-1,
|
323 |
+
transformer_depth=1,
|
324 |
+
use_linear=False,
|
325 |
+
use_checkpoint=False,
|
326 |
+
temporal_conv=False,
|
327 |
+
tempspatial_aware=False,
|
328 |
+
temporal_attention=True,
|
329 |
+
temporal_selfatt_only=True,
|
330 |
+
use_relative_position=True,
|
331 |
+
use_causal_attention=False,
|
332 |
+
temporal_length=None,
|
333 |
+
use_fp16=False,
|
334 |
+
addition_attention=False,
|
335 |
+
use_image_attention=False,
|
336 |
+
temporal_transformer_depth=1,
|
337 |
+
fps_cond=False,
|
338 |
+
):
|
339 |
+
super(UNetModel, self).__init__()
|
340 |
+
if num_heads == -1:
|
341 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
342 |
+
if num_head_channels == -1:
|
343 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
344 |
+
|
345 |
+
self.in_channels = in_channels
|
346 |
+
self.model_channels = model_channels
|
347 |
+
self.out_channels = out_channels
|
348 |
+
self.num_res_blocks = num_res_blocks
|
349 |
+
self.attention_resolutions = attention_resolutions
|
350 |
+
self.dropout = dropout
|
351 |
+
self.channel_mult = channel_mult
|
352 |
+
self.conv_resample = conv_resample
|
353 |
+
self.temporal_attention = temporal_attention
|
354 |
+
time_embed_dim = model_channels * 4
|
355 |
+
self.use_checkpoint = use_checkpoint
|
356 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
357 |
+
self.addition_attention=addition_attention
|
358 |
+
self.use_image_attention = use_image_attention
|
359 |
+
self.fps_cond=fps_cond
|
360 |
+
|
361 |
+
|
362 |
+
|
363 |
+
self.time_embed = nn.Sequential(
|
364 |
+
linear(model_channels, time_embed_dim),
|
365 |
+
nn.SiLU(),
|
366 |
+
linear(time_embed_dim, time_embed_dim),
|
367 |
+
)
|
368 |
+
if self.fps_cond:
|
369 |
+
self.fps_embedding = nn.Sequential(
|
370 |
+
linear(model_channels, time_embed_dim),
|
371 |
+
nn.SiLU(),
|
372 |
+
linear(time_embed_dim, time_embed_dim),
|
373 |
+
)
|
374 |
+
|
375 |
+
self.input_blocks = nn.ModuleList(
|
376 |
+
[
|
377 |
+
TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))
|
378 |
+
]
|
379 |
+
)
|
380 |
+
if self.addition_attention:
|
381 |
+
self.init_attn=TimestepEmbedSequential(
|
382 |
+
TemporalTransformer(
|
383 |
+
model_channels,
|
384 |
+
n_heads=8,
|
385 |
+
d_head=num_head_channels,
|
386 |
+
depth=transformer_depth,
|
387 |
+
context_dim=context_dim,
|
388 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
|
389 |
+
causal_attention=use_causal_attention, relative_position=use_relative_position,
|
390 |
+
temporal_length=temporal_length))
|
391 |
+
|
392 |
+
input_block_chans = [model_channels]
|
393 |
+
ch = model_channels
|
394 |
+
ds = 1
|
395 |
+
for level, mult in enumerate(channel_mult):
|
396 |
+
for _ in range(num_res_blocks):
|
397 |
+
layers = [
|
398 |
+
ResBlock(ch, time_embed_dim, dropout,
|
399 |
+
out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint,
|
400 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
401 |
+
use_temporal_conv=temporal_conv
|
402 |
+
)
|
403 |
+
]
|
404 |
+
ch = mult * model_channels
|
405 |
+
if ds in attention_resolutions:
|
406 |
+
if num_head_channels == -1:
|
407 |
+
dim_head = ch // num_heads
|
408 |
+
else:
|
409 |
+
num_heads = ch // num_head_channels
|
410 |
+
dim_head = num_head_channels
|
411 |
+
layers.append(
|
412 |
+
SpatialTransformer(ch, num_heads, dim_head,
|
413 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
414 |
+
use_checkpoint=use_checkpoint, disable_self_attn=False,
|
415 |
+
img_cross_attention=self.use_image_attention
|
416 |
+
)
|
417 |
+
)
|
418 |
+
if self.temporal_attention:
|
419 |
+
layers.append(
|
420 |
+
TemporalTransformer(ch, num_heads, dim_head,
|
421 |
+
depth=temporal_transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
422 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
|
423 |
+
causal_attention=use_causal_attention, relative_position=use_relative_position,
|
424 |
+
temporal_length=temporal_length
|
425 |
+
)
|
426 |
+
)
|
427 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
428 |
+
input_block_chans.append(ch)
|
429 |
+
if level != len(channel_mult) - 1:
|
430 |
+
out_ch = ch
|
431 |
+
self.input_blocks.append(
|
432 |
+
TimestepEmbedSequential(
|
433 |
+
ResBlock(ch, time_embed_dim, dropout,
|
434 |
+
out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint,
|
435 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
436 |
+
down=True
|
437 |
+
)
|
438 |
+
if resblock_updown
|
439 |
+
else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
440 |
+
)
|
441 |
+
)
|
442 |
+
ch = out_ch
|
443 |
+
input_block_chans.append(ch)
|
444 |
+
ds *= 2
|
445 |
+
|
446 |
+
if num_head_channels == -1:
|
447 |
+
dim_head = ch // num_heads
|
448 |
+
else:
|
449 |
+
num_heads = ch // num_head_channels
|
450 |
+
dim_head = num_head_channels
|
451 |
+
layers = [
|
452 |
+
ResBlock(ch, time_embed_dim, dropout,
|
453 |
+
dims=dims, use_checkpoint=use_checkpoint,
|
454 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
455 |
+
use_temporal_conv=temporal_conv
|
456 |
+
),
|
457 |
+
SpatialTransformer(ch, num_heads, dim_head,
|
458 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
459 |
+
use_checkpoint=use_checkpoint, disable_self_attn=False,
|
460 |
+
img_cross_attention=self.use_image_attention
|
461 |
+
)
|
462 |
+
]
|
463 |
+
if self.temporal_attention:
|
464 |
+
layers.append(
|
465 |
+
TemporalTransformer(ch, num_heads, dim_head,
|
466 |
+
depth=temporal_transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
467 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
|
468 |
+
causal_attention=use_causal_attention, relative_position=use_relative_position,
|
469 |
+
temporal_length=temporal_length
|
470 |
+
)
|
471 |
+
)
|
472 |
+
layers.append(
|
473 |
+
ResBlock(ch, time_embed_dim, dropout,
|
474 |
+
dims=dims, use_checkpoint=use_checkpoint,
|
475 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
476 |
+
use_temporal_conv=temporal_conv
|
477 |
+
)
|
478 |
+
)
|
479 |
+
self.middle_block = TimestepEmbedSequential(*layers)
|
480 |
+
|
481 |
+
self.output_blocks = nn.ModuleList([])
|
482 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
483 |
+
for i in range(num_res_blocks + 1):
|
484 |
+
ich = input_block_chans.pop()
|
485 |
+
layers = [
|
486 |
+
ResBlock(ch + ich, time_embed_dim, dropout,
|
487 |
+
out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint,
|
488 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
489 |
+
use_temporal_conv=temporal_conv
|
490 |
+
)
|
491 |
+
]
|
492 |
+
ch = model_channels * mult
|
493 |
+
if ds in attention_resolutions:
|
494 |
+
if num_head_channels == -1:
|
495 |
+
dim_head = ch // num_heads
|
496 |
+
else:
|
497 |
+
num_heads = ch // num_head_channels
|
498 |
+
dim_head = num_head_channels
|
499 |
+
layers.append(
|
500 |
+
SpatialTransformer(ch, num_heads, dim_head,
|
501 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
502 |
+
use_checkpoint=use_checkpoint, disable_self_attn=False,
|
503 |
+
img_cross_attention=self.use_image_attention
|
504 |
+
)
|
505 |
+
)
|
506 |
+
if self.temporal_attention:
|
507 |
+
layers.append(
|
508 |
+
TemporalTransformer(ch, num_heads, dim_head,
|
509 |
+
depth=temporal_transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
510 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
|
511 |
+
causal_attention=use_causal_attention, relative_position=use_relative_position,
|
512 |
+
temporal_length=temporal_length
|
513 |
+
)
|
514 |
+
)
|
515 |
+
if level and i == num_res_blocks:
|
516 |
+
out_ch = ch
|
517 |
+
layers.append(
|
518 |
+
ResBlock(ch, time_embed_dim, dropout,
|
519 |
+
out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint,
|
520 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
521 |
+
up=True
|
522 |
+
)
|
523 |
+
if resblock_updown
|
524 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
525 |
+
)
|
526 |
+
ds //= 2
|
527 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
528 |
+
|
529 |
+
self.out = nn.Sequential(
|
530 |
+
normalization(ch),
|
531 |
+
nn.SiLU(),
|
532 |
+
zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
|
533 |
+
)
|
534 |
+
|
535 |
+
def forward(self, x, timesteps, context=None, features_adapter=None, fps=16, **kwargs):
|
536 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
537 |
+
emb = self.time_embed(t_emb)
|
538 |
+
|
539 |
+
if self.fps_cond:
|
540 |
+
if type(fps) == int:
|
541 |
+
fps = torch.full_like(timesteps, fps)
|
542 |
+
fps_emb = timestep_embedding(fps,self.model_channels, repeat_only=False)
|
543 |
+
emb += self.fps_embedding(fps_emb)
|
544 |
+
|
545 |
+
b,_,t,_,_ = x.shape
|
546 |
+
## repeat t times for context [(b t) 77 768] & time embedding
|
547 |
+
context = context.repeat_interleave(repeats=t, dim=0)
|
548 |
+
emb = emb.repeat_interleave(repeats=t, dim=0)
|
549 |
+
|
550 |
+
## always in shape (b t) c h w, except for temporal layer
|
551 |
+
x = rearrange(x, 'b c t h w -> (b t) c h w')
|
552 |
+
|
553 |
+
h = x.type(self.dtype)
|
554 |
+
adapter_idx = 0
|
555 |
+
hs = []
|
556 |
+
for id, module in enumerate(self.input_blocks):
|
557 |
+
h = module(h, emb, context=context, batch_size=b)
|
558 |
+
if id ==0 and self.addition_attention:
|
559 |
+
h = self.init_attn(h, emb, context=context, batch_size=b)
|
560 |
+
## plug-in adapter features
|
561 |
+
if ((id+1)%3 == 0) and features_adapter is not None:
|
562 |
+
h = h + features_adapter[adapter_idx]
|
563 |
+
adapter_idx += 1
|
564 |
+
hs.append(h)
|
565 |
+
if features_adapter is not None:
|
566 |
+
assert len(features_adapter)==adapter_idx, 'Wrong features_adapter'
|
567 |
+
|
568 |
+
h = self.middle_block(h, emb, context=context, batch_size=b)
|
569 |
+
for module in self.output_blocks:
|
570 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
571 |
+
h = module(h, emb, context=context, batch_size=b)
|
572 |
+
h = h.type(x.dtype)
|
573 |
+
y = self.out(h)
|
574 |
+
|
575 |
+
# reshape back to (b c t h w)
|
576 |
+
y = rearrange(y, '(b t) c h w -> b c t h w', b=b)
|
577 |
+
return y
|
578 |
+
|
VADER-VideoCrafter/lvdm/modules/x_transformer.py
ADDED
@@ -0,0 +1,640 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""shout-out to https://github.com/lucidrains/x-transformers/tree/main/x_transformers"""
|
2 |
+
from functools import partial
|
3 |
+
from inspect import isfunction
|
4 |
+
from collections import namedtuple
|
5 |
+
from einops import rearrange, repeat
|
6 |
+
import torch
|
7 |
+
from torch import nn, einsum
|
8 |
+
import torch.nn.functional as F
|
9 |
+
|
10 |
+
# constants
|
11 |
+
DEFAULT_DIM_HEAD = 64
|
12 |
+
|
13 |
+
Intermediates = namedtuple('Intermediates', [
|
14 |
+
'pre_softmax_attn',
|
15 |
+
'post_softmax_attn'
|
16 |
+
])
|
17 |
+
|
18 |
+
LayerIntermediates = namedtuple('Intermediates', [
|
19 |
+
'hiddens',
|
20 |
+
'attn_intermediates'
|
21 |
+
])
|
22 |
+
|
23 |
+
|
24 |
+
class AbsolutePositionalEmbedding(nn.Module):
|
25 |
+
def __init__(self, dim, max_seq_len):
|
26 |
+
super().__init__()
|
27 |
+
self.emb = nn.Embedding(max_seq_len, dim)
|
28 |
+
self.init_()
|
29 |
+
|
30 |
+
def init_(self):
|
31 |
+
nn.init.normal_(self.emb.weight, std=0.02)
|
32 |
+
|
33 |
+
def forward(self, x):
|
34 |
+
n = torch.arange(x.shape[1], device=x.device)
|
35 |
+
return self.emb(n)[None, :, :]
|
36 |
+
|
37 |
+
|
38 |
+
class FixedPositionalEmbedding(nn.Module):
|
39 |
+
def __init__(self, dim):
|
40 |
+
super().__init__()
|
41 |
+
inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
42 |
+
self.register_buffer('inv_freq', inv_freq)
|
43 |
+
|
44 |
+
def forward(self, x, seq_dim=1, offset=0):
|
45 |
+
t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq) + offset
|
46 |
+
sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq)
|
47 |
+
emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1)
|
48 |
+
return emb[None, :, :]
|
49 |
+
|
50 |
+
|
51 |
+
# helpers
|
52 |
+
|
53 |
+
def exists(val):
|
54 |
+
return val is not None
|
55 |
+
|
56 |
+
|
57 |
+
def default(val, d):
|
58 |
+
if exists(val):
|
59 |
+
return val
|
60 |
+
return d() if isfunction(d) else d
|
61 |
+
|
62 |
+
|
63 |
+
def always(val):
|
64 |
+
def inner(*args, **kwargs):
|
65 |
+
return val
|
66 |
+
return inner
|
67 |
+
|
68 |
+
|
69 |
+
def not_equals(val):
|
70 |
+
def inner(x):
|
71 |
+
return x != val
|
72 |
+
return inner
|
73 |
+
|
74 |
+
|
75 |
+
def equals(val):
|
76 |
+
def inner(x):
|
77 |
+
return x == val
|
78 |
+
return inner
|
79 |
+
|
80 |
+
|
81 |
+
def max_neg_value(tensor):
|
82 |
+
return -torch.finfo(tensor.dtype).max
|
83 |
+
|
84 |
+
|
85 |
+
# keyword argument helpers
|
86 |
+
|
87 |
+
def pick_and_pop(keys, d):
|
88 |
+
values = list(map(lambda key: d.pop(key), keys))
|
89 |
+
return dict(zip(keys, values))
|
90 |
+
|
91 |
+
|
92 |
+
def group_dict_by_key(cond, d):
|
93 |
+
return_val = [dict(), dict()]
|
94 |
+
for key in d.keys():
|
95 |
+
match = bool(cond(key))
|
96 |
+
ind = int(not match)
|
97 |
+
return_val[ind][key] = d[key]
|
98 |
+
return (*return_val,)
|
99 |
+
|
100 |
+
|
101 |
+
def string_begins_with(prefix, str):
|
102 |
+
return str.startswith(prefix)
|
103 |
+
|
104 |
+
|
105 |
+
def group_by_key_prefix(prefix, d):
|
106 |
+
return group_dict_by_key(partial(string_begins_with, prefix), d)
|
107 |
+
|
108 |
+
|
109 |
+
def groupby_prefix_and_trim(prefix, d):
|
110 |
+
kwargs_with_prefix, kwargs = group_dict_by_key(partial(string_begins_with, prefix), d)
|
111 |
+
kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items())))
|
112 |
+
return kwargs_without_prefix, kwargs
|
113 |
+
|
114 |
+
|
115 |
+
# classes
|
116 |
+
class Scale(nn.Module):
|
117 |
+
def __init__(self, value, fn):
|
118 |
+
super().__init__()
|
119 |
+
self.value = value
|
120 |
+
self.fn = fn
|
121 |
+
|
122 |
+
def forward(self, x, **kwargs):
|
123 |
+
x, *rest = self.fn(x, **kwargs)
|
124 |
+
return (x * self.value, *rest)
|
125 |
+
|
126 |
+
|
127 |
+
class Rezero(nn.Module):
|
128 |
+
def __init__(self, fn):
|
129 |
+
super().__init__()
|
130 |
+
self.fn = fn
|
131 |
+
self.g = nn.Parameter(torch.zeros(1))
|
132 |
+
|
133 |
+
def forward(self, x, **kwargs):
|
134 |
+
x, *rest = self.fn(x, **kwargs)
|
135 |
+
return (x * self.g, *rest)
|
136 |
+
|
137 |
+
|
138 |
+
class ScaleNorm(nn.Module):
|
139 |
+
def __init__(self, dim, eps=1e-5):
|
140 |
+
super().__init__()
|
141 |
+
self.scale = dim ** -0.5
|
142 |
+
self.eps = eps
|
143 |
+
self.g = nn.Parameter(torch.ones(1))
|
144 |
+
|
145 |
+
def forward(self, x):
|
146 |
+
norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
|
147 |
+
return x / norm.clamp(min=self.eps) * self.g
|
148 |
+
|
149 |
+
|
150 |
+
class RMSNorm(nn.Module):
|
151 |
+
def __init__(self, dim, eps=1e-8):
|
152 |
+
super().__init__()
|
153 |
+
self.scale = dim ** -0.5
|
154 |
+
self.eps = eps
|
155 |
+
self.g = nn.Parameter(torch.ones(dim))
|
156 |
+
|
157 |
+
def forward(self, x):
|
158 |
+
norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
|
159 |
+
return x / norm.clamp(min=self.eps) * self.g
|
160 |
+
|
161 |
+
|
162 |
+
class Residual(nn.Module):
|
163 |
+
def forward(self, x, residual):
|
164 |
+
return x + residual
|
165 |
+
|
166 |
+
|
167 |
+
class GRUGating(nn.Module):
|
168 |
+
def __init__(self, dim):
|
169 |
+
super().__init__()
|
170 |
+
self.gru = nn.GRUCell(dim, dim)
|
171 |
+
|
172 |
+
def forward(self, x, residual):
|
173 |
+
gated_output = self.gru(
|
174 |
+
rearrange(x, 'b n d -> (b n) d'),
|
175 |
+
rearrange(residual, 'b n d -> (b n) d')
|
176 |
+
)
|
177 |
+
|
178 |
+
return gated_output.reshape_as(x)
|
179 |
+
|
180 |
+
|
181 |
+
# feedforward
|
182 |
+
|
183 |
+
class GEGLU(nn.Module):
|
184 |
+
def __init__(self, dim_in, dim_out):
|
185 |
+
super().__init__()
|
186 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
187 |
+
|
188 |
+
def forward(self, x):
|
189 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
190 |
+
return x * F.gelu(gate)
|
191 |
+
|
192 |
+
|
193 |
+
class FeedForward(nn.Module):
|
194 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
195 |
+
super().__init__()
|
196 |
+
inner_dim = int(dim * mult)
|
197 |
+
dim_out = default(dim_out, dim)
|
198 |
+
project_in = nn.Sequential(
|
199 |
+
nn.Linear(dim, inner_dim),
|
200 |
+
nn.GELU()
|
201 |
+
) if not glu else GEGLU(dim, inner_dim)
|
202 |
+
|
203 |
+
self.net = nn.Sequential(
|
204 |
+
project_in,
|
205 |
+
nn.Dropout(dropout),
|
206 |
+
nn.Linear(inner_dim, dim_out)
|
207 |
+
)
|
208 |
+
|
209 |
+
def forward(self, x):
|
210 |
+
return self.net(x)
|
211 |
+
|
212 |
+
|
213 |
+
# attention.
|
214 |
+
class Attention(nn.Module):
|
215 |
+
def __init__(
|
216 |
+
self,
|
217 |
+
dim,
|
218 |
+
dim_head=DEFAULT_DIM_HEAD,
|
219 |
+
heads=8,
|
220 |
+
causal=False,
|
221 |
+
mask=None,
|
222 |
+
talking_heads=False,
|
223 |
+
sparse_topk=None,
|
224 |
+
use_entmax15=False,
|
225 |
+
num_mem_kv=0,
|
226 |
+
dropout=0.,
|
227 |
+
on_attn=False
|
228 |
+
):
|
229 |
+
super().__init__()
|
230 |
+
if use_entmax15:
|
231 |
+
raise NotImplementedError("Check out entmax activation instead of softmax activation!")
|
232 |
+
self.scale = dim_head ** -0.5
|
233 |
+
self.heads = heads
|
234 |
+
self.causal = causal
|
235 |
+
self.mask = mask
|
236 |
+
|
237 |
+
inner_dim = dim_head * heads
|
238 |
+
|
239 |
+
self.to_q = nn.Linear(dim, inner_dim, bias=False)
|
240 |
+
self.to_k = nn.Linear(dim, inner_dim, bias=False)
|
241 |
+
self.to_v = nn.Linear(dim, inner_dim, bias=False)
|
242 |
+
self.dropout = nn.Dropout(dropout)
|
243 |
+
|
244 |
+
# talking heads
|
245 |
+
self.talking_heads = talking_heads
|
246 |
+
if talking_heads:
|
247 |
+
self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads))
|
248 |
+
self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads))
|
249 |
+
|
250 |
+
# explicit topk sparse attention
|
251 |
+
self.sparse_topk = sparse_topk
|
252 |
+
|
253 |
+
# entmax
|
254 |
+
#self.attn_fn = entmax15 if use_entmax15 else F.softmax
|
255 |
+
self.attn_fn = F.softmax
|
256 |
+
|
257 |
+
# add memory key / values
|
258 |
+
self.num_mem_kv = num_mem_kv
|
259 |
+
if num_mem_kv > 0:
|
260 |
+
self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
|
261 |
+
self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
|
262 |
+
|
263 |
+
# attention on attention
|
264 |
+
self.attn_on_attn = on_attn
|
265 |
+
self.to_out = nn.Sequential(nn.Linear(inner_dim, dim * 2), nn.GLU()) if on_attn else nn.Linear(inner_dim, dim)
|
266 |
+
|
267 |
+
def forward(
|
268 |
+
self,
|
269 |
+
x,
|
270 |
+
context=None,
|
271 |
+
mask=None,
|
272 |
+
context_mask=None,
|
273 |
+
rel_pos=None,
|
274 |
+
sinusoidal_emb=None,
|
275 |
+
prev_attn=None,
|
276 |
+
mem=None
|
277 |
+
):
|
278 |
+
b, n, _, h, talking_heads, device = *x.shape, self.heads, self.talking_heads, x.device
|
279 |
+
kv_input = default(context, x)
|
280 |
+
|
281 |
+
q_input = x
|
282 |
+
k_input = kv_input
|
283 |
+
v_input = kv_input
|
284 |
+
|
285 |
+
if exists(mem):
|
286 |
+
k_input = torch.cat((mem, k_input), dim=-2)
|
287 |
+
v_input = torch.cat((mem, v_input), dim=-2)
|
288 |
+
|
289 |
+
if exists(sinusoidal_emb):
|
290 |
+
# in shortformer, the query would start at a position offset depending on the past cached memory
|
291 |
+
offset = k_input.shape[-2] - q_input.shape[-2]
|
292 |
+
q_input = q_input + sinusoidal_emb(q_input, offset=offset)
|
293 |
+
k_input = k_input + sinusoidal_emb(k_input)
|
294 |
+
|
295 |
+
q = self.to_q(q_input)
|
296 |
+
k = self.to_k(k_input)
|
297 |
+
v = self.to_v(v_input)
|
298 |
+
|
299 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v))
|
300 |
+
|
301 |
+
input_mask = None
|
302 |
+
if any(map(exists, (mask, context_mask))):
|
303 |
+
q_mask = default(mask, lambda: torch.ones((b, n), device=device).bool())
|
304 |
+
k_mask = q_mask if not exists(context) else context_mask
|
305 |
+
k_mask = default(k_mask, lambda: torch.ones((b, k.shape[-2]), device=device).bool())
|
306 |
+
q_mask = rearrange(q_mask, 'b i -> b () i ()')
|
307 |
+
k_mask = rearrange(k_mask, 'b j -> b () () j')
|
308 |
+
input_mask = q_mask * k_mask
|
309 |
+
|
310 |
+
if self.num_mem_kv > 0:
|
311 |
+
mem_k, mem_v = map(lambda t: repeat(t, 'h n d -> b h n d', b=b), (self.mem_k, self.mem_v))
|
312 |
+
k = torch.cat((mem_k, k), dim=-2)
|
313 |
+
v = torch.cat((mem_v, v), dim=-2)
|
314 |
+
if exists(input_mask):
|
315 |
+
input_mask = F.pad(input_mask, (self.num_mem_kv, 0), value=True)
|
316 |
+
|
317 |
+
dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale
|
318 |
+
mask_value = max_neg_value(dots)
|
319 |
+
|
320 |
+
if exists(prev_attn):
|
321 |
+
dots = dots + prev_attn
|
322 |
+
|
323 |
+
pre_softmax_attn = dots
|
324 |
+
|
325 |
+
if talking_heads:
|
326 |
+
dots = einsum('b h i j, h k -> b k i j', dots, self.pre_softmax_proj).contiguous()
|
327 |
+
|
328 |
+
if exists(rel_pos):
|
329 |
+
dots = rel_pos(dots)
|
330 |
+
|
331 |
+
if exists(input_mask):
|
332 |
+
dots.masked_fill_(~input_mask, mask_value)
|
333 |
+
del input_mask
|
334 |
+
|
335 |
+
if self.causal:
|
336 |
+
i, j = dots.shape[-2:]
|
337 |
+
r = torch.arange(i, device=device)
|
338 |
+
mask = rearrange(r, 'i -> () () i ()') < rearrange(r, 'j -> () () () j')
|
339 |
+
mask = F.pad(mask, (j - i, 0), value=False)
|
340 |
+
dots.masked_fill_(mask, mask_value)
|
341 |
+
del mask
|
342 |
+
|
343 |
+
if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]:
|
344 |
+
top, _ = dots.topk(self.sparse_topk, dim=-1)
|
345 |
+
vk = top[..., -1].unsqueeze(-1).expand_as(dots)
|
346 |
+
mask = dots < vk
|
347 |
+
dots.masked_fill_(mask, mask_value)
|
348 |
+
del mask
|
349 |
+
|
350 |
+
attn = self.attn_fn(dots, dim=-1)
|
351 |
+
post_softmax_attn = attn
|
352 |
+
|
353 |
+
attn = self.dropout(attn)
|
354 |
+
|
355 |
+
if talking_heads:
|
356 |
+
attn = einsum('b h i j, h k -> b k i j', attn, self.post_softmax_proj).contiguous()
|
357 |
+
|
358 |
+
out = einsum('b h i j, b h j d -> b h i d', attn, v)
|
359 |
+
out = rearrange(out, 'b h n d -> b n (h d)')
|
360 |
+
|
361 |
+
intermediates = Intermediates(
|
362 |
+
pre_softmax_attn=pre_softmax_attn,
|
363 |
+
post_softmax_attn=post_softmax_attn
|
364 |
+
)
|
365 |
+
|
366 |
+
return self.to_out(out), intermediates
|
367 |
+
|
368 |
+
|
369 |
+
class AttentionLayers(nn.Module):
|
370 |
+
def __init__(
|
371 |
+
self,
|
372 |
+
dim,
|
373 |
+
depth,
|
374 |
+
heads=8,
|
375 |
+
causal=False,
|
376 |
+
cross_attend=False,
|
377 |
+
only_cross=False,
|
378 |
+
use_scalenorm=False,
|
379 |
+
use_rmsnorm=False,
|
380 |
+
use_rezero=False,
|
381 |
+
rel_pos_num_buckets=32,
|
382 |
+
rel_pos_max_distance=128,
|
383 |
+
position_infused_attn=False,
|
384 |
+
custom_layers=None,
|
385 |
+
sandwich_coef=None,
|
386 |
+
par_ratio=None,
|
387 |
+
residual_attn=False,
|
388 |
+
cross_residual_attn=False,
|
389 |
+
macaron=False,
|
390 |
+
pre_norm=True,
|
391 |
+
gate_residual=False,
|
392 |
+
**kwargs
|
393 |
+
):
|
394 |
+
super().__init__()
|
395 |
+
ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs)
|
396 |
+
attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs)
|
397 |
+
|
398 |
+
dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD)
|
399 |
+
|
400 |
+
self.dim = dim
|
401 |
+
self.depth = depth
|
402 |
+
self.layers = nn.ModuleList([])
|
403 |
+
|
404 |
+
self.has_pos_emb = position_infused_attn
|
405 |
+
self.pia_pos_emb = FixedPositionalEmbedding(dim) if position_infused_attn else None
|
406 |
+
self.rotary_pos_emb = always(None)
|
407 |
+
|
408 |
+
assert rel_pos_num_buckets <= rel_pos_max_distance, 'number of relative position buckets must be less than the relative position max distance'
|
409 |
+
self.rel_pos = None
|
410 |
+
|
411 |
+
self.pre_norm = pre_norm
|
412 |
+
|
413 |
+
self.residual_attn = residual_attn
|
414 |
+
self.cross_residual_attn = cross_residual_attn
|
415 |
+
|
416 |
+
norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm
|
417 |
+
norm_class = RMSNorm if use_rmsnorm else norm_class
|
418 |
+
norm_fn = partial(norm_class, dim)
|
419 |
+
|
420 |
+
norm_fn = nn.Identity if use_rezero else norm_fn
|
421 |
+
branch_fn = Rezero if use_rezero else None
|
422 |
+
|
423 |
+
if cross_attend and not only_cross:
|
424 |
+
default_block = ('a', 'c', 'f')
|
425 |
+
elif cross_attend and only_cross:
|
426 |
+
default_block = ('c', 'f')
|
427 |
+
else:
|
428 |
+
default_block = ('a', 'f')
|
429 |
+
|
430 |
+
if macaron:
|
431 |
+
default_block = ('f',) + default_block
|
432 |
+
|
433 |
+
if exists(custom_layers):
|
434 |
+
layer_types = custom_layers
|
435 |
+
elif exists(par_ratio):
|
436 |
+
par_depth = depth * len(default_block)
|
437 |
+
assert 1 < par_ratio <= par_depth, 'par ratio out of range'
|
438 |
+
default_block = tuple(filter(not_equals('f'), default_block))
|
439 |
+
par_attn = par_depth // par_ratio
|
440 |
+
depth_cut = par_depth * 2 // 3 # 2 / 3 attention layer cutoff suggested by PAR paper
|
441 |
+
par_width = (depth_cut + depth_cut // par_attn) // par_attn
|
442 |
+
assert len(default_block) <= par_width, 'default block is too large for par_ratio'
|
443 |
+
par_block = default_block + ('f',) * (par_width - len(default_block))
|
444 |
+
par_head = par_block * par_attn
|
445 |
+
layer_types = par_head + ('f',) * (par_depth - len(par_head))
|
446 |
+
elif exists(sandwich_coef):
|
447 |
+
assert sandwich_coef > 0 and sandwich_coef <= depth, 'sandwich coefficient should be less than the depth'
|
448 |
+
layer_types = ('a',) * sandwich_coef + default_block * (depth - sandwich_coef) + ('f',) * sandwich_coef
|
449 |
+
else:
|
450 |
+
layer_types = default_block * depth
|
451 |
+
|
452 |
+
self.layer_types = layer_types
|
453 |
+
self.num_attn_layers = len(list(filter(equals('a'), layer_types)))
|
454 |
+
|
455 |
+
for layer_type in self.layer_types:
|
456 |
+
if layer_type == 'a':
|
457 |
+
layer = Attention(dim, heads=heads, causal=causal, **attn_kwargs)
|
458 |
+
elif layer_type == 'c':
|
459 |
+
layer = Attention(dim, heads=heads, **attn_kwargs)
|
460 |
+
elif layer_type == 'f':
|
461 |
+
layer = FeedForward(dim, **ff_kwargs)
|
462 |
+
layer = layer if not macaron else Scale(0.5, layer)
|
463 |
+
else:
|
464 |
+
raise Exception(f'invalid layer type {layer_type}')
|
465 |
+
|
466 |
+
if isinstance(layer, Attention) and exists(branch_fn):
|
467 |
+
layer = branch_fn(layer)
|
468 |
+
|
469 |
+
if gate_residual:
|
470 |
+
residual_fn = GRUGating(dim)
|
471 |
+
else:
|
472 |
+
residual_fn = Residual()
|
473 |
+
|
474 |
+
self.layers.append(nn.ModuleList([
|
475 |
+
norm_fn(),
|
476 |
+
layer,
|
477 |
+
residual_fn
|
478 |
+
]))
|
479 |
+
|
480 |
+
def forward(
|
481 |
+
self,
|
482 |
+
x,
|
483 |
+
context=None,
|
484 |
+
mask=None,
|
485 |
+
context_mask=None,
|
486 |
+
mems=None,
|
487 |
+
return_hiddens=False
|
488 |
+
):
|
489 |
+
hiddens = []
|
490 |
+
intermediates = []
|
491 |
+
prev_attn = None
|
492 |
+
prev_cross_attn = None
|
493 |
+
|
494 |
+
mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers
|
495 |
+
|
496 |
+
for ind, (layer_type, (norm, block, residual_fn)) in enumerate(zip(self.layer_types, self.layers)):
|
497 |
+
is_last = ind == (len(self.layers) - 1)
|
498 |
+
|
499 |
+
if layer_type == 'a':
|
500 |
+
hiddens.append(x)
|
501 |
+
layer_mem = mems.pop(0)
|
502 |
+
|
503 |
+
residual = x
|
504 |
+
|
505 |
+
if self.pre_norm:
|
506 |
+
x = norm(x)
|
507 |
+
|
508 |
+
if layer_type == 'a':
|
509 |
+
out, inter = block(x, mask=mask, sinusoidal_emb=self.pia_pos_emb, rel_pos=self.rel_pos,
|
510 |
+
prev_attn=prev_attn, mem=layer_mem)
|
511 |
+
elif layer_type == 'c':
|
512 |
+
out, inter = block(x, context=context, mask=mask, context_mask=context_mask, prev_attn=prev_cross_attn)
|
513 |
+
elif layer_type == 'f':
|
514 |
+
out = block(x)
|
515 |
+
|
516 |
+
x = residual_fn(out, residual)
|
517 |
+
|
518 |
+
if layer_type in ('a', 'c'):
|
519 |
+
intermediates.append(inter)
|
520 |
+
|
521 |
+
if layer_type == 'a' and self.residual_attn:
|
522 |
+
prev_attn = inter.pre_softmax_attn
|
523 |
+
elif layer_type == 'c' and self.cross_residual_attn:
|
524 |
+
prev_cross_attn = inter.pre_softmax_attn
|
525 |
+
|
526 |
+
if not self.pre_norm and not is_last:
|
527 |
+
x = norm(x)
|
528 |
+
|
529 |
+
if return_hiddens:
|
530 |
+
intermediates = LayerIntermediates(
|
531 |
+
hiddens=hiddens,
|
532 |
+
attn_intermediates=intermediates
|
533 |
+
)
|
534 |
+
|
535 |
+
return x, intermediates
|
536 |
+
|
537 |
+
return x
|
538 |
+
|
539 |
+
|
540 |
+
class Encoder(AttentionLayers):
|
541 |
+
def __init__(self, **kwargs):
|
542 |
+
assert 'causal' not in kwargs, 'cannot set causality on encoder'
|
543 |
+
super().__init__(causal=False, **kwargs)
|
544 |
+
|
545 |
+
|
546 |
+
|
547 |
+
class TransformerWrapper(nn.Module):
|
548 |
+
def __init__(
|
549 |
+
self,
|
550 |
+
*,
|
551 |
+
num_tokens,
|
552 |
+
max_seq_len,
|
553 |
+
attn_layers,
|
554 |
+
emb_dim=None,
|
555 |
+
max_mem_len=0.,
|
556 |
+
emb_dropout=0.,
|
557 |
+
num_memory_tokens=None,
|
558 |
+
tie_embedding=False,
|
559 |
+
use_pos_emb=True
|
560 |
+
):
|
561 |
+
super().__init__()
|
562 |
+
assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder'
|
563 |
+
|
564 |
+
dim = attn_layers.dim
|
565 |
+
emb_dim = default(emb_dim, dim)
|
566 |
+
|
567 |
+
self.max_seq_len = max_seq_len
|
568 |
+
self.max_mem_len = max_mem_len
|
569 |
+
self.num_tokens = num_tokens
|
570 |
+
|
571 |
+
self.token_emb = nn.Embedding(num_tokens, emb_dim)
|
572 |
+
self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) if (
|
573 |
+
use_pos_emb and not attn_layers.has_pos_emb) else always(0)
|
574 |
+
self.emb_dropout = nn.Dropout(emb_dropout)
|
575 |
+
|
576 |
+
self.project_emb = nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity()
|
577 |
+
self.attn_layers = attn_layers
|
578 |
+
self.norm = nn.LayerNorm(dim)
|
579 |
+
|
580 |
+
self.init_()
|
581 |
+
|
582 |
+
self.to_logits = nn.Linear(dim, num_tokens) if not tie_embedding else lambda t: t @ self.token_emb.weight.t()
|
583 |
+
|
584 |
+
# memory tokens (like [cls]) from Memory Transformers paper
|
585 |
+
num_memory_tokens = default(num_memory_tokens, 0)
|
586 |
+
self.num_memory_tokens = num_memory_tokens
|
587 |
+
if num_memory_tokens > 0:
|
588 |
+
self.memory_tokens = nn.Parameter(torch.randn(num_memory_tokens, dim))
|
589 |
+
|
590 |
+
# let funnel encoder know number of memory tokens, if specified
|
591 |
+
if hasattr(attn_layers, 'num_memory_tokens'):
|
592 |
+
attn_layers.num_memory_tokens = num_memory_tokens
|
593 |
+
|
594 |
+
def init_(self):
|
595 |
+
nn.init.normal_(self.token_emb.weight, std=0.02)
|
596 |
+
|
597 |
+
def forward(
|
598 |
+
self,
|
599 |
+
x,
|
600 |
+
return_embeddings=False,
|
601 |
+
mask=None,
|
602 |
+
return_mems=False,
|
603 |
+
return_attn=False,
|
604 |
+
mems=None,
|
605 |
+
**kwargs
|
606 |
+
):
|
607 |
+
b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens
|
608 |
+
x = self.token_emb(x)
|
609 |
+
x += self.pos_emb(x)
|
610 |
+
x = self.emb_dropout(x)
|
611 |
+
|
612 |
+
x = self.project_emb(x)
|
613 |
+
|
614 |
+
if num_mem > 0:
|
615 |
+
mem = repeat(self.memory_tokens, 'n d -> b n d', b=b)
|
616 |
+
x = torch.cat((mem, x), dim=1)
|
617 |
+
|
618 |
+
# auto-handle masking after appending memory tokens
|
619 |
+
if exists(mask):
|
620 |
+
mask = F.pad(mask, (num_mem, 0), value=True)
|
621 |
+
|
622 |
+
x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs)
|
623 |
+
x = self.norm(x)
|
624 |
+
|
625 |
+
mem, x = x[:, :num_mem], x[:, num_mem:]
|
626 |
+
|
627 |
+
out = self.to_logits(x) if not return_embeddings else x
|
628 |
+
|
629 |
+
if return_mems:
|
630 |
+
hiddens = intermediates.hiddens
|
631 |
+
new_mems = list(map(lambda pair: torch.cat(pair, dim=-2), zip(mems, hiddens))) if exists(mems) else hiddens
|
632 |
+
new_mems = list(map(lambda t: t[..., -self.max_mem_len:, :].detach(), new_mems))
|
633 |
+
return out, new_mems
|
634 |
+
|
635 |
+
if return_attn:
|
636 |
+
attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates))
|
637 |
+
return out, attn_maps
|
638 |
+
|
639 |
+
return out
|
640 |
+
|
VADER-VideoCrafter/readme.md
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
|
3 |
+
<!-- TITLE -->
|
4 |
+
# 🌟**VADER-VideoCrafter**
|
5 |
+
</div>
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
We **highly recommend** proceeding with the VADER-VideoCrafter model first, which performs better than the other two.
|
10 |
+
|
11 |
+
## ⚙️ Installation
|
12 |
+
Assuming you are in the `VADER/` directory, you are able to create a Conda environments for VADER-VideoCrafter using the following commands:
|
13 |
+
```bash
|
14 |
+
cd VADER-VideoCrafter
|
15 |
+
conda create -n vader_videocrafter python=3.10
|
16 |
+
conda activate vader_videocrafter
|
17 |
+
conda install pytorch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 pytorch-cuda=12.1 -c pytorch -c nvidia
|
18 |
+
conda install xformers -c xformers
|
19 |
+
pip install -r requirements.txt
|
20 |
+
git clone https://github.com/tgxs002/HPSv2.git
|
21 |
+
cd HPSv2/
|
22 |
+
pip install -e .
|
23 |
+
cd ..
|
24 |
+
```
|
25 |
+
|
26 |
+
|
27 |
+
- We are using the pretrained Text-to-Video [VideoCrafter2](https://huggingface.co/VideoCrafter/VideoCrafter2/blob/main/model.ckpt) model via Hugging Face. If you unfortunately find the model is not automatically downloaded when you running inference or training script, you can manually download it and put the `model.ckpt` in `VADER/VADER-VideoCrafter/checkpoints/base_512_v2/model.ckpt`.
|
28 |
+
|
29 |
+
|
30 |
+
## 📺 Inference
|
31 |
+
Please run `accelerate config` as the first step to configure accelerator settings. If you are not familiar with the accelerator configuration, you can refer to VADER-VideoCrafter [documentation](../documentation/VADER-VideoCrafter.md).
|
32 |
+
|
33 |
+
Assuming you are in the `VADER/` directory, you are able to do inference using the following commands:
|
34 |
+
```bash
|
35 |
+
cd VADER-VideoCrafter
|
36 |
+
sh scripts/run_text2video_inference.sh
|
37 |
+
```
|
38 |
+
- We have tested on PyTorch 2.3.0 and CUDA 12.1. The inferece script works on a single GPU with 16GBs VRAM, when we set `val_batch_size=1` and use `fp16` mixed precision. It should also work with recent PyTorch and CUDA versions.
|
39 |
+
- `VADER/VADER-VideoCrafter/scripts/main/train_t2v_lora.py` is a script for inference of the VideoCrafter2 using VADER via LoRA.
|
40 |
+
- Most of the arguments are the same as the training process. The main difference is that `--inference_only` should be set to `True`.
|
41 |
+
- `--lora_ckpt_path` is required to set to the path of the pretrained LoRA model. Otherwise, the original VideoCrafter model will be used for inference.
|
42 |
+
|
43 |
+
## 🔧 Training
|
44 |
+
Please run `accelerate config` as the first step to configure accelerator settings. If you are not familiar with the accelerator configuration, you can refer to VADER-VideoCrafter [documentation](../documentation/VADER-VideoCrafter.md).
|
45 |
+
|
46 |
+
Assuming you are in the `VADER/` directory, you are able to train the model using the following commands:
|
47 |
+
|
48 |
+
```bash
|
49 |
+
cd VADER-VideoCrafter
|
50 |
+
sh scripts/run_text2video_train.sh
|
51 |
+
```
|
52 |
+
- Our experiments are conducted on PyTorch 2.3.0 and CUDA 12.1 while using 4 A6000s (48GB RAM). It should also work with recent PyTorch and CUDA versions. The training script have been tested on a single GPU with 16GBs VRAM, when we set `train_batch_size=1 val_batch_size=1` and use `fp16` mixed precision.
|
53 |
+
- `VADER/VADER-VideoCrafter/scripts/main/train_t2v_lora.py` is also a script for fine-tuning the VideoCrafter2 using VADER via LoRA.
|
54 |
+
- You can read the VADER-VideoCrafter [documentation](../documentation/VADER-VideoCrafter.md) to understand the usage of arguments.
|
55 |
+
|
56 |
+
## 💡 Tutorial
|
57 |
+
This section is to provide a tutorial on how to implement the VADER method on VideoCrafter by yourself. We will provide a step-by-step guide to help you understand the implementation details. Thus, you can easily adapt the VADER method to later versions of VideCrafter. This tutorial is based on the VideoCrafter2.
|
58 |
+
|
59 |
+
### Step 1: Install the dependencies
|
60 |
+
First, you need to install the dependencies according to the [VideoCrafter](https://github.com/AILab-CVC/VideoCrafter) repository. You can also follow the instructions in the repository to install the dependencies.
|
61 |
+
```bash
|
62 |
+
conda create -n vader_videocrafter python=3.8.5
|
63 |
+
conda activate vader_videocrafter
|
64 |
+
pip install -r requirements.txt
|
65 |
+
```
|
66 |
+
|
67 |
+
You have to download pretrained Text-to-Video [VideoCrafter2](https://huggingface.co/VideoCrafter/VideoCrafter2/blob/main/model.ckpt) model via Hugging Face, and put the `model.ckpt` in the downloaded VideoCrafter directionary as `VideoCrafter/checkpoints/base_512_v2/model.ckpt`.
|
68 |
+
|
69 |
+
There are a list of extra dependencies that you need to install for VADER. You can install them by running the following command.
|
70 |
+
```bash
|
71 |
+
# Install the HPS
|
72 |
+
git clone https://github.com/tgxs002/HPSv2.git
|
73 |
+
cd HPSv2/
|
74 |
+
pip install -e .
|
75 |
+
cd ..
|
76 |
+
|
77 |
+
# Install the dependencies
|
78 |
+
pip install albumentations \
|
79 |
+
peft \
|
80 |
+
bitsandbytes \
|
81 |
+
accelerate \
|
82 |
+
inflect \
|
83 |
+
wandb \
|
84 |
+
ipdb \
|
85 |
+
pytorch_lightning
|
86 |
+
```
|
87 |
+
|
88 |
+
### Step 2: Transfer VADER scripts
|
89 |
+
You can copy our `VADER/VADER-VideoCrafter/scripts/main/train_t2v_lora.py` to the `VideoCrafter/scripts/evaluation/` directory of VideoCrafter. It is better to copy our `run_text2video_train.sh` and `run_text2video_inference.sh` to the directionary `VideoCrafter/scripts/` as well. Then, you need to copy All the files in `VADER/Core/` and `VADER/assets/` to the parent directory of VideoCrafter, which means `Core/`, `assets` and `VideoCrafter/` should be in the same directory. Now, you may have a directory structure like:
|
90 |
+
```bash
|
91 |
+
.
|
92 |
+
├── Core
|
93 |
+
│ ├── ...
|
94 |
+
├── VideoCrafter
|
95 |
+
│ ├── scripts
|
96 |
+
│ │ ├── evaluation
|
97 |
+
│ │ │ ├── train_t2v_lora.py
|
98 |
+
│ │ ├── run_text2video_train.sh
|
99 |
+
│ │ ├── run_text2video_inference.sh
|
100 |
+
│ ├── checkpoints
|
101 |
+
│ │ ├── base_512_v2
|
102 |
+
│ │ │ ├── model.ckpt
|
103 |
+
├── assets
|
104 |
+
│ ├── ...
|
105 |
+
```
|
106 |
+
|
107 |
+
### Step 3: Modify the VideoCrafter code
|
108 |
+
You need to modify the VideoCrafter code to adapt the VADER method. You can follow the instructions below to modify the code.
|
109 |
+
|
110 |
+
- Modify the `batch_ddim_sampling()` function in `VideoCrafter/scripts/evaluation/funcs.py` as our implementation in `VADER/VADER-VideoCrafter/scripts/main/funcs.py`.
|
111 |
+
- Modify the `DDIMSampler.__init__()`, `DDIMSampler.sample()` and `DDIMSampler.ddim_sampling` functions in `VideoCrafter\lvdm\models\samplers\ddim.py` as our implementation in `VADER/VADER-VideoCrafter\lvdm\models\samplers\ddim.py`.
|
112 |
+
- Comment out the `@torch.no_grad()` before `DDIMSampler.sample()`, `DDIMSampler.ddim_sampling`, and `DDIMSampler.p_sample_ddim()` in `VideoCrafter\lvdm\models\samplers\ddim.py`. Also, comment out the `@torch.no_grad()` before `LatentDiffusion.decode_first_stage_2DAE()` in `VideoCrafter\lvdm\models\ddpm3d.py`.
|
113 |
+
- Because we have commented out the `@torch.no_grad()`, you can add `with torch.no_grad():` at some places in `VideoCrater/scripts/evaluation/inference.py` to avoid the gradient calculation.
|
114 |
+
|
115 |
+
### Step 4: Ready to Train
|
116 |
+
Now you have all the files in the right place and modified the VideoCrafter source code. You can run the training script by running the following command.
|
117 |
+
```bash
|
118 |
+
cd VideoCrafter
|
119 |
+
|
120 |
+
# training
|
121 |
+
sh scripts/run_text2video_train.sh
|
122 |
+
|
123 |
+
# or inference
|
124 |
+
sh scripts/run_text2video_inference.sh
|
125 |
+
```
|
126 |
+
|
127 |
+
|
128 |
+
## Acknowledgement
|
129 |
+
|
130 |
+
Our codebase is directly built on top of [VideoCrafter](https://github.com/AILab-CVC/VideoCrafter), [Open-Sora](https://github.com/hpcaitech/Open-Sora), and [Animate Anything](https://github.com/alibaba/animate-anything/). We would like to thank the authors for open-sourcing their code.
|
131 |
+
|
132 |
+
## Citation
|
133 |
+
|
134 |
+
If you find this work useful in your research, please cite:
|
135 |
+
|
136 |
+
```bibtex
|
137 |
+
|
138 |
+
```
|
VADER-VideoCrafter/requirements.txt
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
decord==0.6.0
|
2 |
+
einops==0.3.0
|
3 |
+
imageio==2.9.0
|
4 |
+
numpy==1.24.2
|
5 |
+
omegaconf==2.1.1
|
6 |
+
opencv_python
|
7 |
+
pandas==2.0.0
|
8 |
+
Pillow==9.5.0
|
9 |
+
pytorch_lightning==2.3.1
|
10 |
+
PyYAML==6.0
|
11 |
+
setuptools==65.6.3
|
12 |
+
tqdm==4.65.0
|
13 |
+
transformers==4.25.1
|
14 |
+
moviepy==1.0.3
|
15 |
+
av==12.2.0
|
16 |
+
gradio
|
17 |
+
timm==1.0.7
|
18 |
+
scikit-learn==1.5.0
|
19 |
+
open_clip_torch==2.22.0
|
20 |
+
kornia==0.7.3
|
21 |
+
albumentations==1.3.1
|
22 |
+
peft==0.11.1
|
23 |
+
bitsandbytes==0.42.0
|
24 |
+
accelerate==0.31.0
|
25 |
+
inflect==7.3.0
|
26 |
+
wandb==0.17.3
|
27 |
+
ipdb==0.13.13
|
28 |
+
huggingface-hub==0.23.4
|
VADER-VideoCrafter/scripts/main/ddp_wrapper.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copied from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import datetime
|
3 |
+
import argparse, importlib
|
4 |
+
from pytorch_lightning import seed_everything
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.distributed as dist
|
8 |
+
|
9 |
+
def setup_dist(local_rank):
|
10 |
+
if dist.is_initialized():
|
11 |
+
return
|
12 |
+
torch.cuda.set_device(local_rank)
|
13 |
+
torch.distributed.init_process_group('nccl', init_method='env://')
|
14 |
+
|
15 |
+
|
16 |
+
def get_dist_info():
|
17 |
+
if dist.is_available():
|
18 |
+
initialized = dist.is_initialized()
|
19 |
+
else:
|
20 |
+
initialized = False
|
21 |
+
if initialized:
|
22 |
+
rank = dist.get_rank()
|
23 |
+
world_size = dist.get_world_size()
|
24 |
+
else:
|
25 |
+
rank = 0
|
26 |
+
world_size = 1
|
27 |
+
return rank, world_size
|
28 |
+
|
29 |
+
|
30 |
+
if __name__ == '__main__':
|
31 |
+
now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
|
32 |
+
parser = argparse.ArgumentParser()
|
33 |
+
parser.add_argument("--module", type=str, help="module name", default="inference")
|
34 |
+
parser.add_argument("--local_rank", type=int, nargs="?", help="for ddp", default=0)
|
35 |
+
args, unknown = parser.parse_known_args()
|
36 |
+
inference_api = importlib.import_module(args.module, package=None)
|
37 |
+
|
38 |
+
inference_parser = inference_api.get_parser()
|
39 |
+
inference_args, unknown = inference_parser.parse_known_args()
|
40 |
+
|
41 |
+
seed_everything(inference_args.seed)
|
42 |
+
setup_dist(args.local_rank)
|
43 |
+
torch.backends.cudnn.benchmark = True
|
44 |
+
rank, gpu_num = get_dist_info()
|
45 |
+
|
46 |
+
print("@CoLVDM Inference [rank%d]: %s"%(rank, now))
|
47 |
+
inference_api.run_inference(inference_args, gpu_num, rank)
|
VADER-VideoCrafter/scripts/main/funcs.py
ADDED
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from VideoCrafter: https://github.com/AILab-CVC/VideoCrafter
|
2 |
+
import os, sys, glob
|
3 |
+
import numpy as np
|
4 |
+
from collections import OrderedDict
|
5 |
+
from decord import VideoReader, cpu
|
6 |
+
import cv2
|
7 |
+
import random
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torchvision
|
11 |
+
sys.path.insert(1, os.path.join(sys.path[0], '..', '..'))
|
12 |
+
from lvdm.models.samplers.ddim import DDIMSampler
|
13 |
+
# import ipdb
|
14 |
+
# st = ipdb.set_trace
|
15 |
+
|
16 |
+
def batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1.0,\
|
17 |
+
cfg_scale=1.0, temporal_cfg_scale=None, backprop_mode=None, decode_frame='-1', **kwargs):
|
18 |
+
ddim_sampler = DDIMSampler(model)
|
19 |
+
if backprop_mode is not None: # it is for training now, backprop_mode != None also means vader training mode
|
20 |
+
ddim_sampler.backprop_mode = backprop_mode
|
21 |
+
ddim_sampler.training_mode = True
|
22 |
+
uncond_type = model.uncond_type
|
23 |
+
batch_size = noise_shape[0]
|
24 |
+
|
25 |
+
## construct unconditional guidance
|
26 |
+
if cfg_scale != 1.0:
|
27 |
+
if uncond_type == "empty_seq":
|
28 |
+
prompts = batch_size * [""]
|
29 |
+
|
30 |
+
uc_emb = model.get_learned_conditioning(prompts)
|
31 |
+
elif uncond_type == "zero_embed":
|
32 |
+
c_emb = cond["c_crossattn"][0] if isinstance(cond, dict) else cond
|
33 |
+
uc_emb = torch.zeros_like(c_emb)
|
34 |
+
|
35 |
+
## process image embedding token
|
36 |
+
if hasattr(model, 'embedder'):
|
37 |
+
uc_img = torch.zeros(noise_shape[0],3,224,224).to(model.device)
|
38 |
+
## img: b c h w >> b l c
|
39 |
+
uc_img = model.get_image_embeds(uc_img)
|
40 |
+
uc_emb = torch.cat([uc_emb, uc_img], dim=1)
|
41 |
+
|
42 |
+
if isinstance(cond, dict):
|
43 |
+
uc = {key:cond[key] for key in cond.keys()}
|
44 |
+
uc.update({'c_crossattn': [uc_emb]})
|
45 |
+
else:
|
46 |
+
uc = uc_emb
|
47 |
+
else:
|
48 |
+
uc = None
|
49 |
+
|
50 |
+
x_T = None
|
51 |
+
batch_variants = []
|
52 |
+
|
53 |
+
for _ in range(n_samples):
|
54 |
+
if ddim_sampler is not None:
|
55 |
+
kwargs.update({"clean_cond": True})
|
56 |
+
samples, _ = ddim_sampler.sample(S=ddim_steps, # samples: batch, c, t, h, w
|
57 |
+
conditioning=cond,
|
58 |
+
batch_size=noise_shape[0],
|
59 |
+
shape=noise_shape[1:],
|
60 |
+
verbose=False,
|
61 |
+
unconditional_guidance_scale=cfg_scale,
|
62 |
+
unconditional_conditioning=uc,
|
63 |
+
eta=ddim_eta,
|
64 |
+
temporal_length=noise_shape[2],
|
65 |
+
conditional_guidance_scale_temporal=temporal_cfg_scale,
|
66 |
+
x_T=x_T,
|
67 |
+
**kwargs
|
68 |
+
)
|
69 |
+
|
70 |
+
## reconstruct from latent to pixel space
|
71 |
+
if backprop_mode is not None: # it is for training now. Use one frame randomly to save memory
|
72 |
+
try:
|
73 |
+
decode_frame=int(decode_frame)
|
74 |
+
#it's a int
|
75 |
+
except:
|
76 |
+
pass
|
77 |
+
if type(decode_frame) == int:
|
78 |
+
frame_index = random.randint(0,samples.shape[2]-1) if decode_frame == -1 else decode_frame # samples: batch, c, t, h, w
|
79 |
+
batch_images = model.decode_first_stage_2DAE(samples[:,:,frame_index:frame_index+1,:,:])
|
80 |
+
elif decode_frame in ['alt', 'all']:
|
81 |
+
idxs = range(0, samples.shape[2], 2) if decode_frame == 'alt' else range(samples.shape[2])
|
82 |
+
batch_images = model.decode_first_stage_2DAE(samples[:,:,idxs,:,:])
|
83 |
+
|
84 |
+
|
85 |
+
else: # inference mode
|
86 |
+
batch_images = model.decode_first_stage_2DAE(samples)
|
87 |
+
batch_variants.append(batch_images)
|
88 |
+
|
89 |
+
## batch, <samples>, c, t, h, w
|
90 |
+
batch_variants = torch.stack(batch_variants, dim=1)
|
91 |
+
return batch_variants
|
92 |
+
|
93 |
+
|
94 |
+
def get_filelist(data_dir, ext='*'):
|
95 |
+
file_list = glob.glob(os.path.join(data_dir, '*.%s'%ext))
|
96 |
+
file_list.sort()
|
97 |
+
return file_list
|
98 |
+
|
99 |
+
def get_dirlist(path):
|
100 |
+
list = []
|
101 |
+
if (os.path.exists(path)):
|
102 |
+
files = os.listdir(path)
|
103 |
+
for file in files:
|
104 |
+
m = os.path.join(path,file)
|
105 |
+
if (os.path.isdir(m)):
|
106 |
+
list.append(m)
|
107 |
+
list.sort()
|
108 |
+
return list
|
109 |
+
|
110 |
+
|
111 |
+
def load_model_checkpoint(model, ckpt):
|
112 |
+
def load_checkpoint(model, ckpt, full_strict):
|
113 |
+
state_dict = torch.load(ckpt, map_location="cpu")
|
114 |
+
try:
|
115 |
+
## deepspeed
|
116 |
+
new_pl_sd = OrderedDict()
|
117 |
+
for key in state_dict['module'].keys():
|
118 |
+
new_pl_sd[key[16:]]=state_dict['module'][key]
|
119 |
+
model.load_state_dict(new_pl_sd, strict=full_strict)
|
120 |
+
except:
|
121 |
+
if "state_dict" in list(state_dict.keys()):
|
122 |
+
state_dict = state_dict["state_dict"]
|
123 |
+
model.load_state_dict(state_dict, strict=full_strict)
|
124 |
+
return model
|
125 |
+
load_checkpoint(model, ckpt, full_strict=True)
|
126 |
+
print('>>> model checkpoint loaded.')
|
127 |
+
return model
|
128 |
+
|
129 |
+
|
130 |
+
def load_prompts(prompt_file):
|
131 |
+
f = open(prompt_file, 'r')
|
132 |
+
prompt_list = []
|
133 |
+
for idx, line in enumerate(f.readlines()):
|
134 |
+
l = line.strip()
|
135 |
+
if len(l) != 0:
|
136 |
+
prompt_list.append(l)
|
137 |
+
f.close()
|
138 |
+
return prompt_list
|
139 |
+
|
140 |
+
|
141 |
+
def load_video_batch(filepath_list, frame_stride, video_size=(256,256), video_frames=16):
|
142 |
+
'''
|
143 |
+
Notice about some special cases:
|
144 |
+
1. video_frames=-1 means to take all the frames (with fs=1)
|
145 |
+
2. when the total video frames is less than required, padding strategy will be used (repreated last frame)
|
146 |
+
'''
|
147 |
+
fps_list = []
|
148 |
+
batch_tensor = []
|
149 |
+
assert frame_stride > 0, "valid frame stride should be a positive interge!"
|
150 |
+
for filepath in filepath_list:
|
151 |
+
padding_num = 0
|
152 |
+
vidreader = VideoReader(filepath, ctx=cpu(0), width=video_size[1], height=video_size[0])
|
153 |
+
fps = vidreader.get_avg_fps()
|
154 |
+
total_frames = len(vidreader)
|
155 |
+
max_valid_frames = (total_frames-1) // frame_stride + 1
|
156 |
+
if video_frames < 0:
|
157 |
+
## all frames are collected: fs=1 is a must
|
158 |
+
required_frames = total_frames
|
159 |
+
frame_stride = 1
|
160 |
+
else:
|
161 |
+
required_frames = video_frames
|
162 |
+
query_frames = min(required_frames, max_valid_frames)
|
163 |
+
frame_indices = [frame_stride*i for i in range(query_frames)]
|
164 |
+
|
165 |
+
## [t,h,w,c] -> [c,t,h,w]
|
166 |
+
frames = vidreader.get_batch(frame_indices)
|
167 |
+
frame_tensor = torch.tensor(frames.asnumpy()).permute(3, 0, 1, 2).float()
|
168 |
+
frame_tensor = (frame_tensor / 255. - 0.5) * 2
|
169 |
+
if max_valid_frames < required_frames:
|
170 |
+
padding_num = required_frames - max_valid_frames
|
171 |
+
frame_tensor = torch.cat([frame_tensor, *([frame_tensor[:,-1:,:,:]]*padding_num)], dim=1)
|
172 |
+
print(f'{os.path.split(filepath)[1]} is not long enough: {padding_num} frames padded.')
|
173 |
+
batch_tensor.append(frame_tensor)
|
174 |
+
sample_fps = int(fps/frame_stride)
|
175 |
+
fps_list.append(sample_fps)
|
176 |
+
|
177 |
+
return torch.stack(batch_tensor, dim=0)
|
178 |
+
|
179 |
+
from PIL import Image
|
180 |
+
def load_image_batch(filepath_list, image_size=(256,256)):
|
181 |
+
batch_tensor = []
|
182 |
+
for filepath in filepath_list:
|
183 |
+
_, filename = os.path.split(filepath)
|
184 |
+
_, ext = os.path.splitext(filename)
|
185 |
+
if ext == '.mp4':
|
186 |
+
vidreader = VideoReader(filepath, ctx=cpu(0), width=image_size[1], height=image_size[0])
|
187 |
+
frame = vidreader.get_batch([0])
|
188 |
+
img_tensor = torch.tensor(frame.asnumpy()).squeeze(0).permute(2, 0, 1).float()
|
189 |
+
elif ext == '.png' or ext == '.jpg':
|
190 |
+
img = Image.open(filepath).convert("RGB")
|
191 |
+
rgb_img = np.array(img, np.float32)
|
192 |
+
#bgr_img = cv2.imread(filepath, cv2.IMREAD_COLOR)
|
193 |
+
#bgr_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
|
194 |
+
rgb_img = cv2.resize(rgb_img, (image_size[1],image_size[0]), interpolation=cv2.INTER_LINEAR)
|
195 |
+
img_tensor = torch.from_numpy(rgb_img).permute(2, 0, 1).float()
|
196 |
+
else:
|
197 |
+
print(f'ERROR: <{ext}> image loading only support format: [mp4], [png], [jpg]')
|
198 |
+
raise NotImplementedError
|
199 |
+
img_tensor = (img_tensor / 255. - 0.5) * 2
|
200 |
+
batch_tensor.append(img_tensor)
|
201 |
+
return torch.stack(batch_tensor, dim=0)
|
202 |
+
|
203 |
+
|
204 |
+
def save_videos(batch_tensors, savedir, filenames, fps=10):
|
205 |
+
# b,samples,c,t,h,w
|
206 |
+
n_samples = batch_tensors.shape[1]
|
207 |
+
for idx, vid_tensor in enumerate(batch_tensors):
|
208 |
+
video = vid_tensor.detach().cpu()
|
209 |
+
video = torch.clamp(video.float(), -1., 1.)
|
210 |
+
video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w
|
211 |
+
frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n_samples)) for framesheet in video] #[3, 1*h, n*w]
|
212 |
+
grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w]
|
213 |
+
grid = (grid + 1.0) / 2.0
|
214 |
+
grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1)
|
215 |
+
savepath = os.path.join(savedir, f"{filenames[idx]}.mp4")
|
216 |
+
torchvision.io.write_video(savepath, grid, fps=fps, video_codec='h264', options={'crf': '10'})
|
217 |
+
|
218 |
+
def get_videos(batch_tensors, fps=10):
|
219 |
+
# b,samples,c,t,h,w
|
220 |
+
n_samples = batch_tensors.shape[1]
|
221 |
+
vid_tensor = batch_tensors[0]
|
222 |
+
video = vid_tensor.detach().cpu()
|
223 |
+
video = torch.clamp(video.float(), -1., 1.)
|
224 |
+
video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w
|
225 |
+
frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n_samples)) for framesheet in video] #[3, 1*h, n*w]
|
226 |
+
grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w]
|
227 |
+
grid = (grid + 1.0) / 2.0
|
228 |
+
grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1)
|
229 |
+
|
230 |
+
return grid
|
231 |
+
|
VADER-VideoCrafter/scripts/main/train_t2v_lora.py
ADDED
@@ -0,0 +1,817 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse, os, sys, glob, yaml, math, random
|
2 |
+
sys.path.append('../') # setting path to get Core and assets
|
3 |
+
|
4 |
+
import datetime, time
|
5 |
+
import numpy as np
|
6 |
+
from omegaconf import OmegaConf
|
7 |
+
from collections import OrderedDict
|
8 |
+
from tqdm import trange, tqdm
|
9 |
+
from einops import repeat
|
10 |
+
from einops import rearrange, repeat
|
11 |
+
from functools import partial
|
12 |
+
import torch
|
13 |
+
from pytorch_lightning import seed_everything
|
14 |
+
|
15 |
+
from funcs import load_model_checkpoint, load_prompts, load_image_batch, get_filelist, save_videos, get_videos
|
16 |
+
from funcs import batch_ddim_sampling
|
17 |
+
from utils.utils import instantiate_from_config
|
18 |
+
|
19 |
+
import peft
|
20 |
+
import torchvision
|
21 |
+
from transformers.utils import ContextManagers
|
22 |
+
from transformers import AutoProcessor, AutoModel, AutoImageProcessor, AutoModelForObjectDetection, AutoModelForZeroShotObjectDetection
|
23 |
+
from Core.aesthetic_scorer import AestheticScorerDiff
|
24 |
+
from Core.actpred_scorer import ActPredScorer
|
25 |
+
from Core.weather_scorer import WeatherScorer
|
26 |
+
from Core.compression_scorer import JpegCompressionScorer, jpeg_compressibility
|
27 |
+
import Core.prompts as prompts_file
|
28 |
+
from hpsv2.src.open_clip import create_model_and_transforms, get_tokenizer
|
29 |
+
import hpsv2
|
30 |
+
import bitsandbytes as bnb
|
31 |
+
from accelerate import Accelerator
|
32 |
+
from accelerate.logging import get_logger
|
33 |
+
from accelerate.utils import gather_object
|
34 |
+
import torch.distributed as dist
|
35 |
+
import logging
|
36 |
+
import gc
|
37 |
+
from PIL import Image
|
38 |
+
import io
|
39 |
+
import albumentations as A
|
40 |
+
from huggingface_hub import snapshot_download
|
41 |
+
import cv2
|
42 |
+
# import ipdb
|
43 |
+
# st = ipdb.set_trace
|
44 |
+
|
45 |
+
|
46 |
+
logger = get_logger(__name__, log_level="INFO") # get logger for current module
|
47 |
+
|
48 |
+
def create_logging(logging, logger, accelerator):
|
49 |
+
logging.basicConfig(
|
50 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
51 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
52 |
+
level=logging.INFO,
|
53 |
+
)
|
54 |
+
logger.info(accelerator.state, main_process_only=False)
|
55 |
+
|
56 |
+
def create_output_folders(output_dir, run_name):
|
57 |
+
out_dir = os.path.join(output_dir, run_name)
|
58 |
+
os.makedirs(out_dir, exist_ok=True)
|
59 |
+
os.makedirs(f"{out_dir}/samples", exist_ok=True)
|
60 |
+
return out_dir
|
61 |
+
|
62 |
+
def str2bool(v):
|
63 |
+
if isinstance(v, bool):
|
64 |
+
return v
|
65 |
+
if v.lower() in ('yes', 'true', 't', 'y', '1'):
|
66 |
+
return True
|
67 |
+
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
|
68 |
+
return False
|
69 |
+
else:
|
70 |
+
raise argparse.ArgumentTypeError('Boolean value expected.')
|
71 |
+
|
72 |
+
def get_parser():
|
73 |
+
parser = argparse.ArgumentParser()
|
74 |
+
parser.add_argument("--seed", type=int, default=20230211, help="seed for seed_everything")
|
75 |
+
parser.add_argument("--mode", default="base", type=str, help="which kind of inference mode: {'base', 'i2v'}")
|
76 |
+
parser.add_argument("--ckpt_path", type=str, default='VADER-VideoCrafter/checkpoints/base_512_v2/model.ckpt', help="checkpoint path")
|
77 |
+
parser.add_argument("--config", type=str, default='VADER-VideoCrafter/configs/inference_t2v_512_v2.0.yaml', help="config (yaml) path")
|
78 |
+
parser.add_argument("--savefps", type=str, default=10, help="video fps to generate")
|
79 |
+
parser.add_argument("--n_samples", type=int, default=1, help="num of samples per prompt",)
|
80 |
+
parser.add_argument("--ddim_steps", type=int, default=50, help="steps of ddim if positive, otherwise use DDPM",)
|
81 |
+
parser.add_argument("--ddim_eta", type=float, default=1.0, help="eta for ddim sampling (0.0 yields deterministic sampling)",)
|
82 |
+
parser.add_argument("--height", type=int, default=512, help="image height, in pixel space")
|
83 |
+
parser.add_argument("--width", type=int, default=512, help="image width, in pixel space")
|
84 |
+
parser.add_argument("--frames", type=int, default=-1, help="frames num to inference")
|
85 |
+
parser.add_argument("--fps", type=int, default=24)
|
86 |
+
parser.add_argument("--unconditional_guidance_scale", type=float, default=1.0, help="prompt classifier-free guidance")
|
87 |
+
parser.add_argument("--unconditional_guidance_scale_temporal", type=float, default=None, help="temporal consistency guidance")
|
88 |
+
## for conditional i2v only
|
89 |
+
parser.add_argument("--cond_input", type=str, default=None, help="data dir of conditional input")
|
90 |
+
## for training
|
91 |
+
parser.add_argument("--lr", type=float, default=2e-4, help="learning rate")
|
92 |
+
parser.add_argument("--val_batch_size", type=int, default=1, help="batch size for validation")
|
93 |
+
parser.add_argument("--num_val_runs", type=int, default=1, help="total number of validation samples = num_val_runs * num_gpus * num_val_batch")
|
94 |
+
parser.add_argument("--train_batch_size", type=int, default=1, help="batch size for training")
|
95 |
+
parser.add_argument("--reward_fn", type=str, default="aesthetic", help="reward function: 'aesthetic', 'hps', 'aesthetic_hps', 'pick_score', 'rainy', 'snowy', 'objectDetection', 'actpred', 'compression'")
|
96 |
+
parser.add_argument("--compression_model_path", type=str, default='assets/compression_reward.pt', help="compression model path") # The compression model is used only when reward_fn is 'compression'
|
97 |
+
# The "book." is for grounding-dino model . Remember to add "." at the end of the object name for grounding-dino model.
|
98 |
+
# But for yolos model, do not add "." at the end of the object name. Instead, you should set the object name to "book" for example.
|
99 |
+
parser.add_argument("--target_object", type=str, default="book", help="target object for object detection reward function")
|
100 |
+
parser.add_argument("--detector_model", type=str, default="yolos-base", help="object detection model",
|
101 |
+
choices=["yolos-base", "yolos-tiny", "grounding-dino-base", "grounding-dino-tiny"])
|
102 |
+
parser.add_argument("--hps_version", type=str, default="v2.1", help="hps version: 'v2.0', 'v2.1'")
|
103 |
+
parser.add_argument("--prompt_fn", type=str, default="hps_custom", help="prompt function")
|
104 |
+
parser.add_argument("--nouns_file", type=str, default="simple_animals.txt", help="nouns file")
|
105 |
+
parser.add_argument("--activities_file", type=str, default="activities.txt", help="activities file")
|
106 |
+
parser.add_argument("--num_train_epochs", type=int, default=200, help="number of training epochs")
|
107 |
+
parser.add_argument("--max_train_steps", type=int, default=10000, help="max training steps")
|
108 |
+
parser.add_argument("--backprop_mode", type=str, default="last", help="backpropagation mode: 'last', 'rand', 'specific'") # backprop_mode != None also means training mode for batch_ddim_sampling
|
109 |
+
parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="gradient accumulation steps")
|
110 |
+
parser.add_argument("--mixed_precision", type=str, default='fp16', help="mixed precision training: 'no', 'fp8', 'fp16', 'bf16'")
|
111 |
+
parser.add_argument("--project_dir", type=str, default="VADER-VideoCrafter/project_dir", help="project directory")
|
112 |
+
parser.add_argument("--validation_steps", type=int, default=1, help="The frequency of validation, e.g., 1 means validate every 1*accelerator.num_processes steps")
|
113 |
+
parser.add_argument("--checkpointing_steps", type=int, default=1, help="The frequency of checkpointing")
|
114 |
+
parser.add_argument("--wandb_entity", type=str, default="", help="wandb entity")
|
115 |
+
parser.add_argument("--debug", type=str2bool, default=False, help="debug mode")
|
116 |
+
parser.add_argument("--max_grad_norm", type=float, default=1.0, help="max gradient norm")
|
117 |
+
parser.add_argument("--use_AdamW8bit", type=str2bool, default=False, help="use AdamW8bit optimizer")
|
118 |
+
parser.add_argument("--is_sample_preview", type=str2bool, default=True, help="sample preview during training")
|
119 |
+
parser.add_argument("--decode_frame", type=str, default="-1", help="decode frame: '-1', 'fml', 'all', 'alt'") # it could also be any number str like '3', '10'. alt: alternate frames, fml: first, middle, last frames, all: all frames. '-1': random frame
|
120 |
+
parser.add_argument("--inference_only", type=str2bool, default=True, help="only do inference")
|
121 |
+
parser.add_argument("--lora_ckpt_path", type=str, default=None, help="LoRA checkpoint path")
|
122 |
+
parser.add_argument("--lora_rank", type=int, default=16, help="LoRA rank")
|
123 |
+
|
124 |
+
return parser
|
125 |
+
|
126 |
+
|
127 |
+
def aesthetic_loss_fn(aesthetic_target=None,
|
128 |
+
grad_scale=0,
|
129 |
+
device=None,
|
130 |
+
torch_dtype=None):
|
131 |
+
'''
|
132 |
+
Args:
|
133 |
+
aesthetic_target: float, the target value of the aesthetic score. it is 10 in this experiment
|
134 |
+
grad_scale: float, the scale of the gradient. it is 0.1 in this experiment
|
135 |
+
device: torch.device, the device to run the model.
|
136 |
+
torch_dtype: torch.dtype, the data type of the model.
|
137 |
+
|
138 |
+
Returns:
|
139 |
+
loss_fn: function, the loss function of the aesthetic reward function.
|
140 |
+
'''
|
141 |
+
target_size = (224, 224)
|
142 |
+
normalize = torchvision.transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
|
143 |
+
std=[0.26862954, 0.26130258, 0.27577711])
|
144 |
+
|
145 |
+
scorer = AestheticScorerDiff(dtype=torch_dtype).to(device, dtype=torch_dtype)
|
146 |
+
scorer.requires_grad_(False)
|
147 |
+
|
148 |
+
def loss_fn(im_pix_un):
|
149 |
+
im_pix = ((im_pix_un / 2) + 0.5).clamp(0, 1)
|
150 |
+
im_pix = torchvision.transforms.Resize(target_size)(im_pix)
|
151 |
+
im_pix = normalize(im_pix).to(im_pix_un.dtype)
|
152 |
+
rewards = scorer(im_pix)
|
153 |
+
if aesthetic_target is None: # default maximization
|
154 |
+
loss = -1 * rewards
|
155 |
+
else:
|
156 |
+
# using L1 to keep on same scale
|
157 |
+
loss = abs(rewards - aesthetic_target)
|
158 |
+
return loss.mean() * grad_scale, rewards.mean()
|
159 |
+
return loss_fn
|
160 |
+
|
161 |
+
|
162 |
+
def hps_loss_fn(inference_dtype=None, device=None, hps_version="v2.0"):
|
163 |
+
'''
|
164 |
+
Args:
|
165 |
+
inference_dtype: torch.dtype, the data type of the model.
|
166 |
+
device: torch.device, the device to run the model.
|
167 |
+
hps_version: str, the version of the HPS model. It is "v2.0" or "v2.1" in this experiment.
|
168 |
+
|
169 |
+
Returns:
|
170 |
+
loss_fn: function, the loss function of the HPS reward function.
|
171 |
+
'''
|
172 |
+
model_name = "ViT-H-14"
|
173 |
+
|
174 |
+
model, preprocess_train, preprocess_val = create_model_and_transforms(
|
175 |
+
model_name,
|
176 |
+
'laion2B-s32B-b79K',
|
177 |
+
precision=inference_dtype,
|
178 |
+
device=device,
|
179 |
+
jit=False,
|
180 |
+
force_quick_gelu=False,
|
181 |
+
force_custom_text=False,
|
182 |
+
force_patch_dropout=False,
|
183 |
+
force_image_size=None,
|
184 |
+
pretrained_image=False,
|
185 |
+
image_mean=None,
|
186 |
+
image_std=None,
|
187 |
+
light_augmentation=True,
|
188 |
+
aug_cfg={},
|
189 |
+
output_dict=True,
|
190 |
+
with_score_predictor=False,
|
191 |
+
with_region_predictor=False
|
192 |
+
)
|
193 |
+
|
194 |
+
tokenizer = get_tokenizer(model_name)
|
195 |
+
|
196 |
+
if hps_version == "v2.0": # if there is a error, please download the model manually and set the path
|
197 |
+
checkpoint_path = f"{os.path.expanduser('~')}/.cache/huggingface/hub/models--xswu--HPSv2/snapshots/697403c78157020a1ae59d23f111aa58ced35b0a/HPS_v2_compressed.pt"
|
198 |
+
else: # hps_version == "v2.1"
|
199 |
+
checkpoint_path = f"{os.path.expanduser('~')}/.cache/huggingface/hub/models--xswu--HPSv2/snapshots/697403c78157020a1ae59d23f111aa58ced35b0a/HPS_v2.1_compressed.pt"
|
200 |
+
# force download of model via score
|
201 |
+
hpsv2.score([], "", hps_version=hps_version)
|
202 |
+
|
203 |
+
checkpoint = torch.load(checkpoint_path, map_location=device)
|
204 |
+
model.load_state_dict(checkpoint['state_dict'])
|
205 |
+
tokenizer = get_tokenizer(model_name)
|
206 |
+
model = model.to(device, dtype=inference_dtype)
|
207 |
+
model.eval()
|
208 |
+
|
209 |
+
target_size = (224, 224)
|
210 |
+
normalize = torchvision.transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
|
211 |
+
std=[0.26862954, 0.26130258, 0.27577711])
|
212 |
+
|
213 |
+
def loss_fn(im_pix, prompts):
|
214 |
+
im_pix = ((im_pix / 2) + 0.5).clamp(0, 1)
|
215 |
+
x_var = torchvision.transforms.Resize(target_size)(im_pix)
|
216 |
+
x_var = normalize(x_var).to(im_pix.dtype)
|
217 |
+
caption = tokenizer(prompts)
|
218 |
+
caption = caption.to(device)
|
219 |
+
outputs = model(x_var, caption)
|
220 |
+
image_features, text_features = outputs["image_features"], outputs["text_features"]
|
221 |
+
logits = image_features @ text_features.T
|
222 |
+
scores = torch.diagonal(logits)
|
223 |
+
loss = 1.0 - scores
|
224 |
+
return loss.mean(), scores.mean()
|
225 |
+
|
226 |
+
return loss_fn
|
227 |
+
|
228 |
+
def aesthetic_hps_loss_fn(aesthetic_target=None,
|
229 |
+
grad_scale=0,
|
230 |
+
inference_dtype=None,
|
231 |
+
device=None,
|
232 |
+
hps_version="v2.0"):
|
233 |
+
'''
|
234 |
+
Args:
|
235 |
+
aesthetic_target: float, the target value of the aesthetic score. it is 10 in this experiment
|
236 |
+
grad_scale: float, the scale of the gradient. it is 0.1 in this experiment
|
237 |
+
inference_dtype: torch.dtype, the data type of the model.
|
238 |
+
device: torch.device, the device to run the model.
|
239 |
+
hps_version: str, the version of the HPS model. It is "v2.0" or "v2.1" in this experiment.
|
240 |
+
|
241 |
+
Returns:
|
242 |
+
loss_fn: function, the loss function of a combination of aesthetic and HPS reward function.
|
243 |
+
'''
|
244 |
+
# HPS
|
245 |
+
model_name = "ViT-H-14"
|
246 |
+
|
247 |
+
model, preprocess_train, preprocess_val = create_model_and_transforms(
|
248 |
+
model_name,
|
249 |
+
'laion2B-s32B-b79K',
|
250 |
+
precision=inference_dtype,
|
251 |
+
device=device,
|
252 |
+
jit=False,
|
253 |
+
force_quick_gelu=False,
|
254 |
+
force_custom_text=False,
|
255 |
+
force_patch_dropout=False,
|
256 |
+
force_image_size=None,
|
257 |
+
pretrained_image=False,
|
258 |
+
image_mean=None,
|
259 |
+
image_std=None,
|
260 |
+
light_augmentation=True,
|
261 |
+
aug_cfg={},
|
262 |
+
output_dict=True,
|
263 |
+
with_score_predictor=False,
|
264 |
+
with_region_predictor=False
|
265 |
+
)
|
266 |
+
|
267 |
+
# tokenizer = get_tokenizer(model_name)
|
268 |
+
|
269 |
+
if hps_version == "v2.0": # if there is a error, please download the model manually and set the path
|
270 |
+
checkpoint_path = f"{os.path.expanduser('~')}/.cache/huggingface/hub/models--xswu--HPSv2/snapshots/697403c78157020a1ae59d23f111aa58ced35b0a/HPS_v2_compressed.pt"
|
271 |
+
else: # hps_version == "v2.1"
|
272 |
+
checkpoint_path = f"{os.path.expanduser('~')}/.cache/huggingface/hub/models--xswu--HPSv2/snapshots/697403c78157020a1ae59d23f111aa58ced35b0a/HPS_v2.1_compressed.pt"
|
273 |
+
# force download of model via score
|
274 |
+
hpsv2.score([], "", hps_version=hps_version)
|
275 |
+
|
276 |
+
checkpoint = torch.load(checkpoint_path, map_location=device)
|
277 |
+
model.load_state_dict(checkpoint['state_dict'])
|
278 |
+
tokenizer = get_tokenizer(model_name)
|
279 |
+
model = model.to(device, dtype=inference_dtype)
|
280 |
+
model.eval()
|
281 |
+
|
282 |
+
target_size = (224, 224)
|
283 |
+
normalize = torchvision.transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
|
284 |
+
std=[0.26862954, 0.26130258, 0.27577711])
|
285 |
+
# Aesthetic
|
286 |
+
scorer = AestheticScorerDiff(dtype=inference_dtype).to(device, dtype=inference_dtype)
|
287 |
+
scorer.requires_grad_(False)
|
288 |
+
|
289 |
+
def loss_fn(im_pix_un, prompts):
|
290 |
+
# Aesthetic
|
291 |
+
im_pix = ((im_pix_un / 2) + 0.5).clamp(0, 1)
|
292 |
+
im_pix = torchvision.transforms.Resize(target_size)(im_pix)
|
293 |
+
im_pix = normalize(im_pix).to(im_pix_un.dtype)
|
294 |
+
|
295 |
+
aesthetic_rewards = scorer(im_pix)
|
296 |
+
if aesthetic_target is None: # default maximization
|
297 |
+
aesthetic_loss = -1 * aesthetic_rewards
|
298 |
+
else:
|
299 |
+
# using L1 to keep on same scale
|
300 |
+
aesthetic_loss = abs(aesthetic_rewards - aesthetic_target)
|
301 |
+
aesthetic_loss = aesthetic_loss.mean() * grad_scale
|
302 |
+
aesthetic_rewards = aesthetic_rewards.mean()
|
303 |
+
|
304 |
+
# HPS
|
305 |
+
caption = tokenizer(prompts)
|
306 |
+
caption = caption.to(device)
|
307 |
+
outputs = model(im_pix, caption)
|
308 |
+
image_features, text_features = outputs["image_features"], outputs["text_features"]
|
309 |
+
logits = image_features @ text_features.T
|
310 |
+
scores = torch.diagonal(logits)
|
311 |
+
hps_loss = abs(1.0 - scores)
|
312 |
+
hps_loss = hps_loss.mean()
|
313 |
+
hps_rewards = scores.mean()
|
314 |
+
|
315 |
+
loss = (1.5 * aesthetic_loss + hps_loss) /2 # 1.5 is a hyperparameter. Set it to 1.5 because experimentally hps_loss is 1.5 times larger than aesthetic_loss
|
316 |
+
rewards = (aesthetic_rewards + 15 * hps_rewards) / 2 # 15 is a hyperparameter. Set it to 15 because experimentally aesthetic_rewards is 15 times larger than hps_reward
|
317 |
+
return loss, rewards
|
318 |
+
|
319 |
+
return loss_fn
|
320 |
+
|
321 |
+
def pick_score_loss_fn(inference_dtype=None, device=None):
|
322 |
+
'''
|
323 |
+
Args:
|
324 |
+
inference_dtype: torch.dtype, the data type of the model.
|
325 |
+
device: torch.device, the device to run the model.
|
326 |
+
|
327 |
+
Returns:
|
328 |
+
loss_fn: function, the loss function of the PickScore reward function.
|
329 |
+
'''
|
330 |
+
processor_name_or_path = "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
|
331 |
+
model_pretrained_name_or_path = "yuvalkirstain/PickScore_v1"
|
332 |
+
processor = AutoProcessor.from_pretrained(processor_name_or_path, torch_dtype=inference_dtype)
|
333 |
+
model = AutoModel.from_pretrained(model_pretrained_name_or_path, torch_dtype=inference_dtype).eval().to(device)
|
334 |
+
model.requires_grad_(False)
|
335 |
+
|
336 |
+
def loss_fn(im_pix_un, prompts): # im_pix_un: b,c,h,w
|
337 |
+
im_pix = ((im_pix_un / 2) + 0.5).clamp(0, 1)
|
338 |
+
|
339 |
+
# reproduce the pick_score preprocessing
|
340 |
+
im_pix = im_pix * 255 # b,c,h,w
|
341 |
+
|
342 |
+
if im_pix.shape[2] < im_pix.shape[3]:
|
343 |
+
height = 224
|
344 |
+
width = im_pix.shape[3] * height // im_pix.shape[2] # keep the aspect ratio, so the width is w * 224/h
|
345 |
+
else:
|
346 |
+
width = 224
|
347 |
+
height = im_pix.shape[2] * width // im_pix.shape[3] # keep the aspect ratio, so the height is h * 224/w
|
348 |
+
|
349 |
+
# interpolation and antialiasing should be the same as below
|
350 |
+
im_pix = torchvision.transforms.Resize((height, width),
|
351 |
+
interpolation=torchvision.transforms.InterpolationMode.BICUBIC,
|
352 |
+
antialias=True)(im_pix)
|
353 |
+
im_pix = im_pix.permute(0, 2, 3, 1) # b,c,h,w -> (b,h,w,c)
|
354 |
+
# crop the center 224x224
|
355 |
+
startx = width//2 - (224//2)
|
356 |
+
starty = height//2 - (224//2)
|
357 |
+
im_pix = im_pix[:, starty:starty+224, startx:startx+224, :]
|
358 |
+
# do rescale and normalize as CLIP
|
359 |
+
im_pix = im_pix * 0.00392156862745098 # rescale factor
|
360 |
+
mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).to(device)
|
361 |
+
std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).to(device)
|
362 |
+
im_pix = (im_pix - mean) / std
|
363 |
+
im_pix = im_pix.permute(0, 3, 1, 2) # BHWC -> BCHW
|
364 |
+
|
365 |
+
text_inputs = processor(
|
366 |
+
text=prompts,
|
367 |
+
padding=True,
|
368 |
+
truncation=True,
|
369 |
+
max_length=77,
|
370 |
+
return_tensors="pt",
|
371 |
+
).to(device)
|
372 |
+
|
373 |
+
|
374 |
+
# embed
|
375 |
+
image_embs = model.get_image_features(pixel_values=im_pix)
|
376 |
+
image_embs = image_embs / torch.norm(image_embs, dim=-1, keepdim=True)
|
377 |
+
|
378 |
+
text_embs = model.get_text_features(**text_inputs)
|
379 |
+
text_embs = text_embs / torch.norm(text_embs, dim=-1, keepdim=True)
|
380 |
+
|
381 |
+
# score
|
382 |
+
scores = model.logit_scale.exp() * (text_embs @ image_embs.T)[0]
|
383 |
+
loss = abs(1.0 - scores / 100.0)
|
384 |
+
return loss.mean(), scores.mean()
|
385 |
+
|
386 |
+
return loss_fn
|
387 |
+
|
388 |
+
def weather_loss_fn(inference_dtype=None, device=None, weather="rainy", target=None, grad_scale=0):
|
389 |
+
'''
|
390 |
+
Args:
|
391 |
+
inference_dtype: torch.dtype, the data type of the model.
|
392 |
+
device: torch.device, the device to run the model.
|
393 |
+
weather: str, the weather condition. It is "rainy" or "snowy" in this experiment.
|
394 |
+
target: float, the target value of the weather score. It is 1.0 in this experiment.
|
395 |
+
grad_scale: float, the scale of the gradient. It is 1 in this experiment.
|
396 |
+
|
397 |
+
Returns:
|
398 |
+
loss_fn: function, the loss function of the weather reward function.
|
399 |
+
'''
|
400 |
+
if weather == "rainy":
|
401 |
+
reward_model_path = "../assets/rainy_reward.pt"
|
402 |
+
elif weather == "snowy":
|
403 |
+
reward_model_path = "../assets/snowy_reward.pt"
|
404 |
+
else:
|
405 |
+
raise NotImplementedError
|
406 |
+
scorer = WeatherScorer(dtype=inference_dtype, model_path=reward_model_path).to(device, dtype=inference_dtype)
|
407 |
+
scorer.requires_grad_(False)
|
408 |
+
scorer.eval()
|
409 |
+
def loss_fn(im_pix_un):
|
410 |
+
im_pix = ((im_pix_un + 1) / 2).clamp(0, 1) # from [-1, 1] to [0, 1]
|
411 |
+
rewards = scorer(im_pix)
|
412 |
+
|
413 |
+
if target is None:
|
414 |
+
loss = rewards
|
415 |
+
else:
|
416 |
+
loss = abs(rewards - target)
|
417 |
+
|
418 |
+
return loss.mean() * grad_scale, rewards.mean()
|
419 |
+
return loss_fn
|
420 |
+
|
421 |
+
def objectDetection_loss_fn(inference_dtype=None, device=None, targetObject='dog.', model_name='grounding-dino-base'):
|
422 |
+
'''
|
423 |
+
This reward function is used to remove the target object from the generated video.
|
424 |
+
We use yolo-s-tiny model to detect the target object in the generated video.
|
425 |
+
|
426 |
+
Args:
|
427 |
+
inference_dtype: torch.dtype, the data type of the model.
|
428 |
+
device: torch.device, the device to run the model.
|
429 |
+
targetObject: str, the object to detect. It is "dog" in this experiment.
|
430 |
+
|
431 |
+
Returns:
|
432 |
+
loss_fn: function, the loss function of the object detection reward function.
|
433 |
+
'''
|
434 |
+
if model_name == "yolos-base":
|
435 |
+
image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-base", torch_dtype=inference_dtype)
|
436 |
+
model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-base", torch_dtype=inference_dtype).to(device)
|
437 |
+
# check if "." in the targetObject name for yolos model
|
438 |
+
if "." in targetObject:
|
439 |
+
raise ValueError("The targetObject name should not contain '.' for yolos-base model.")
|
440 |
+
elif model_name == "yolos-tiny":
|
441 |
+
image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-tiny", torch_dtype=inference_dtype)
|
442 |
+
model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny", torch_dtype=inference_dtype).to(device)
|
443 |
+
# check if "." in the targetObject name for yolos model
|
444 |
+
if "." in targetObject:
|
445 |
+
raise ValueError("The targetObject name should not contain '.' for yolos-tiny model.")
|
446 |
+
elif model_name == "grounding-dino-base":
|
447 |
+
image_processor = AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-base", torch_dtype=inference_dtype)
|
448 |
+
model = AutoModelForZeroShotObjectDetection.from_pretrained("IDEA-Research/grounding-dino-base",torch_dtype=inference_dtype).to(device)
|
449 |
+
# check if "." in the targetObject name for grounding-dino model
|
450 |
+
if "." not in targetObject:
|
451 |
+
raise ValueError("The targetObject name should contain '.' for grounding-dino-base model.")
|
452 |
+
elif model_name == "grounding-dino-tiny":
|
453 |
+
image_processor = AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-tiny", torch_dtype=inference_dtype)
|
454 |
+
model = AutoModelForZeroShotObjectDetection.from_pretrained("IDEA-Research/grounding-dino-tiny", torch_dtype=inference_dtype).to(device)
|
455 |
+
# check if "." in the targetObject name for grounding-dino model
|
456 |
+
if "." not in targetObject:
|
457 |
+
raise ValueError("The targetObject name should contain '.' for grounding-dino-tiny model.")
|
458 |
+
else:
|
459 |
+
raise NotImplementedError
|
460 |
+
|
461 |
+
model.requires_grad_(False)
|
462 |
+
model.eval()
|
463 |
+
|
464 |
+
def loss_fn(im_pix_un): # im_pix_un: b,c,h,w
|
465 |
+
images = ((im_pix_un / 2) + 0.5).clamp(0.0, 1.0)
|
466 |
+
|
467 |
+
# reproduce the yolo preprocessing
|
468 |
+
height = 512
|
469 |
+
width = 512 * images.shape[3] // images.shape[2] # keep the aspect ratio, so the width is 512 * w/h
|
470 |
+
images = torchvision.transforms.Resize((height, width), antialias=False)(images)
|
471 |
+
images = images.permute(0, 2, 3, 1) # b,c,h,w -> (b,h,w,c)
|
472 |
+
|
473 |
+
image_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
|
474 |
+
image_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
|
475 |
+
|
476 |
+
images = (images - image_mean) / image_std
|
477 |
+
normalized_image = images.permute(0,3,1,2) # NHWC -> NCHW
|
478 |
+
|
479 |
+
# Process images
|
480 |
+
if model_name == "yolos-base" or model_name == "yolos-tiny":
|
481 |
+
outputs = model(pixel_values=normalized_image)
|
482 |
+
else: # grounding-dino model
|
483 |
+
inputs = image_processor(text=targetObject, return_tensors="pt").to(device)
|
484 |
+
outputs = model(pixel_values=normalized_image, input_ids=inputs.input_ids)
|
485 |
+
|
486 |
+
# Get target sizes for each image
|
487 |
+
target_sizes = torch.tensor([normalized_image[0].shape[1:]]*normalized_image.shape[0]).to(device)
|
488 |
+
|
489 |
+
# Post-process results for each image
|
490 |
+
if model_name == "yolos-base" or model_name == "yolos-tiny":
|
491 |
+
results = image_processor.post_process_object_detection(outputs, threshold=0.2, target_sizes=target_sizes)
|
492 |
+
else: # grounding-dino model
|
493 |
+
results = image_processor.post_process_grounded_object_detection(
|
494 |
+
outputs,
|
495 |
+
inputs.input_ids,
|
496 |
+
box_threshold=0.4,
|
497 |
+
text_threshold=0.3,
|
498 |
+
target_sizes=target_sizes
|
499 |
+
)
|
500 |
+
|
501 |
+
sum_avg_scores = 0
|
502 |
+
for i, result in enumerate(results):
|
503 |
+
if model_name == "yolos-base" or model_name == "yolos-tiny":
|
504 |
+
id = model.config.label2id[targetObject]
|
505 |
+
# get index of targetObject's label
|
506 |
+
index = torch.where(result["labels"] == id)
|
507 |
+
if len(index[0]) == 0: # index: ([],[]) so index[0] is the first list
|
508 |
+
sum_avg_scores = torch.sum(outputs.logits - outputs.logits) # set sum_avg_scores to 0
|
509 |
+
continue
|
510 |
+
scores = result["scores"][index]
|
511 |
+
else: # grounding-dino model
|
512 |
+
if result["scores"].shape[0] == 0:
|
513 |
+
sum_avg_scores = torch.sum(outputs.last_hidden_state - outputs.last_hidden_state) # set sum_avg_scores to 0
|
514 |
+
continue
|
515 |
+
scores = result["scores"]
|
516 |
+
sum_avg_scores = sum_avg_scores + (torch.sum(scores) / scores.shape[0])
|
517 |
+
|
518 |
+
loss = sum_avg_scores / len(results)
|
519 |
+
reward = 1 - loss
|
520 |
+
|
521 |
+
return loss, reward
|
522 |
+
return loss_fn
|
523 |
+
|
524 |
+
def compression_loss_fn(inference_dtype=None, device=None, target=None, grad_scale=0, model_path=None):
|
525 |
+
'''
|
526 |
+
Args:
|
527 |
+
inference_dtype: torch.dtype, the data type of the model.
|
528 |
+
device: torch.device, the device to run the model.
|
529 |
+
model_path: str, the path of the compression model.
|
530 |
+
|
531 |
+
Returns:
|
532 |
+
loss_fn: function, the loss function of the compression reward function.
|
533 |
+
'''
|
534 |
+
scorer = JpegCompressionScorer(dtype=inference_dtype, model_path=model_path).to(device, dtype=inference_dtype)
|
535 |
+
scorer.requires_grad_(False)
|
536 |
+
scorer.eval()
|
537 |
+
def loss_fn(im_pix_un):
|
538 |
+
im_pix = ((im_pix_un + 1) / 2).clamp(0, 1)
|
539 |
+
rewards = scorer(im_pix)
|
540 |
+
|
541 |
+
if target is None:
|
542 |
+
loss = rewards
|
543 |
+
else:
|
544 |
+
loss = abs(rewards - target)
|
545 |
+
return loss.mean() * grad_scale, rewards.mean()
|
546 |
+
|
547 |
+
return loss_fn
|
548 |
+
|
549 |
+
def actpred_loss_fn(inference_dtype=None, device=None, num_frames = 14, target_size=224):
|
550 |
+
scorer = ActPredScorer(device=device, num_frames = num_frames, dtype=inference_dtype)
|
551 |
+
scorer.requires_grad_(False)
|
552 |
+
|
553 |
+
def preprocess_img(img):
|
554 |
+
img = ((img/2) + 0.5).clamp(0,1)
|
555 |
+
img = torchvision.transforms.Resize((target_size, target_size), antialias = True)(img)
|
556 |
+
img = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])(img)
|
557 |
+
return img
|
558 |
+
def loss_fn(vid, target_action_label):
|
559 |
+
vid = torch.cat([preprocess_img(img).unsqueeze(0) for img in vid])[None]
|
560 |
+
return scorer.get_loss_and_score(vid, target_action_label)
|
561 |
+
|
562 |
+
return loss_fn
|
563 |
+
|
564 |
+
|
565 |
+
def should_sample(global_step, validation_steps, is_sample_preview):
|
566 |
+
return (global_step % validation_steps == 0 or global_step ==1) \
|
567 |
+
and is_sample_preview
|
568 |
+
|
569 |
+
|
570 |
+
def run_training(args, peft_model, **kwargs):
|
571 |
+
## ---------------------step 1: accelerator setup---------------------------
|
572 |
+
accelerator = Accelerator( # Initialize Accelerator
|
573 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
574 |
+
mixed_precision=args.mixed_precision,
|
575 |
+
project_dir=args.project_dir
|
576 |
+
|
577 |
+
)
|
578 |
+
output_dir = args.project_dir
|
579 |
+
|
580 |
+
# Make one log on every process with the configuration for debugging.
|
581 |
+
create_logging(logging, logger, accelerator)
|
582 |
+
|
583 |
+
# ## ------------------------step 2: model config-----------------------------
|
584 |
+
# # download the checkpoint for VideoCrafter2 model
|
585 |
+
# ckpt_dir = args.ckpt_path.split('/') # args.ckpt='checkpoints/base_512_v2/model.ckpt' -> 'checkpoints/base_512_v2'
|
586 |
+
# ckpt_dir = '/'.join(ckpt_dir[:-1])
|
587 |
+
# snapshot_download(repo_id='VideoCrafter/VideoCrafter2', local_dir =ckpt_dir)
|
588 |
+
|
589 |
+
# # load the model
|
590 |
+
# config = OmegaConf.load(args.config)
|
591 |
+
# model_config = config.pop("model", OmegaConf.create())
|
592 |
+
# model = instantiate_from_config(model_config)
|
593 |
+
|
594 |
+
# assert os.path.exists(args.ckpt_path), f"Error: checkpoint [{args.ckpt_path}] Not Found!"
|
595 |
+
# model = load_model_checkpoint(model, args.ckpt_path)
|
596 |
+
|
597 |
+
|
598 |
+
# # convert first_stage_model and cond_stage_model to torch.float16 if mixed_precision is True
|
599 |
+
# if args.mixed_precision != 'no':
|
600 |
+
# model.first_stage_model = model.first_stage_model.half()
|
601 |
+
# model.cond_stage_model = model.cond_stage_model.half()
|
602 |
+
|
603 |
+
# # step 2.1: add LoRA using peft
|
604 |
+
# config = peft.LoraConfig(
|
605 |
+
# r=args.lora_rank,
|
606 |
+
# target_modules=["to_k", "to_v", "to_q"], # only diffusion_model has these modules
|
607 |
+
# lora_dropout=0.01,
|
608 |
+
# )
|
609 |
+
|
610 |
+
# peft_model = peft.get_peft_model(model, config)
|
611 |
+
|
612 |
+
# peft_model.print_trainable_parameters()
|
613 |
+
|
614 |
+
# # load the pretrained LoRA model
|
615 |
+
# if args.lora_ckpt_path is not None:
|
616 |
+
# if args.lora_ckpt_path == "huggingface-hps-aesthetic": # download the pretrained LoRA model from huggingface
|
617 |
+
# snapshot_download(repo_id='zheyangqin/VADER', local_dir ='VADER-VideoCrafter/checkpoints/pretrained_lora')
|
618 |
+
# args.lora_ckpt_path = 'VADER-VideoCrafter/checkpoints/pretrained_lora/vader_videocrafter_hps_aesthetic.pt'
|
619 |
+
# elif args.lora_ckpt_path == "huggingface-pickscore": # download the pretrained LoRA model from huggingface
|
620 |
+
# snapshot_download(repo_id='zheyangqin/VADER', local_dir ='VADER-VideoCrafter/checkpoints/pretrained_lora')
|
621 |
+
# args.lora_ckpt_path = 'VADER-VideoCrafter/checkpoints/pretrained_lora/vader_videocrafter_pickscore.pt'
|
622 |
+
# # load the pretrained LoRA model
|
623 |
+
# peft.set_peft_model_state_dict(peft_model, torch.load(args.lora_ckpt_path))
|
624 |
+
|
625 |
+
# Inference Step: only do inference and save the videos. Skip this step if it is training
|
626 |
+
# ==================================================================
|
627 |
+
if args.inference_only:
|
628 |
+
peft_model = accelerator.prepare(peft_model)
|
629 |
+
# sample shape
|
630 |
+
assert (args.height % 16 == 0) and (args.width % 16 == 0), "Error: image size [h,w] should be multiples of 16!"
|
631 |
+
# latent noise shape
|
632 |
+
h, w = args.height // 8, args.width // 8
|
633 |
+
if isinstance(peft_model, torch.nn.parallel.DistributedDataParallel):
|
634 |
+
frames = peft_model.module.temporal_length if args.frames < 0 else args.frames
|
635 |
+
channels = peft_model.module.channels
|
636 |
+
else:
|
637 |
+
frames = peft_model.temporal_length if args.frames < 0 else args.frames
|
638 |
+
channels = peft_model.channels
|
639 |
+
|
640 |
+
## Inference step 2: run Inference over samples
|
641 |
+
logger.info("***** Running inference *****")
|
642 |
+
|
643 |
+
first_epoch = 0
|
644 |
+
global_step = 0
|
645 |
+
|
646 |
+
|
647 |
+
## Inference Step 3: generate new validation videos
|
648 |
+
with torch.no_grad():
|
649 |
+
|
650 |
+
# set random seed for each process
|
651 |
+
random.seed(args.seed)
|
652 |
+
torch.manual_seed(args.seed)
|
653 |
+
|
654 |
+
prompts_all = [args.prompt_str]
|
655 |
+
val_prompt = list(prompts_all)
|
656 |
+
|
657 |
+
assert len(val_prompt) == 1, "Error: only one prompt is allowed for inference in gradio!"
|
658 |
+
|
659 |
+
# store output of generations in dict
|
660 |
+
results=dict(filenames=[],dir_name=[], prompt=[])
|
661 |
+
|
662 |
+
# Inference Step 3.1: forward pass
|
663 |
+
batch_size = len(val_prompt)
|
664 |
+
noise_shape = [batch_size, channels, frames, h, w]
|
665 |
+
|
666 |
+
fps = torch.tensor([args.fps]*batch_size).to(accelerator.device).long()
|
667 |
+
|
668 |
+
prompts = val_prompt
|
669 |
+
if isinstance(prompts, str):
|
670 |
+
prompts = [prompts]
|
671 |
+
|
672 |
+
|
673 |
+
with accelerator.autocast(): # mixed precision
|
674 |
+
if isinstance(peft_model, torch.nn.parallel.DistributedDataParallel):
|
675 |
+
text_emb = peft_model.module.get_learned_conditioning(prompts).to(accelerator.device)
|
676 |
+
else:
|
677 |
+
text_emb = peft_model.get_learned_conditioning(prompts).to(accelerator.device)
|
678 |
+
|
679 |
+
if args.mode == 'base':
|
680 |
+
cond = {"c_crossattn": [text_emb], "fps": fps}
|
681 |
+
else: # TODO: implement i2v mode training in the future
|
682 |
+
raise NotImplementedError
|
683 |
+
|
684 |
+
# Inference Step 3.2: inference, batch_samples shape: batch, <samples>, c, t, h, w
|
685 |
+
# no backprop_mode=args.backprop_mode because it is inference process
|
686 |
+
if isinstance(peft_model, torch.nn.parallel.DistributedDataParallel):
|
687 |
+
batch_samples = batch_ddim_sampling(peft_model.module, cond, noise_shape, args.n_samples, \
|
688 |
+
args.ddim_steps, args.ddim_eta, args.unconditional_guidance_scale, None, decode_frame=args.decode_frame, **kwargs)
|
689 |
+
else:
|
690 |
+
batch_samples = batch_ddim_sampling(peft_model, cond, noise_shape, args.n_samples, \
|
691 |
+
args.ddim_steps, args.ddim_eta, args.unconditional_guidance_scale, None, decode_frame=args.decode_frame, **kwargs)
|
692 |
+
|
693 |
+
# batch_samples: b,samples,c,t,h,w
|
694 |
+
dir_name = os.path.join(output_dir, "samples")
|
695 |
+
# filenames should be related to the gpu index
|
696 |
+
# get timestamps for filenames to avoid overwriting
|
697 |
+
# current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
698 |
+
filenames = [f"temporal"] # only one sample
|
699 |
+
# if dir_name is not exists, create it
|
700 |
+
os.makedirs(dir_name, exist_ok=True)
|
701 |
+
|
702 |
+
save_videos(batch_samples, dir_name, filenames, fps=args.savefps)
|
703 |
+
|
704 |
+
results["filenames"].extend(filenames)
|
705 |
+
results["dir_name"].extend([dir_name]*len(filenames))
|
706 |
+
results["prompt"].extend(prompts)
|
707 |
+
results=[ results ] # transform to list, otherwise gather_object() will not collect correctly
|
708 |
+
|
709 |
+
# Inference Step 3.3: collect inference results and save the videos to wandb
|
710 |
+
# collect inference results from all the GPUs
|
711 |
+
results_gathered=gather_object(results)
|
712 |
+
|
713 |
+
if accelerator.is_main_process:
|
714 |
+
filenames = []
|
715 |
+
dir_name = []
|
716 |
+
prompts = []
|
717 |
+
for i in range(len(results_gathered)):
|
718 |
+
filenames.extend(results_gathered[i]["filenames"])
|
719 |
+
dir_name.extend(results_gathered[i]["dir_name"])
|
720 |
+
prompts.extend(results_gathered[i]["prompt"])
|
721 |
+
|
722 |
+
logger.info("Validation sample saved!")
|
723 |
+
|
724 |
+
# # batch size is 1, so only one video is generated
|
725 |
+
|
726 |
+
# video = get_videos(batch_samples)
|
727 |
+
|
728 |
+
# # read the video from the saved path
|
729 |
+
video_path = os.path.join(dir_name[0], filenames[0]+".mp4")
|
730 |
+
|
731 |
+
|
732 |
+
|
733 |
+
# release memory
|
734 |
+
del batch_samples
|
735 |
+
torch.cuda.empty_cache()
|
736 |
+
gc.collect()
|
737 |
+
|
738 |
+
return video_path
|
739 |
+
|
740 |
+
# end of inference only, training script continues
|
741 |
+
# ==================================================================
|
742 |
+
|
743 |
+
|
744 |
+
def setup_model(lora_ckpt_path="huggingface-pickscore", lora_rank=16):
|
745 |
+
parser = get_parser()
|
746 |
+
args = parser.parse_args()
|
747 |
+
|
748 |
+
## ------------------------step 2: model config-----------------------------
|
749 |
+
# download the checkpoint for VideoCrafter2 model
|
750 |
+
ckpt_dir = args.ckpt_path.split('/') # args.ckpt='checkpoints/base_512_v2/model.ckpt' -> 'checkpoints/base_512_v2'
|
751 |
+
ckpt_dir = '/'.join(ckpt_dir[:-1])
|
752 |
+
snapshot_download(repo_id='VideoCrafter/VideoCrafter2', local_dir =ckpt_dir)
|
753 |
+
|
754 |
+
# load the model
|
755 |
+
config = OmegaConf.load(args.config)
|
756 |
+
model_config = config.pop("model", OmegaConf.create())
|
757 |
+
model = instantiate_from_config(model_config)
|
758 |
+
|
759 |
+
assert os.path.exists(args.ckpt_path), f"Error: checkpoint [{args.ckpt_path}] Not Found!"
|
760 |
+
model = load_model_checkpoint(model, args.ckpt_path)
|
761 |
+
|
762 |
+
# convert first_stage_model and cond_stage_model to torch.float16 if mixed_precision is True
|
763 |
+
if args.mixed_precision != 'no':
|
764 |
+
model.first_stage_model = model.first_stage_model.half()
|
765 |
+
model.cond_stage_model = model.cond_stage_model.half()
|
766 |
+
|
767 |
+
# step 2.1: add LoRA using peft
|
768 |
+
config = peft.LoraConfig(
|
769 |
+
r=args.lora_rank,
|
770 |
+
target_modules=["to_k", "to_v", "to_q"], # only diffusion_model has these modules
|
771 |
+
lora_dropout=0.01,
|
772 |
+
)
|
773 |
+
|
774 |
+
peft_model = peft.get_peft_model(model, config)
|
775 |
+
|
776 |
+
peft_model.print_trainable_parameters()
|
777 |
+
|
778 |
+
# load the pretrained LoRA model
|
779 |
+
if lora_ckpt_path != "Base Model":
|
780 |
+
if lora_ckpt_path == "huggingface-hps-aesthetic": # download the pretrained LoRA model from huggingface
|
781 |
+
snapshot_download(repo_id='zheyangqin/VADER', local_dir ='VADER-VideoCrafter/checkpoints/pretrained_lora')
|
782 |
+
lora_ckpt_path = 'VADER-VideoCrafter/checkpoints/pretrained_lora/vader_videocrafter_hps_aesthetic.pt'
|
783 |
+
elif lora_ckpt_path == "huggingface-pickscore": # download the pretrained LoRA model from huggingface
|
784 |
+
snapshot_download(repo_id='zheyangqin/VADER', local_dir ='VADER-VideoCrafter/checkpoints/pretrained_lora')
|
785 |
+
lora_ckpt_path = 'VADER-VideoCrafter/checkpoints/pretrained_lora/vader_videocrafter_pickscore.pt'
|
786 |
+
# load the pretrained LoRA model
|
787 |
+
peft.set_peft_model_state_dict(peft_model, torch.load(lora_ckpt_path))
|
788 |
+
|
789 |
+
print("Model setup complete!")
|
790 |
+
return peft_model
|
791 |
+
|
792 |
+
|
793 |
+
def main_fn(prompt, seed=200, height=320, width=512, unconditional_guidance_scale=12, ddim_steps=25, ddim_eta=1.0,
|
794 |
+
frames=24, savefps=10, model=None):
|
795 |
+
|
796 |
+
parser = get_parser()
|
797 |
+
args = parser.parse_args()
|
798 |
+
|
799 |
+
|
800 |
+
|
801 |
+
# overwrite the default arguments
|
802 |
+
args.prompt_str = prompt
|
803 |
+
args.seed = seed
|
804 |
+
args.height = height
|
805 |
+
args.width = width
|
806 |
+
args.unconditional_guidance_scale = unconditional_guidance_scale
|
807 |
+
args.ddim_steps = ddim_steps
|
808 |
+
args.ddim_eta = ddim_eta
|
809 |
+
args.frames = frames
|
810 |
+
args.savefps = savefps
|
811 |
+
|
812 |
+
seed_everything(args.seed)
|
813 |
+
|
814 |
+
video_path = run_training(args, model)
|
815 |
+
|
816 |
+
return video_path
|
817 |
+
|
VADER-VideoCrafter/scripts/run_text2video_inference.sh
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ckpt='checkpoints/base_512_v2/model.ckpt'
|
2 |
+
config='configs/inference_t2v_512_v2.0.yaml'
|
3 |
+
PORT=$((20000 + RANDOM % 10000))
|
4 |
+
|
5 |
+
accelerate launch --multi_gpu --main_process_port $PORT scripts/main/train_t2v_lora.py \
|
6 |
+
--seed 200 \
|
7 |
+
--mode 'base' \
|
8 |
+
--ckpt_path $ckpt \
|
9 |
+
--config $config \
|
10 |
+
--height 320 --width 512 \
|
11 |
+
--unconditional_guidance_scale 12.0 \
|
12 |
+
--ddim_steps 25 \
|
13 |
+
--ddim_eta 1.0 \
|
14 |
+
--frames 24 \
|
15 |
+
--prompt_fn 'chatgpt_custom_cute' \
|
16 |
+
--val_batch_size 1 \
|
17 |
+
--num_val_runs 1 \
|
18 |
+
--lora_rank 16 \
|
19 |
+
--inference_only True \
|
20 |
+
--project_dir ./project_dir/inference \
|
21 |
+
--lora_ckpt_path huggingface-pickscore \
|
22 |
+
--is_sample_preview True
|
23 |
+
|
24 |
+
|
25 |
+
|
26 |
+
ckpt='checkpoints/base_512_v2/model.ckpt'
|
27 |
+
config='configs/inference_t2v_512_v2.0.yaml'
|
28 |
+
PORT=$((20000 + RANDOM % 10000))
|
29 |
+
|
30 |
+
accelerate launch --multi_gpu --main_process_port 15009 scripts/main/train_t2v_lora.py --seed 200 --mode 'base' --ckpt_path 'checkpoints/base_512_v2/model.ckpt' --config 'configs/inference_t2v_512_v2.0.yaml' --height 320 --width 512 --unconditional_guidance_scale 12.0 --ddim_steps 25 --ddim_eta 1.0 --frames 24 --prompt_fn 'chatgpt_custom_cute' --val_batch_size 1 --num_val_runs 1 --lora_rank 16 --inference_only True --project_dir ./project_dir/inference --lora_ckpt_path huggingface-pickscore --is_sample_preview True
|
VADER-VideoCrafter/scripts/run_text2video_train.sh
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ckpt='checkpoints/base_512_v2/model.ckpt'
|
2 |
+
config='configs/inference_t2v_512_v2.0.yaml'
|
3 |
+
PORT=$((20000 + RANDOM % 10000))
|
4 |
+
|
5 |
+
accelerate launch --multi_gpu --main_process_port $PORT scripts/main/train_t2v_lora.py \
|
6 |
+
--seed 300 \
|
7 |
+
--mode 'base' \
|
8 |
+
--ckpt_path $ckpt \
|
9 |
+
--config $config \
|
10 |
+
--height 320 --width 512 \
|
11 |
+
--unconditional_guidance_scale 12.0 \
|
12 |
+
--ddim_steps 25 \
|
13 |
+
--ddim_eta 1.0 \
|
14 |
+
--frames 12 \
|
15 |
+
--prompt_fn 'chatgpt_custom_instruments' \
|
16 |
+
--gradient_accumulation_steps 8 \
|
17 |
+
--num_train_epochs 200 \
|
18 |
+
--train_batch_size 1 \
|
19 |
+
--val_batch_size 1 \
|
20 |
+
--num_val_runs 1 \
|
21 |
+
--reward_fn 'aesthetic_hps' \
|
22 |
+
--decode_frame '-1' \
|
23 |
+
--hps_version 'v2.1' \
|
24 |
+
--lr 0.0002 \
|
25 |
+
--validation_steps 10 \
|
26 |
+
--lora_rank 16 \
|
27 |
+
--is_sample_preview True
|
28 |
+
|
VADER-VideoCrafter/utils/utils.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib
|
2 |
+
import numpy as np
|
3 |
+
import cv2
|
4 |
+
import torch
|
5 |
+
import torch.distributed as dist
|
6 |
+
|
7 |
+
|
8 |
+
def count_params(model, verbose=False):
|
9 |
+
total_params = sum(p.numel() for p in model.parameters())
|
10 |
+
if verbose:
|
11 |
+
print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.")
|
12 |
+
return total_params
|
13 |
+
|
14 |
+
|
15 |
+
def check_istarget(name, para_list):
|
16 |
+
"""
|
17 |
+
name: full name of source para
|
18 |
+
para_list: partial name of target para
|
19 |
+
"""
|
20 |
+
istarget=False
|
21 |
+
for para in para_list:
|
22 |
+
if para in name:
|
23 |
+
return True
|
24 |
+
return istarget
|
25 |
+
|
26 |
+
|
27 |
+
def instantiate_from_config(config):
|
28 |
+
if not "target" in config:
|
29 |
+
if config == '__is_first_stage__':
|
30 |
+
return None
|
31 |
+
elif config == "__is_unconditional__":
|
32 |
+
return None
|
33 |
+
raise KeyError("Expected key `target` to instantiate.")
|
34 |
+
return get_obj_from_str(config["target"])(**config.get("params", dict()))
|
35 |
+
|
36 |
+
|
37 |
+
def get_obj_from_str(string, reload=False):
|
38 |
+
module, cls = string.rsplit(".", 1)
|
39 |
+
if reload:
|
40 |
+
module_imp = importlib.import_module(module)
|
41 |
+
importlib.reload(module_imp)
|
42 |
+
return getattr(importlib.import_module(module, package=None), cls)
|
43 |
+
|
44 |
+
|
45 |
+
def load_npz_from_dir(data_dir):
|
46 |
+
data = [np.load(os.path.join(data_dir, data_name))['arr_0'] for data_name in os.listdir(data_dir)]
|
47 |
+
data = np.concatenate(data, axis=0)
|
48 |
+
return data
|
49 |
+
|
50 |
+
|
51 |
+
def load_npz_from_paths(data_paths):
|
52 |
+
data = [np.load(data_path)['arr_0'] for data_path in data_paths]
|
53 |
+
data = np.concatenate(data, axis=0)
|
54 |
+
return data
|
55 |
+
|
56 |
+
|
57 |
+
def resize_numpy_image(image, max_resolution=512 * 512, resize_short_edge=None):
|
58 |
+
h, w = image.shape[:2]
|
59 |
+
if resize_short_edge is not None:
|
60 |
+
k = resize_short_edge / min(h, w)
|
61 |
+
else:
|
62 |
+
k = max_resolution / (h * w)
|
63 |
+
k = k**0.5
|
64 |
+
h = int(np.round(h * k / 64)) * 64
|
65 |
+
w = int(np.round(w * k / 64)) * 64
|
66 |
+
image = cv2.resize(image, (w, h), interpolation=cv2.INTER_LANCZOS4)
|
67 |
+
return image
|
68 |
+
|
69 |
+
|
70 |
+
def setup_dist(args):
|
71 |
+
if dist.is_initialized():
|
72 |
+
return
|
73 |
+
torch.cuda.set_device(args.local_rank)
|
74 |
+
torch.distributed.init_process_group(
|
75 |
+
'nccl',
|
76 |
+
init_method='env://'
|
77 |
+
)
|
app.py
CHANGED
@@ -1,7 +1,210 @@
|
|
1 |
import gradio as gr
|
|
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import os
|
3 |
|
4 |
+
import sys
|
5 |
+
sys.path.append('./VADER-VideoCrafter/scripts/main')
|
6 |
+
sys.path.append('./VADER-VideoCrafter/scripts')
|
7 |
+
sys.path.append('./VADER-VideoCrafter')
|
8 |
|
9 |
+
from train_t2v_lora import main_fn, setup_model
|
10 |
+
|
11 |
+
model = None # Placeholder for model
|
12 |
+
|
13 |
+
def gradio_main_fn(prompt, seed, height, width, unconditional_guidance_scale, ddim_steps, ddim_eta,
|
14 |
+
frames, savefps):
|
15 |
+
global model
|
16 |
+
if model is None:
|
17 |
+
return "Model is not loaded. Please load the model first."
|
18 |
+
video_path = main_fn(prompt=prompt,
|
19 |
+
seed=int(seed),
|
20 |
+
height=int(height),
|
21 |
+
width=int(width),
|
22 |
+
unconditional_guidance_scale=float(unconditional_guidance_scale),
|
23 |
+
ddim_steps=int(ddim_steps),
|
24 |
+
ddim_eta=float(ddim_eta),
|
25 |
+
frames=int(frames),
|
26 |
+
savefps=int(savefps),
|
27 |
+
model=model)
|
28 |
+
|
29 |
+
return video_path
|
30 |
+
|
31 |
+
def reset_fn():
|
32 |
+
return ("A mermaid with flowing hair and a shimmering tail discovers a hidden underwater kingdom adorned with coral palaces, glowing pearls, and schools of colorful fish, encountering both wonders and dangers along the way.",
|
33 |
+
200, 320, 512, 12.0, 25, 1.0, 24, 16, 10, "huggingface-pickscore")
|
34 |
+
|
35 |
+
def update_lora_rank(lora_model):
|
36 |
+
if lora_model == "huggingface-pickscore":
|
37 |
+
return gr.update(value=16)
|
38 |
+
elif lora_model == "huggingface-hps-aesthetic":
|
39 |
+
return gr.update(value=8)
|
40 |
+
else: # "Base Model"
|
41 |
+
return gr.update(value=0)
|
42 |
+
|
43 |
+
def update_dropdown(lora_rank):
|
44 |
+
if lora_rank == 16:
|
45 |
+
return gr.update(value="huggingface-pickscore")
|
46 |
+
elif lora_rank == 8:
|
47 |
+
return gr.update(value="huggingface-hps-aesthetic")
|
48 |
+
else: # 0
|
49 |
+
return gr.update(value="Base Model")
|
50 |
+
|
51 |
+
|
52 |
+
def setup_model_progress(lora_model, lora_rank):
|
53 |
+
global model
|
54 |
+
|
55 |
+
# Disable buttons and show loading indicator
|
56 |
+
yield (gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), "Loading model...")
|
57 |
+
|
58 |
+
model = setup_model(lora_model, lora_rank) # Ensure you pass the necessary parameters to the setup_model function
|
59 |
+
|
60 |
+
# Enable buttons after loading and update indicator
|
61 |
+
yield (gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), "Model loaded successfully")
|
62 |
+
|
63 |
+
css = """
|
64 |
+
.centered {
|
65 |
+
display: flex;
|
66 |
+
justify-content: center;
|
67 |
+
}
|
68 |
+
"""
|
69 |
+
|
70 |
+
|
71 |
+
with gr.Blocks(css=css) as demo:
|
72 |
+
with gr.Row():
|
73 |
+
with gr.Column():
|
74 |
+
gr.HTML(
|
75 |
+
"""
|
76 |
+
<h1 style='text-align: center; font-size: 3.2em; margin-bottom: 0.5em; font-family: Arial, sans-serif; margin: 20px;'>
|
77 |
+
Video Diffusion Alignment via Reward Gradient
|
78 |
+
</h1>
|
79 |
+
"""
|
80 |
+
)
|
81 |
+
gr.HTML(
|
82 |
+
"""
|
83 |
+
<style>
|
84 |
+
body {
|
85 |
+
font-family: Arial, sans-serif;
|
86 |
+
text-align: center;
|
87 |
+
margin: 50px;
|
88 |
+
}
|
89 |
+
a {
|
90 |
+
text-decoration: none !important;
|
91 |
+
color: black !important;
|
92 |
+
}
|
93 |
+
|
94 |
+
</style>
|
95 |
+
<body>
|
96 |
+
<div style="font-size: 1.4em; margin-bottom: 0.5em; ">
|
97 |
+
<a href="https://mihirp1998.github.io">Mihir Prabhudesai</a><sup>*</sup>
|
98 |
+
<a href="https://russellmendonca.github.io/">Russell Mendonca</a><sup>*</sup>
|
99 |
+
<a href="mailto: [email protected]">Zheyang Qin</a><sup>*</sup>
|
100 |
+
<a href="https://www.cs.cmu.edu/~katef/">Katerina Fragkiadaki</a><sup></sup>
|
101 |
+
<a href="https://www.cs.cmu.edu/~dpathak/">Deepak Pathak</a><sup></sup>
|
102 |
+
|
103 |
+
|
104 |
+
</div>
|
105 |
+
<div style="font-size: 1.3em; font-style: italic;">
|
106 |
+
Carnegie Mellon University
|
107 |
+
</div>
|
108 |
+
</body>
|
109 |
+
"""
|
110 |
+
)
|
111 |
+
gr.HTML(
|
112 |
+
"""
|
113 |
+
<head>
|
114 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
115 |
+
|
116 |
+
<style>
|
117 |
+
.button-container {
|
118 |
+
display: flex;
|
119 |
+
justify-content: center;
|
120 |
+
gap: 10px;
|
121 |
+
margin-top: 10px;
|
122 |
+
}
|
123 |
+
|
124 |
+
.button-container a {
|
125 |
+
display: inline-flex;
|
126 |
+
align-items: center;
|
127 |
+
padding: 10px 20px;
|
128 |
+
border-radius: 30px;
|
129 |
+
border: 1px solid #ccc;
|
130 |
+
text-decoration: none;
|
131 |
+
color: #333 !important;
|
132 |
+
font-size: 16px;
|
133 |
+
text-decoration: none !important;
|
134 |
+
}
|
135 |
+
|
136 |
+
.button-container a i {
|
137 |
+
margin-right: 8px;
|
138 |
+
}
|
139 |
+
</style>
|
140 |
+
</head>
|
141 |
+
|
142 |
+
<div class="button-container">
|
143 |
+
<a href="https://arxiv.org/abs/2407.08737" class="btn btn-outline-primary">
|
144 |
+
<i class="fa-solid fa-file-pdf"></i> Paper
|
145 |
+
</a>
|
146 |
+
<a href="https://vader-vid.github.io/" class="btn btn-outline-danger">
|
147 |
+
<i class="fa-solid fa-video"></i> Website
|
148 |
+
<a href="https://github.com/mihirp1998/VADER" class="btn btn-outline-secondary">
|
149 |
+
<i class="fa-brands fa-github"></i> Code
|
150 |
+
</a>
|
151 |
+
</div>
|
152 |
+
"""
|
153 |
+
)
|
154 |
+
|
155 |
+
with gr.Row(elem_classes="centered"):
|
156 |
+
with gr.Column(scale=0.6):
|
157 |
+
output_video = gr.Video()
|
158 |
+
|
159 |
+
with gr.Row():
|
160 |
+
lora_model = gr.Dropdown(
|
161 |
+
label="VADER Model",
|
162 |
+
choices=["huggingface-pickscore", "huggingface-hps-aesthetic", "Base Model"],
|
163 |
+
value="huggingface-pickscore"
|
164 |
+
)
|
165 |
+
lora_rank = gr.Slider(minimum=0, maximum=16, label="LoRA Rank", step = 8, value=16)
|
166 |
+
load_btn = gr.Button("Load Model")
|
167 |
+
# Add a label to show the loading indicator
|
168 |
+
loading_indicator = gr.Label(value="", label="Loading Indicator")
|
169 |
+
|
170 |
+
prompt = gr.Textbox(placeholder="Enter prompt text here", lines=4, label="Text Prompt",
|
171 |
+
value="A mermaid with flowing hair and a shimmering tail discovers a hidden underwater kingdom adorned with coral palaces, glowing pearls, and schools of colorful fish, encountering both wonders and dangers along the way.")
|
172 |
+
|
173 |
+
seed = gr.Slider(minimum=0, maximum=65536, label="Seed", step = 1, value=200)
|
174 |
+
|
175 |
+
run_btn = gr.Button("Run Inference")
|
176 |
+
|
177 |
+
|
178 |
+
with gr.Row():
|
179 |
+
height = gr.Slider(minimum=0, maximum=1024, label="Height", step = 16, value=320)
|
180 |
+
width = gr.Slider(minimum=0, maximum=1024, label="Width", step = 16, value=512)
|
181 |
+
|
182 |
+
with gr.Row():
|
183 |
+
frames = gr.Slider(minimum=0, maximum=50, label="Frames", step = 1, value=24)
|
184 |
+
savefps = gr.Slider(minimum=0, maximum=60, label="Save FPS", step = 1, value=10)
|
185 |
+
|
186 |
+
|
187 |
+
with gr.Row():
|
188 |
+
DDIM_Steps = gr.Slider(minimum=0, maximum=100, label="DDIM Steps", step = 1, value=25)
|
189 |
+
unconditional_guidance_scale = gr.Slider(minimum=0, maximum=50, label="Guidance Scale", step = 0.1, value=12.0)
|
190 |
+
DDIM_Eta = gr.Slider(minimum=0, maximum=1, label="DDIM Eta", step = 0.01, value=1.0)
|
191 |
+
|
192 |
+
# reset button
|
193 |
+
reset_btn = gr.Button("Reset")
|
194 |
+
|
195 |
+
reset_btn.click(fn=reset_fn, outputs=[prompt, seed, height, width, unconditional_guidance_scale, DDIM_Steps, DDIM_Eta, frames, lora_rank, savefps, lora_model])
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
load_btn.click(fn=setup_model_progress, inputs=[lora_model, lora_rank], outputs=[load_btn, run_btn, reset_btn, loading_indicator])
|
200 |
+
run_btn.click(fn=gradio_main_fn,
|
201 |
+
inputs=[prompt, seed, height, width, unconditional_guidance_scale, DDIM_Steps, DDIM_Eta, frames, savefps],
|
202 |
+
outputs=output_video
|
203 |
+
)
|
204 |
+
|
205 |
+
lora_model.change(fn=update_lora_rank, inputs=lora_model, outputs=lora_rank)
|
206 |
+
lora_rank.change(fn=update_dropdown, inputs=lora_rank, outputs=lora_model)
|
207 |
+
|
208 |
+
demo.launch()
|
209 |
+
|
210 |
+
# main_fn(prompt="A mermaid with flowing hair and a shimmering tail discovers a hidden underwater kingdom adorned with coral palaces, glowing pearls, and schools of colorful fish, encountering both wonders and dangers along the way.",)
|
assets/activities.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
washing the dishes
|
2 |
+
riding a bike
|
3 |
+
playing chess
|
assets/chatgpt_custom.txt
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A dog catching a red frisbee in mid-air with the sun setting behind, casting a golden glow.
|
2 |
+
A dog fetching a stick thrown into a crystal-clear lake surrounded by trees.
|
3 |
+
A dog running alongside a bicycle on a park trail lined with golden autumn leaves.
|
4 |
+
A dog leaping over a fence to catch a ball in a yard illuminated by string lights.
|
5 |
+
A dog performing agility course obstacles with precision in a park decorated with lanterns.
|
6 |
+
A dog running through a tunnel on an agility course with soft, colorful lighting.
|
7 |
+
A dog playing tug-of-war with a human in the backyard under a canopy of twinkling lights.
|
8 |
+
A dog retrieving a ball from the water in a pond surrounded by blooming lilies.
|
9 |
+
A dog weaving through poles on an agility course with soft lighting creating a magical atmosphere.
|
10 |
+
A dog running to catch a thrown toy in the air with vibrant flowers in the background.
|
11 |
+
A dog diving into a pool to retrieve a toy with sunlight sparkling on the water.
|
12 |
+
A dog catching a ball on the run during a game of fetch in a picturesque park.
|
13 |
+
A dog jumping through a hoop in an agility course with colorful flags.
|
14 |
+
A dog playing with a toy in a garden filled with blooming flowers.
|
15 |
+
A dog retrieving a frisbee from the air in a park under a bright blue sky.
|
16 |
+
A dog running at full speed across a field with a rainbow overhead.
|
17 |
+
A dog chasing a thrown stick in a field with golden sunlight.
|
18 |
+
A dog performing tricks in a park filled with children and laughter.
|
19 |
+
A dog chasing its tail in a backyard with colorful flowers.
|
20 |
+
A dog cuddling with a human under a tree with soft, ambient lighting.
|
21 |
+
A dog and cat playing together in a garden with soft morning light filtering through the trees.
|
22 |
+
A dog and cat chasing each other around the living room with fairy lights twinkling.
|
23 |
+
A dog and cat lounging together under a tree with soft, ambient lighting.
|
24 |
+
A dog and cat playing with a toy in a cozy, warmly lit room.
|
25 |
+
A dog and cat cuddling with a human on a couch with a fireplace glowing.
|
26 |
+
A cat jumping onto a high shelf to reach a dangling toy mouse, with soft light filtering through the window.
|
27 |
+
A cat chasing a laser pointer around the living room with fairy lights twinkling in the background.
|
28 |
+
A cat climbing up a curtain to reach a window ledge overlooking a moonlit garden.
|
29 |
+
A cat playing with a toy on a string hanging from a door, with soft ambient lighting creating a cozy atmosphere.
|
30 |
+
A cat pouncing on a moving object on the floor with gentle candlelight flickering nearby.
|
31 |
+
A cat batting at a moving object on a string, with a fireplace crackling in the background.
|
32 |
+
A cat chasing after a butterfly in the garden with soft morning light filtering through the trees.
|
33 |
+
A cat stalking a bird from behind a bush in the yard, with evening light casting long shadows.
|
34 |
+
A cat swiping at a moving toy on the floor with a cozy, warmly lit room.
|
35 |
+
A cat jumping from one surface to another on a bookshelf with soft lighting.
|
36 |
+
A cat chasing a toy car on the floor with sunlight streaming through the window.
|
37 |
+
A cat leaping to catch a feather toy hanging from a door with sunlight streaming in.
|
38 |
+
A cat playing with a ball in the living room with soft ambient lighting.
|
39 |
+
A cat batting at a dangling feather toy in a cozy, warmly lit room.
|
40 |
+
A cat chasing a string in a room filled with soft, ambient light.
|
41 |
+
A cat playing hide and seek with a toy in the living room with a warm glow.
|
42 |
+
A cat lounging in a sunbeam with a toy nearby.
|
43 |
+
A cat curling up in a cozy bed with soft ambient light around.
|
44 |
+
A cat playing with a small ball in a room with a warm, inviting atmosphere.
|
45 |
+
A cat and dog playing together in a garden with soft morning light filtering through the trees.
|
46 |
+
A cat and dog chasing each other around the living room with fairy lights twinkling.
|
47 |
+
A cat and dog lounging together under a tree with soft, ambient lighting.
|
48 |
+
A cat and dog playing with a toy in a cozy, warmly lit room.
|
49 |
+
A cat and dog cuddling with a human on a couch with a fireplace glowing.
|
50 |
+
A cat jumping onto a high shelf to reach a dangling toy mouse, with soft light filtering through the window.
|
assets/chatgpt_custom_actpred.txt
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A young girl playing the piano in a cozy living room.
|
2 |
+
A boy playing guitar on a sunny beach.
|
3 |
+
A woman chopping wood in a forest.
|
4 |
+
A girl jogging along a scenic trail.
|
5 |
+
A boy playing the piano in a school auditorium.
|
6 |
+
A young woman playing guitar by a campfire.
|
7 |
+
A woman jogging in a park at sunrise.
|
8 |
+
A young girl chopping wood in a rustic backyard.
|
9 |
+
A boy jogging along a beach at sunset.
|
10 |
+
A man playing the piano in a modern living room.
|
11 |
+
A woman playing guitar at a local music festival.
|
12 |
+
A boy chopping wood in a snowy forest.
|
13 |
+
A young man jogging through a busy city street.
|
14 |
+
A woman playing the piano in an elegant ballroom.
|
15 |
+
A man playing guitar in a cozy café.
|
16 |
+
A boy jogging on a mountain trail.
|
17 |
+
A young girl playing the piano in a music classroom.
|
18 |
+
A man chopping wood in a rural countryside.
|
19 |
+
A woman jogging along a riverbank.
|
20 |
+
A boy playing guitar on a rooftop terrace.
|
21 |
+
A young man chopping wood in a quiet forest.
|
22 |
+
A woman playing the piano in a beautifully decorated hall.
|
23 |
+
A man jogging in a suburban neighborhood.
|
24 |
+
A girl playing guitar at a summer camp.
|
25 |
+
A young woman jogging on a scenic beach.
|
26 |
+
A man playing the piano at a fancy restaurant.
|
27 |
+
A woman chopping wood in her backyard.
|
28 |
+
A young girl jogging in a peaceful park.
|
29 |
+
A boy playing guitar in a busy city square.
|
30 |
+
A woman playing guitar in a cozy living room.
|
31 |
+
A girl jogging through a bustling market.
|
32 |
+
A boy playing the piano at a local talent show.
|
33 |
+
A young man chopping wood at a cabin retreat.
|
34 |
+
A young girl jogging in a colorful garden.
|
35 |
+
A man playing guitar at a rooftop party.
|
36 |
+
A woman playing the piano in a vintage-style parlor.
|
37 |
+
A boy chopping wood on a farm.
|
38 |
+
A young man jogging in an urban park.
|
39 |
+
A woman playing guitar in a chic coffee shop.
|
40 |
+
A man jogging along a cliffside trail.
|
41 |
+
A young girl playing the piano in a sunlit room.
|
assets/chatgpt_custom_actpred2.txt
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A young girl playing the piano in a cozy living room.
|
2 |
+
A boy playing guitar on a sunny beach.
|
3 |
+
A man playing the violin in a bustling city square.
|
4 |
+
A woman chopping wood in a forest.
|
5 |
+
A girl jogging along a scenic trail.
|
6 |
+
A boy playing the piano in a school auditorium.
|
7 |
+
A young woman playing guitar by a campfire.
|
8 |
+
A man playing the violin in a grand concert hall.
|
9 |
+
A woman jogging in a park at sunrise.
|
10 |
+
A young girl chopping wood in a rustic backyard.
|
11 |
+
A boy jogging along a beach at sunset.
|
12 |
+
A man playing the piano in a modern living room.
|
13 |
+
A woman playing guitar at a local music festival.
|
14 |
+
A young girl playing the violin in a tranquil garden.
|
15 |
+
A boy chopping wood in a snowy forest.
|
16 |
+
A young man jogging through a busy city street.
|
17 |
+
A woman playing the piano in an elegant ballroom.
|
18 |
+
A man playing guitar in a cozy café.
|
19 |
+
A girl playing the violin in a historic church.
|
20 |
+
A boy jogging on a mountain trail.
|
21 |
+
A young girl playing the piano in a music classroom.
|
22 |
+
A man chopping wood in a rural countryside.
|
23 |
+
A woman jogging along a riverbank.
|
24 |
+
A boy playing guitar on a rooftop terrace.
|
25 |
+
A young girl playing the violin in a flower-filled meadow.
|
26 |
+
A young man chopping wood in a quiet forest.
|
27 |
+
A woman playing the piano in a beautifully decorated hall.
|
28 |
+
A man jogging in a suburban neighborhood.
|
29 |
+
A girl playing guitar at a summer camp.
|
30 |
+
A boy playing the violin in a quaint library.
|
31 |
+
A young woman jogging on a scenic beach.
|
32 |
+
A man playing the piano at a fancy restaurant.
|
33 |
+
A woman chopping wood in her backyard.
|
34 |
+
A young girl jogging in a peaceful park.
|
35 |
+
A boy playing guitar in a busy city square.
|
36 |
+
A man playing the violin in a modern art gallery.
|
37 |
+
A woman playing guitar in a cozy living room.
|
38 |
+
A girl jogging through a bustling market.
|
39 |
+
A boy playing the piano at a local talent show.
|
40 |
+
A young man chopping wood at a cabin retreat.
|
41 |
+
A woman playing the violin on a balcony overlooking a city.
|
42 |
+
A young girl jogging in a colorful garden.
|
43 |
+
A man playing guitar at a rooftop party.
|
44 |
+
A woman playing the piano in a vintage-style parlor.
|
45 |
+
A boy chopping wood on a farm.
|
46 |
+
A girl playing the violin in a serene forest.
|
47 |
+
A young man jogging in an urban park.
|
48 |
+
A woman playing guitar in a chic coffee shop.
|
49 |
+
A man jogging along a cliffside trail.
|
50 |
+
A young girl playing the piano in a sunlit room.
|
assets/chatgpt_custom_animal.txt
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A happy dog running in a sunny park, with children playing in the background and birds flying above.
|
2 |
+
A cozy cat sleeping on a couch, surrounded by soft pillows and a warm blanket, with a gentle breeze coming through an open window.
|
3 |
+
A graceful bird flying across a clear blue sky, with fluffy white clouds and distant mountains in the background.
|
4 |
+
An excited dog fetching a bright red frisbee and bringing it back to its smiling owner in a green park.
|
5 |
+
A curious cat climbing a tall tree to chase a quick squirrel in a thick forest.
|
6 |
+
A big elephant spraying water with its trunk, making a rainbow in the bright sunlight at a calm waterhole.
|
7 |
+
A friendly dog playing with a curious cat in a colorful garden full of blooming flowers and buzzing bees.
|
8 |
+
A busy bird feeding its hungry chicks in a cozy nest on a tall tree, with the morning sun shining.
|
9 |
+
A strong lion and a graceful lioness resting together in the shade of a big tree on a wide grassland.
|
10 |
+
A playful penguin sliding down a snowy hill with its friends, the snow sparkling under a bright winter sun.
|
11 |
+
A clever monkey riding a small bicycle through a lively village, drawing the amazed looks of local children.
|
12 |
+
A tall giraffe bending down to drink water from a clear river, surrounded by green trees and colorful birds.
|
13 |
+
A majestic whale swimming in the deep blue ocean during a beautiful sunset, with the sky painted in orange and pink colors.
|
14 |
+
A peaceful deer eating grass in a thick forest, with sunlight filtering through the trees creating a magical feeling.
|
15 |
+
A determined turtle crawling on a sandy beach, with waves gently crashing in the background under a bright, clear sky.
|
16 |
+
A joyful dog playing in the snow, leaving paw prints and trying to catch snowflakes on its nose.
|
17 |
+
A cautious cat hiding from the rain under a tree, its fur slightly wet and raindrops making ripples in puddles.
|
18 |
+
A lively horse running through a field of blooming flowers in spring, the landscape full of colors and sweet smells.
|
19 |
+
A sad puppy looking sorry after being scolded, its ears down and eyes wet with tears in a quiet room.
|
20 |
+
An excited kitten playing with a ball of yarn, moving quickly and nimbly, in a cozy living room full of toys.
|
21 |
+
A curious elephant exploring its surroundings, its trunk gently touching things and eyes wide with wonder in a dense jungle.
|
22 |
+
A group of dolphins jumping out of the water, the sun setting behind them and casting a golden light on the waves.
|
23 |
+
A flock of birds flying during autumn, with colorful leaves swirling around them in the cool air.
|
24 |
+
A content panda eating bamboo in a peaceful forest, with a gentle waterfall flowing in the background.
|
assets/chatgpt_custom_animal_action.txt
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Cat riding a skateboard.
|
2 |
+
Dog riding a skateboard.
|
3 |
+
Rabbit riding a skateboard.
|
4 |
+
Raccoon riding a skateboard.
|
5 |
+
Monkey riding a skateboard.
|
6 |
+
Hedgehog riding a skateboard.
|
7 |
+
Bat riding a skateboard.
|
8 |
+
Mouse riding a skateboard.
|
9 |
+
Cat working on a laptop.
|
10 |
+
Dog working on a laptop.
|
11 |
+
Rabbit working on a laptop.
|
12 |
+
Raccoon working on a laptop.
|
13 |
+
Monkey working on a laptop.
|
14 |
+
Hedgehog working on a laptop.
|
15 |
+
Bat working on a laptop.
|
16 |
+
Mouse working on a laptop.
|
17 |
+
Cat reading a book.
|
18 |
+
Dog reading a book.
|
19 |
+
Rabbit reading a book.
|
20 |
+
Raccoon reading a book.
|
21 |
+
Monkey reading a book.
|
22 |
+
Hedgehog reading a book.
|
23 |
+
Bat reading a book.
|
24 |
+
Mouse reading a book.
|
25 |
+
Cat eating an apple.
|
26 |
+
Dog eating an apple.
|
27 |
+
Rabbit eating an apple.
|
28 |
+
Raccoon eating an apple.
|
29 |
+
Monkey eating an apple.
|
30 |
+
Hedgehog eating an apple.
|
31 |
+
Bat eating an apple.
|
32 |
+
Mouse eating an apple.
|
33 |
+
Cat eating watermelon.
|
34 |
+
Dog eating watermelon.
|
35 |
+
Rabbit eating watermelon.
|
36 |
+
Raccoon eating watermelon.
|
37 |
+
Monkey eating watermelon.
|
38 |
+
Hedgehog eating watermelon.
|
39 |
+
Bat eating watermelon.
|
40 |
+
Mouse eating watermelon.
|
assets/chatgpt_custom_animal_clothes.txt
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A dog in a red shirt, running in a park.
|
2 |
+
A cat in a blue shirt, sitting on a windowsill.
|
3 |
+
A rabbit in a green shirt, pretending to cook.
|
4 |
+
A bear in a yellow shirt, splashing in puddles.
|
5 |
+
A penguin in a red scarf, waddling on ice.
|
6 |
+
A squirrel in a blue scarf, collecting acorns.
|
7 |
+
A monkey in a green scarf, juggling balls.
|
8 |
+
A lion in a yellow scarf, sitting on a rock.
|
9 |
+
A dolphin in a red hat, jumping out of the water.
|
10 |
+
A turtle in a blue hat, relaxing on a beach.
|
11 |
+
A dog in a firefighter hat, standing by a toy fire truck.
|
12 |
+
A cat in a ballet hat, practicing dance moves.
|
13 |
+
A rabbit in a magician's hat, pulling a carrot from a hat.
|
14 |
+
A bear in a cowboy hat, pretending to chop wood.
|
15 |
+
A penguin in a Santa hat, sliding on ice.
|
16 |
+
A squirrel in a knight's hat, holding a tiny sword.
|
17 |
+
A monkey in a detective hat, holding a magnifying glass.
|
18 |
+
A lion in a wizard's hat, looking at the stars.
|
19 |
+
A dolphin in a red shirt, hitting a ball with its nose.
|
20 |
+
A turtle in a blue shirt, holding a small wand.
|
21 |
+
A dog in a green shirt, skateboarding in a park.
|
22 |
+
A cat in a yellow shirt, sleeping on a bed.
|
23 |
+
A rabbit in a red shirt, picking flowers.
|
24 |
+
A bear in a blue shirt, fishing by a river.
|
25 |
+
A penguin in a green shirt, walking to an office.
|
26 |
+
A squirrel in a yellow shirt, collecting nuts.
|
27 |
+
A monkey in a red shirt, playing on a jungle gym.
|
28 |
+
A lion in a blue shirt, playing catch.
|
29 |
+
A dolphin in a green shirt, swimming near a boat.
|
30 |
+
A turtle in a yellow shirt, hiking on a trail.
|
31 |
+
A dog in a red hat, walking down an aisle.
|
32 |
+
A cat in a blue hat, sitting at a table.
|
33 |
+
A rabbit in a green hat, holding a diploma.
|
34 |
+
A bear in a yellow hat, trick-or-treating.
|
35 |
+
A penguin in a red scarf, decorating a Christmas tree.
|
36 |
+
A squirrel in a blue scarf, celebrating a birthday.
|
37 |
+
A monkey in a green scarf, holding confetti.
|
38 |
+
A lion in a yellow scarf, sitting by a cake.
|
39 |
+
A dolphin in a red hat, jumping in a pool.
|
40 |
+
A turtle in a blue hat, at a garden party.
|
41 |
+
A dog in a red jacket, playing in the snow.
|
42 |
+
A cat in a blue jacket, lounging under an umbrella.
|
43 |
+
A rabbit in a green jacket, hopping in a garden.
|
44 |
+
A bear in a yellow jacket, sitting by a campfire.
|
45 |
+
A penguin in a red jacket, skating on ice.
|
46 |
+
A squirrel in a blue jacket, enjoying a sunny day.
|
47 |
+
A monkey in a green jacket, swinging from trees.
|
48 |
+
A lion in a yellow jacket, building a sandcastle.
|
49 |
+
A dolphin in a red jacket, jumping through hoops.
|
50 |
+
A turtle in a blue jacket, celebrating a holiday.
|
assets/chatgpt_custom_animal_clothesV2.txt
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The dog is wearing a red shirt and eating from a bowl.
|
2 |
+
The cat is wearing a blue shirt and playing with yarn.
|
3 |
+
The rabbit is wearing a green shirt and reading a book.
|
4 |
+
The bear is wearing a yellow shirt and painting a picture.
|
5 |
+
The raccoon is wearing a red dress and sliding down a tree.
|
6 |
+
The squirrel is wearing a blue dress and holding a nut.
|
7 |
+
The monkey is wearing a green dress and climbing a tree.
|
8 |
+
The lion is wearing a yellow dress and lying on a rock.
|
9 |
+
The fox is wearing a red hat and balancing a ball.
|
10 |
+
The panda is wearing a blue hat and looking at flowers.
|
11 |
+
The dog is wearing a firefighter hat and holding a hose.
|
12 |
+
The cat is wearing a ballet hat and standing on one foot.
|
13 |
+
The rabbit is wearing a magician's hat and holding a wand.
|
14 |
+
The bear is wearing a cowboy hat and tipping its hat.
|
15 |
+
The raccoon is wearing a Santa hat and carrying a gift.
|
16 |
+
The squirrel is wearing a knight's hat and holding a toy sword.
|
17 |
+
The monkey is wearing a detective hat and looking through a magnifying glass.
|
18 |
+
The lion is wearing a wizard's hat and holding a book.
|
19 |
+
The fox is wearing a red shirt and splashing water.
|
20 |
+
The panda is wearing a blue shirt and blowing bubbles.
|
21 |
+
The dog is wearing a green shirt and digging a hole.
|
22 |
+
The cat is wearing a yellow shirt and napping on a cushion.
|
23 |
+
The rabbit is wearing a red shirt and watering plants.
|
24 |
+
The bear is wearing a blue shirt and eating honey.
|
25 |
+
The raccoon is wearing a green shirt and building a small fort.
|
26 |
+
The squirrel is wearing a yellow shirt and sitting on a branch.
|
27 |
+
The monkey is wearing a red shirt and peeling a banana.
|
28 |
+
The lion is wearing a blue shirt and looking at the sky.
|
29 |
+
The fox is wearing a green shirt and sitting in a garden.
|
30 |
+
The panda is wearing a yellow shirt and walking in a forest
|
31 |
+
The dog is wearing a red hat and carrying a flower.
|
32 |
+
The cat is wearing a blue hat and sitting at a table.
|
33 |
+
The rabbit is wearing a green hat and holding a diploma.
|
34 |
+
The bear is wearing a yellow hat and holding a pumpkin.
|
35 |
+
The raccoon is wearing a red dress and hanging ornaments.
|
36 |
+
The squirrel is wearing a blue dress and eating cake.
|
37 |
+
The monkey is wearing a green dress and blowing a whistle.
|
38 |
+
The lion is wearing a yellow dress and standing next to a cake.
|
39 |
+
The fox is wearing a red hat and playing with leaves.
|
40 |
+
The panda is wearing a blue hat and holding a balloon.
|
41 |
+
The dog is wearing a red coat and sniffing the snow.
|
42 |
+
The cat is wearing a blue coat and sunbathing.
|
43 |
+
The rabbit is wearing a green coat and picking flowers.
|
44 |
+
The bear is wearing a yellow coat and roasting marshmallows.
|
45 |
+
The raccoon is wearing a red coat and holding a snowball.
|
46 |
+
The squirrel is wearing a blue coat and looking at leaves.
|
47 |
+
The monkey is wearing a green coat and eating fruit.
|
48 |
+
The lion is wearing a yellow coat and digging in the sand.
|
49 |
+
The fox is wearing a red coat and jumping in a pile of leaves.
|
50 |
+
The panda is wearing a blue coat and sitting by a fire.
|
assets/chatgpt_custom_animal_clothesV3.txt
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Cat in a red jacket
|
2 |
+
Cat in a blue jacket
|
3 |
+
Cat in a yellow jacket
|
4 |
+
Cat in a black jacket
|
5 |
+
Cat in a red shirt
|
6 |
+
Cat in a blue shirt
|
7 |
+
Cat in a yellow shirt
|
8 |
+
Cat in a black shirt
|
9 |
+
Cat in a red dress
|
10 |
+
Cat in a blue dress
|
11 |
+
Cat in a yellow dress
|
12 |
+
Cat in a black dress
|
13 |
+
Dog in a red jacket
|
14 |
+
Dog in a blue jacket
|
15 |
+
Dog in a yellow jacket
|
16 |
+
Dog in a black jacket
|
17 |
+
Dog in a red shirt
|
18 |
+
Dog in a blue shirt
|
19 |
+
Dog in a yellow shirt
|
20 |
+
Dog in a black shirt
|
21 |
+
Dog in a red dress
|
22 |
+
Dog in a blue dress
|
23 |
+
Dog in a yellow dress
|
24 |
+
Dog in a black dress
|
25 |
+
Rabbit in a red jacket
|
26 |
+
Rabbit in a blue jacket
|
27 |
+
Rabbit in a yellow jacket
|
28 |
+
Rabbit in a black jacket
|
29 |
+
Rabbit in a red shirt
|
30 |
+
Rabbit in a blue shirt
|
31 |
+
Rabbit in a yellow shirt
|
32 |
+
Rabbit in a black shirt
|
33 |
+
Rabbit in a red dress
|
34 |
+
Rabbit in a blue dress
|
35 |
+
Rabbit in a yellow dress
|
36 |
+
Rabbit in a black dress
|
37 |
+
Raccoon in a red jacket
|
38 |
+
Raccoon in a blue jacket
|
39 |
+
Raccoon in a yellow jacket
|
40 |
+
Raccoon in a black jacket
|
41 |
+
Raccoon in a red shirt
|
42 |
+
Raccoon in a blue shirt
|
43 |
+
Raccoon in a yellow shirt
|
44 |
+
Raccoon in a black shirt
|
45 |
+
Raccoon in a red dress
|
46 |
+
Raccoon in a blue dress
|
47 |
+
Raccoon in a yellow dress
|
48 |
+
Raccoon in a black dress
|
49 |
+
Monkey in a red jacket
|
50 |
+
Monkey in a blue jacket
|
51 |
+
Monkey in a yellow jacket
|
52 |
+
Monkey in a black jacket
|
53 |
+
Monkey in a red shirt
|
54 |
+
Monkey in a blue shirt
|
55 |
+
Monkey in a yellow shirt
|
56 |
+
Monkey in a black shirt
|
57 |
+
Monkey in a red dress
|
58 |
+
Monkey in a blue dress
|
59 |
+
Monkey in a yellow dress
|
60 |
+
Monkey in a black dress
|
61 |
+
Hedgehog in a red jacket
|
62 |
+
Hedgehog in a blue jacket
|
63 |
+
Hedgehog in a yellow jacket
|
64 |
+
Hedgehog in a black jacket
|
65 |
+
Hedgehog in a red shirt
|
66 |
+
Hedgehog in a blue shirt
|
67 |
+
Hedgehog in a yellow shirt
|
68 |
+
Hedgehog in a black shirt
|
69 |
+
Hedgehog in a red dress
|
70 |
+
Hedgehog in a blue dress
|
71 |
+
Hedgehog in a yellow dress
|
72 |
+
Hedgehog in a black dress
|
73 |
+
Mouse in a red jacket
|
74 |
+
Mouse in a blue jacket
|
75 |
+
Mouse in a yellow jacket
|
76 |
+
Mouse in a black jacket
|
77 |
+
Mouse in a red shirt
|
78 |
+
Mouse in a blue shirt
|
79 |
+
Mouse in a yellow shirt
|
80 |
+
Mouse in a black shirt
|
81 |
+
Mouse in a red dress
|
82 |
+
Mouse in a blue dress
|
83 |
+
Mouse in a yellow dress
|
84 |
+
Mouse in a black dress
|
85 |
+
Panda in a red jacket
|
86 |
+
Panda in a blue jacket
|
87 |
+
Panda in a yellow jacket
|
88 |
+
Panda in a black jacket
|
89 |
+
Panda in a red shirt
|
90 |
+
Panda in a blue shirt
|
91 |
+
Panda in a yellow shirt
|
92 |
+
Panda in a black shirt
|
93 |
+
Panda in a red dress
|
94 |
+
Panda in a blue dress
|
95 |
+
Panda in a yellow dress
|
96 |
+
Panda in a black dress
|
assets/chatgpt_custom_animal_housework.txt
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The monkey is watering the plants.
|
2 |
+
The raccoon is vacuuming the carpet.
|
3 |
+
The cat is sweeping the floor.
|
4 |
+
The rabbit is wiping the windows.
|
5 |
+
The hedgehog is washing the car.
|
6 |
+
The dog is wiping the dining table.
|
7 |
+
The bat is dusting the shelves.
|
8 |
+
The monkey is watering the garden.
|
9 |
+
The raccoon is vacuuming the stairs.
|
10 |
+
The cat is sweeping the porch.
|
11 |
+
The rabbit is wiping the windowsills.
|
12 |
+
The hedgehog is washing the car windows.
|
13 |
+
The dog is wiping the kitchen table.
|
14 |
+
The bat is dusting the bookshelf.
|
15 |
+
The monkey is watering the indoor plants.
|
16 |
+
The raccoon is vacuuming the bedroom.
|
17 |
+
The cat is sweeping the garage.
|
18 |
+
The rabbit is wiping the patio doors.
|
19 |
+
The hedgehog is washing the car hood.
|
20 |
+
The dog is wiping the coffee table.
|
21 |
+
The bat is dusting the mantle.
|
22 |
+
The monkey is watering the hanging plants.
|
23 |
+
The raccoon is vacuuming the living room rug.
|
24 |
+
The cat is sweeping the basement.
|
25 |
+
The rabbit is wiping the bedroom windows.
|
26 |
+
The hedgehog is washing the car tires.
|
27 |
+
The dog is wiping the side table.
|
28 |
+
The bat is dusting the picture frames.
|
29 |
+
The monkey is watering the flower pots.
|
30 |
+
The raccoon is vacuuming the hallway.
|
31 |
+
The cat is sweeping the deck.
|
32 |
+
The rabbit is wiping the kitchen windows.
|
33 |
+
The hedgehog is washing the car bumper.
|
34 |
+
The dog is wiping the dining chairs.
|
35 |
+
The bat is dusting the TV stand.
|
36 |
+
The monkey is watering the balcony plants.
|
37 |
+
The raccoon is vacuuming the study.
|
38 |
+
The cat is sweeping the driveway.
|
39 |
+
The rabbit is wiping the glass doors.
|
40 |
+
The hedgehog is washing the car rear window.
|
41 |
+
The dog is wiping the dining table before dinner.
|
42 |
+
The bat is dusting the living room shelves.
|
43 |
+
The monkey is watering the backyard garden.
|
44 |
+
The raccoon is vacuuming the hallway carpet.
|
45 |
+
The cat is sweeping the patio.
|
46 |
+
The rabbit is wiping the sliding doors.
|
47 |
+
The hedgehog is washing the car front grille.
|
48 |
+
The dog is wiping the kitchen table after a meal.
|
49 |
+
The bat is dusting the study shelves.
|
50 |
+
The monkey is watering the windowsill plants.
|
51 |
+
The raccoon is vacuuming the nursery.
|
52 |
+
The cat is sweeping the front porch.
|
53 |
+
The rabbit is wiping the exterior windows.
|
54 |
+
The hedgehog is washing the car side mirrors.
|
55 |
+
The dog is wiping the dining table after dinner.
|
56 |
+
The bat is dusting the bedroom nightstands.
|
57 |
+
The monkey is watering the kitchen herb garden.
|
58 |
+
The raccoon is vacuuming the playroom.
|
59 |
+
The cat is sweeping the mudroom.
|
60 |
+
The rabbit is wiping the windows with a squeegee.
|
61 |
+
The hedgehog is washing the car headlights.
|
62 |
+
The dog is wiping the dining table after breakfast.
|
63 |
+
The bat is dusting the entertainment center.
|
64 |
+
The monkey is watering the sunroom plants.
|
65 |
+
The raccoon is vacuuming the family room.
|
66 |
+
The cat is sweeping the garden shed.
|
67 |
+
The rabbit is wiping the windows in the family room.
|
68 |
+
The hedgehog is washing the car roof.
|
69 |
+
The dog is wiping the living room table.
|
70 |
+
The bat is dusting the home office shelves.
|
71 |
+
The monkey is watering the front yard flowers.
|
72 |
+
The raccoon is vacuuming the home theater.
|
73 |
+
The cat is sweeping the steps.
|
74 |
+
The rabbit is wiping the kitchen windows with a sponge.
|
75 |
+
The hedgehog is washing the car front bumper.
|
76 |
+
The dog is wiping the dining table after lunch.
|
77 |
+
The bat is dusting the mantelpiece.
|
78 |
+
The monkey is watering the windowsill herbs.
|
79 |
+
The raccoon is vacuuming the dining room.
|
80 |
+
The cat is sweeping the entryway.
|
81 |
+
The rabbit is wiping the interior windows.
|
82 |
+
The hedgehog is washing the car fenders.
|
83 |
+
The dog is wiping the dining table before a meal.
|
84 |
+
The bat is dusting the entertainment center.
|
85 |
+
The monkey is watering the patio plants.
|
86 |
+
The raccoon is vacuuming the basement.
|
87 |
+
The cat is sweeping the sidewalk.
|
88 |
+
The rabbit is wiping the blinds.
|
89 |
+
The hedgehog is washing the car tires.
|
90 |
+
The dog is wiping the kitchen table before setting it.
|
91 |
+
The bat is dusting the bookshelf.
|
92 |
+
The monkey is watering the office plants.
|
93 |
+
The raccoon is vacuuming the guest room.
|
94 |
+
The cat is sweeping the garden shed.
|
95 |
+
The rabbit is wiping the playroom windows.
|
96 |
+
The hedgehog is washing the car roof.
|
97 |
+
The dog is wiping the dining table after breakfast.
|
98 |
+
The bat is dusting the picture frames.
|
99 |
+
The monkey is watering the porch plants.
|
100 |
+
The raccoon is vacuuming the family room carpet.
|
101 |
+
The cat is sweeping the garage.
|
102 |
+
The rabbit is wiping the sunroom windows.
|
103 |
+
The hedgehog is washing the car hood.
|
104 |
+
The dog is wiping the kitchen table after lunch.
|
105 |
+
The bat is dusting the nightstands.
|
106 |
+
The monkey is watering the balcony plants.
|
107 |
+
The raccoon is vacuuming the home theater carpet.
|
108 |
+
The cat is sweeping the front steps.
|
109 |
+
The rabbit is wiping the living room windows.
|
110 |
+
The hedgehog is washing the car side mirrors.
|
111 |
+
The dog is wiping the dining table before dinner.
|
112 |
+
The bat is dusting the study shelves.
|
113 |
+
The monkey is watering the backyard flowers.
|
114 |
+
The raccoon is vacuuming the bedroom carpet.
|
115 |
+
The cat is sweeping the patio.
|
116 |
+
The rabbit is wiping the glass doors.
|
117 |
+
The hedgehog is washing the car front grille.
|
118 |
+
The dog is wiping the dining table after a meal.
|
119 |
+
The bat is dusting the bookshelf.
|
120 |
+
The monkey is watering the hallway plants.
|
121 |
+
The raccoon is vacuuming the living room carpet.
|
122 |
+
The cat is sweeping the garage floor.
|
123 |
+
The rabbit is wiping the patio doors.
|
124 |
+
The hedgehog is washing the car bumper.
|
125 |
+
The dog is wiping the dining table before setting it.
|
126 |
+
The bat is dusting the family room shelves.
|
127 |
+
The monkey is watering the kitchen herbs.
|
128 |
+
The raccoon is vacuuming the playroom carpet.
|
129 |
+
The cat is sweeping the front porch.
|
130 |
+
The rabbit is wiping the windowsills.
|
131 |
+
The hedgehog is washing the car hood.
|
132 |
+
The dog is wiping the dining chairs.
|
133 |
+
The bat is dusting the TV stand.
|
134 |
+
The monkey is watering the garden.
|
135 |
+
The raccoon is vacuuming the stairs.
|
136 |
+
The cat is sweeping the basement.
|
137 |
+
The rabbit is wiping the kitchen windows.
|
138 |
+
The hedgehog is washing the car rear window.
|
139 |
+
The dog is wiping the dining table before dinner.
|
140 |
+
The bat is dusting the nightstands.
|
141 |
+
The monkey is watering the flower pots.
|
142 |
+
The raccoon is vacuuming the hallway.
|
143 |
+
The cat is sweeping the deck.
|
144 |
+
The rabbit is wiping the kitchen windows.
|
145 |
+
The hedgehog is washing the car tires.
|
146 |
+
The dog is wiping the dining chairs.
|
147 |
+
The bat is dusting the TV stand.
|
148 |
+
The monkey is watering the indoor plants.
|
149 |
+
The raccoon is vacuuming the bedroom carpet.
|
150 |
+
The cat is sweeping the floor.
|
assets/chatgpt_custom_animal_sport.txt
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A dog playing soccer in a green field, wearing a red jersey and kicking a ball towards a goal.
|
2 |
+
A cat playing tennis on a sunny court, wearing a white visor and swinging a racket to hit the ball.
|
3 |
+
A kangaroo boxing in a ring, wearing blue boxing gloves and shorts, jumping and throwing punches.
|
4 |
+
A bear lifting weights in a gym, wearing a headband and wristbands, straining as it lifts a heavy barbell.
|
5 |
+
A penguin ice skating in an indoor rink, wearing a bright scarf and gracefully gliding on the ice.
|
6 |
+
A rabbit running in a track race, wearing running shoes and a number bib, sprinting towards the finish line.
|
7 |
+
A horse playing polo on a green field, wearing a helmet and riding gear, skillfully hitting the ball with a mallet.
|
8 |
+
A squirrel surfing on a big wave, wearing a wetsuit and balancing on a surfboard with skill.
|
9 |
+
A monkey climbing a rock wall, wearing climbing shoes and a harness, reaching for the next hold with determination.
|
10 |
+
An elephant playing basketball in a playground, wearing a jersey and shooting the ball into the hoop with its trunk.
|
11 |
+
A group of dogs playing football, all wearing team jerseys and helmets, running and tackling each other on the field.
|
12 |
+
A pair of cats playing beach volleyball, wearing sunglasses and swim trunks, jumping to spike the ball over the net.
|
13 |
+
A herd of elephants playing rugby, wearing matching uniforms and charging towards the goal line.
|
14 |
+
A flock of birds playing badminton in a park, wearing tiny sweatbands and fluttering to hit the shuttlecock.
|
15 |
+
A team of rabbits playing baseball, wearing caps and gloves, one rabbit pitching the ball while another gets ready to bat.
|
16 |
+
A fox skateboarding in a skate park, wearing a helmet and knee pads, performing tricks on the ramps.
|
17 |
+
A cheetah racing in a motocross event, wearing a racing suit and helmet, speeding over dirt hills and jumps.
|
18 |
+
A raccoon doing parkour in an urban environment, wearing a bandana and wristbands, skillfully jumping between buildings.
|
19 |
+
A dolphin windsurfing on the ocean, wearing a bright life vest and maneuvering the board with precision.
|
20 |
+
A tiger bungee jumping off a bridge, wearing a safety harness and roaring as it plunges towards the river below.
|
21 |
+
A polar bear swimming competitively in a pool, wearing goggles and a swim cap, racing towards the finish line.
|
22 |
+
A seal playing water polo, wearing a swim cap and maneuvering the ball with its flippers in a heated match.
|
23 |
+
A duck rowing a boat in a lake, wearing a life jacket and paddling vigorously with its team.
|
24 |
+
A turtle snorkeling in a coral reef, wearing a snorkel mask and fins, exploring the colorful underwater world.
|
25 |
+
A frog kayaking down a river, wearing a helmet and life vest, skillfully navigating through the rapids.
|
assets/chatgpt_custom_animal_sportV2.txt
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A dog playing soccer in a green field, wearing a red jersey and kicking a ball towards a goal.
|
2 |
+
A cat playing tennis on a sunny court, wearing a white visor and swinging a racket to hit the ball.
|
3 |
+
A kangaroo boxing in a ring, wearing blue boxing gloves and shorts, jumping and throwing punches.
|
4 |
+
A bear lifting weights in a gym, wearing a headband and wristbands, straining as it lifts a heavy barbell.
|
5 |
+
A penguin ice skating in an indoor rink, wearing a bright scarf and gracefully gliding on the ice.
|
6 |
+
A rabbit running in a track race, wearing running shoes and a number bib, sprinting towards the finish line.
|
7 |
+
A sea otter surfing on a big wave, wearing a wetsuit and balancing on a surfboard with ease.
|
8 |
+
A monkey climbing a rock wall, wearing climbing shoes and a harness, reaching for the next hold with determination.
|
9 |
+
An elephant playing basketball in a playground, wearing a jersey and shooting the ball into the hoop with its trunk.
|
10 |
+
A kangaroo playing rugby, wearing a jersey and running with the ball towards the goal line.
|
11 |
+
A group of dogs playing football, all wearing team jerseys and helmets, running and tackling each other on the field.
|
12 |
+
A pair of cats playing beach volleyball, wearing sunglasses and swim trunks, jumping to spike the ball over the net.
|
13 |
+
A herd of elephants playing rugby, wearing matching uniforms and charging towards the goal line.
|
14 |
+
A team of rabbits playing baseball, wearing caps and gloves, one rabbit pitching the ball while another gets ready to bat.
|
15 |
+
A team of squirrels playing soccer, wearing colorful jerseys and skillfully passing the ball to each other.
|
16 |
+
A fox skateboarding in a skate park, wearing a helmet and knee pads, performing tricks on the ramps.
|
17 |
+
A cheetah racing in a motocross event, wearing a racing suit and helmet, speeding over dirt hills and jumps.
|
18 |
+
A raccoon doing parkour in an urban environment, wearing a bandana and wristbands, skillfully jumping between buildings.
|
19 |
+
A dolphin windsurfing on the ocean, wearing a bright life vest and maneuvering the board with precision.
|
20 |
+
A squirrel bungee jumping off a bridge, wearing a safety harness and looking excited as it bounces.
|
21 |
+
A polar bear swimming competitively in a pool, wearing goggles and a swim cap, racing towards the finish line.
|
22 |
+
A seal playing water polo, wearing a swim cap and maneuvering the ball with its flippers in a heated match.
|
23 |
+
A duck rowing a boat in a calm lake, wearing a life jacket and paddling vigorously with its webbed feet.
|
24 |
+
A turtle snorkeling in a coral reef, wearing a snorkel mask and fins, exploring the colorful underwater world.
|
25 |
+
A frog kayaking down a river, wearing a helmet and life vest, skillfully navigating through the rapids.
|
26 |
+
A dog sledding in a snowy landscape, wearing a harness and pulling a sled through the snow.
|
27 |
+
A rabbit skiing down a snowy hill, wearing a winter hat and goggles, expertly navigating the slopes.
|
28 |
+
A penguin sliding down an icy slope, wearing a scarf and having fun in the winter wonderland.
|
29 |
+
A polar bear playing ice hockey, wearing a jersey and skates, skillfully handling the puck with its stick.
|
30 |
+
A cat snowboarding on a mountain, wearing a colorful jacket and performing tricks on the snow.
|
31 |
+
A dog playing frisbee in a park, wearing a bandana and leaping high to catch the flying disc.
|
32 |
+
A cat performing gymnastics, wearing a leotard and balancing gracefully on a beam.
|
33 |
+
A rabbit participating in an agility course, wearing a harness and quickly navigating through the obstacles.
|
34 |
+
A bear doing archery in a field, wearing a quiver and aiming carefully at the target.
|
35 |
+
A kangaroo playing basketball, wearing a jersey and dribbling the ball before making a jump shot.
|
36 |
+
A group of dogs playing basketball, wearing team jerseys and passing the ball to each other.
|
37 |
+
A pair of cats playing doubles tennis, wearing matching visors and coordinating their shots.
|
38 |
+
A team of rabbits playing soccer, wearing colorful jerseys and skillfully dribbling the ball.
|
39 |
+
A pair of kangaroos playing doubles badminton, wearing wristbands and jumping to hit the shuttlecock.
|
40 |
+
A team of monkeys playing volleyball, wearing headbands and high-fiving each other after a point.
|
41 |
+
A cheetah running in a marathon, wearing running shoes and a number bib, speeding towards the finish line.
|
42 |
+
A raccoon skateboarding down a city street, wearing a helmet and knee pads, performing tricks on the pavement.
|
43 |
+
A dolphin doing synchronized swimming, wearing a swim cap and gracefully moving in sync with others.
|
44 |
+
A squirrel doing a high-wire act in a circus, wearing a tiny costume and balancing skillfully on the rope.
|
45 |
+
A monkey doing bungee jumping, wearing a safety harness and looking thrilled as it bounces up and down.
|
46 |
+
A sea lion surfing on the ocean waves, wearing a wetsuit and riding the surfboard with expertise.
|
47 |
+
A duck swimming in a lake race, wearing a small cap and paddling swiftly with its webbed feet.
|
48 |
+
A turtle diving in a pool, wearing goggles and fins, gracefully exploring the underwater environment.
|
49 |
+
A frog rowing a boat in a calm river, wearing a life jacket and paddling smoothly with its strong legs.
|
50 |
+
A seal doing synchronized swimming, wearing a swim cap and performing elegant moves in the water.
|
assets/chatgpt_custom_animal_technology.txt
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The dog is using a computer, typing on the keyboard.
|
2 |
+
The cat is talking on a phone.
|
3 |
+
The rabbit is playing a video game with a controller.
|
4 |
+
The bear is watching TV.
|
5 |
+
The raccoon is taking a selfie with a phone.
|
6 |
+
The squirrel is wearing headphones and listening to music.
|
7 |
+
The monkey is using a tablet.
|
8 |
+
The lion is using a laptop.
|
9 |
+
The fox is changing TV channels with a remote control.
|
10 |
+
The panda is checking the time on a smartwatch.
|
11 |
+
The dog is browsing on a tablet.
|
12 |
+
The cat is taking a photo with a camera.
|
13 |
+
The rabbit is video calling a friend on a laptop.
|
14 |
+
The bear is listening to music on a speaker.
|
15 |
+
The raccoon is charging a phone.
|
16 |
+
The squirrel is reading an e-book on a tablet.
|
17 |
+
The monkey is typing on a laptop.
|
18 |
+
The lion is taking a video with a phone.
|
19 |
+
The fox is setting an alarm on a smartwatch.
|
20 |
+
The panda is playing a game on a tablet.
|
21 |
+
The dog is watching videos on a phone.
|
22 |
+
The cat is using a fitness tracker.
|
23 |
+
The rabbit is browsing the internet on a computer.
|
24 |
+
The bear is listening to a podcast on a phone.
|
25 |
+
The raccoon is texting on a phone.
|
26 |
+
The squirrel is watching a movie on a tablet.
|
27 |
+
The monkey is scrolling through social media on a phone.
|
28 |
+
The lion is video calling a friend on a laptop.
|
29 |
+
The fox is using a calculator on a phone.
|
30 |
+
The panda is playing a video game with a controller.
|
31 |
+
The dog is checking email on a computer.
|
32 |
+
The cat is listening to music with earbuds.
|
33 |
+
The rabbit is using a webcam for a video chat.
|
34 |
+
The bear is typing a document on a laptop.
|
35 |
+
The raccoon is taking a photo with a tablet.
|
36 |
+
The squirrel is using a microwave to heat food.
|
37 |
+
The monkey is reading a digital book on an e-reader.
|
38 |
+
The lion is taking a picture with a smartphone.
|
39 |
+
The fox is watching a show on a tablet.
|
40 |
+
The panda is checking the weather on a smartphone.
|
41 |
+
The dog is using a laptop to write a story.
|
42 |
+
The cat is using a smart light to change colors.
|
43 |
+
The rabbit is listening to an audiobook on a phone.
|
44 |
+
The bear is making a video call on a tablet.
|
45 |
+
The raccoon is setting a reminder on a smartwatch.
|
46 |
+
The squirrel is using a digital thermometer to check the temperature.
|
47 |
+
The monkey is editing a photo on a laptop.
|
48 |
+
The lion is playing music on a Bluetooth speaker.
|
49 |
+
The fox is setting a timer on a smartphone.
|
50 |
+
The panda is watching a tutorial on a computer.
|
assets/chatgpt_custom_banana.txt
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A banana and a vase of flowers on a marble kitchen counter.
|
2 |
+
A banana and a cup of tea on a wooden desk.
|
3 |
+
A banana and a water bottle on a park bench.
|
4 |
+
A banana and a small pot of herbs on a windowsill.
|
5 |
+
A banana and a wicker basket on a picnic table.
|
6 |
+
A banana and a soft blanket on a bookshelf.
|
7 |
+
A banana and a lamp on a nightstand.
|
8 |
+
A banana and a latte on a café table.
|
9 |
+
A banana and sunglasses on a car dashboard.
|
10 |
+
A banana and fine china on a dining table.
|
11 |
+
A banana and a notebook on a classroom desk.
|
12 |
+
A banana and a water bottle on a gym bench.
|
13 |
+
A banana and seashells on a beach towel.
|
14 |
+
A banana and a potted plant on a windowsill.
|
15 |
+
A banana and candles on a fireplace mantel.
|
16 |
+
A banana and flowers in a bicycle basket.
|
17 |
+
A banana and old books on a library table.
|
18 |
+
A banana and a remote control on a couch armrest.
|
19 |
+
A banana and vegetables on a kitchen island.
|
20 |
+
A banana and a small vase of daisies on a restaurant table.
|
21 |
+
A banana and a book on a park table.
|
22 |
+
A banana and sheet music on a grand piano.
|
23 |
+
A banana and roses on a garden bench.
|
24 |
+
A banana and a water bottle on a yoga mat.
|
25 |
+
A banana and a cup of pens on a teacher’s desk.
|
26 |
+
A banana and a glass of water on a bedside table.
|
27 |
+
A banana and paintbrushes on a workbench.
|
28 |
+
A banana and a playbill on a theater seat.
|
29 |
+
A banana and a small bag of snacks on a park fountain edge.
|
30 |
+
A banana and a fishing rod on a boat deck.
|
31 |
+
A banana and other fruits on a street vendor’s cart.
|
32 |
+
A banana and a glass of wine on a rooftop terrace table.
|
33 |
+
A banana and a bag of popcorn on a stadium seat.
|
34 |
+
A banana and a coffee mug on a computer desk.
|
35 |
+
A banana and a book on a garden swing.
|
36 |
+
A banana and a magazine on a city bus seat.
|
37 |
+
A banana and a travel brochure on a hotel lobby table.
|
38 |
+
A banana and a stack of notebooks on a classroom bookshelf.
|
39 |
+
A banana and a cappuccino on a café counter.
|
40 |
+
A banana and a water bottle on a treadmill console.
|
41 |
+
A banana and a bowl of nuts on a restaurant bar counter.
|
42 |
+
A banana and a thermos of tea on a park path bench.
|
43 |
+
A banana and a magazine on a hospital waiting room chair.
|
44 |
+
A banana and a suitcase on a train station bench.
|
45 |
+
A banana and a basket of snacks on a beach picnic blanket.
|
46 |
+
A banana and a program on a concert hall seat.
|
47 |
+
A banana and a small vase of flowers on a kitchen window ledge.
|
48 |
+
A banana and a sketchbook on an artist’s worktable.
|
49 |
+
A banana and a water bottle on a hiking trail bench.
|
50 |
+
A banana and a cup of tea on a coffee table.
|
assets/chatgpt_custom_book_cup.txt
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A book and a cup of coffee on a cozy armchair.
|
2 |
+
A book and a cup of tea on a windowsill with raindrops.
|
3 |
+
A book and a cup of hot chocolate on a wooden desk.
|
4 |
+
A book and a cup of herbal tea on a bedside table.
|
5 |
+
A book and a cup of coffee on a park bench under a tree.
|
6 |
+
A book and a cup of tea on a picnic blanket in a meadow.
|
7 |
+
A book and a cup of coffee on a café table by the window.
|
8 |
+
A book and a cup of tea on a porch swing.
|
9 |
+
A book and a cup of coffee on a kitchen counter with a fruit bowl.
|
10 |
+
A book and a cup of tea on a library table surrounded by shelves of books.
|
11 |
+
A book and a cup of hot chocolate on a coffee table by the fireplace.
|
12 |
+
A book and a cup of tea on a garden bench among blooming flowers.
|
13 |
+
A book and a cup of coffee on a balcony with a city view.
|
14 |
+
A book and a cup of tea on a nightstand with a lamp.
|
15 |
+
A book and a cup of herbal tea on a yoga mat in a serene room.
|
16 |
+
A book and a cup of coffee on a desk in a home office.
|
17 |
+
A book and a cup of tea on a park bench by a pond.
|
18 |
+
A book and a cup of coffee on a café patio with string lights.
|
19 |
+
A book and a cup of tea on a picnic table in the forest.
|
20 |
+
A book and a cup of hot chocolate on a windowsill with a snowy view.
|
21 |
+
A book and a cup of tea on a hammock in the garden.
|
22 |
+
A book and a cup of coffee on a rustic wooden table in a cabin.
|
23 |
+
A book and a cup of tea on a bench in a botanical garden.
|
24 |
+
A book and a cup of coffee on a study table with a globe.
|
25 |
+
A book and a cup of tea on a blanket in a sunflower field.
|
assets/chatgpt_custom_book_cup_character.txt
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A woman reading a book and sipping a cup of coffee on a cozy armchair.
|
2 |
+
A man reading a book and drinking a cup of tea on a windowsill with raindrops.
|
3 |
+
A girl with a book and a cup of hot chocolate on a wooden desk.
|
4 |
+
A man reading a book and enjoying a cup of herbal tea on a bedside table.
|
5 |
+
A girl reading a book and holding a cup of coffee on a park bench under a tree.
|
6 |
+
A woman lying on a picnic blanket in a meadow with a book and a cup of tea.
|
7 |
+
A man reading a book and sipping a cup of coffee on a café table by the window.
|
8 |
+
A girl swinging on a porch swing with a book and a cup of tea.
|
9 |
+
A woman reading a book and enjoying a cup of coffee on a kitchen counter with a fruit bowl.
|
10 |
+
A man surrounded by books, reading with a cup of tea on a library table.
|
11 |
+
A child reading a book and drinking a cup of hot chocolate on a coffee table by the fireplace.
|
12 |
+
A woman sitting on a garden bench, reading a book and sipping a cup of tea among blooming flowers.
|
13 |
+
A man reading a book and enjoying a cup of coffee on a balcony with a city view.
|
14 |
+
A woman reading a book and drinking a cup of tea on a nightstand with a lamp.
|
15 |
+
A woman reading a book and sipping a cup of herbal tea on a yoga mat in a serene room.
|
16 |
+
A man reading a book and drinking a cup of coffee on a desk in a home office.
|
17 |
+
A man reading a book and enjoying a cup of tea on a park bench by a pond.
|
18 |
+
A couple reading books and sipping cups of coffee on a café patio with string lights.
|
19 |
+
A woman reading a book and drinking a cup of tea on a picnic table in the forest.
|
20 |
+
A child reading a book and drinking a cup of hot chocolate on a windowsill with a snowy view.
|
21 |
+
A woman lounging in a hammock with a book and a cup of tea in the garden.
|
22 |
+
A man reading a book and sipping a cup of coffee on a rustic wooden table in a cabin.
|
23 |
+
A woman reading a book and drinking a cup of tea on a bench in a botanical garden.
|
24 |
+
A child reading a book and enjoying a cup of coffee on a study table with a globe.
|
25 |
+
A girl lying on a blanket in a sunflower field with a book and a cup of tea.
|