multimodalart HF staff commited on
Commit
0366b8b
1 Parent(s): e14ba5f

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/13.gif filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ *pyc
3
+ .vscode
4
+ __pycache__
5
+ *.egg-info
6
+
7
+ checkpoints
8
+ results
9
+ backup
10
+ LOG
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Tencent
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,12 +1,257 @@
1
- ---
2
- title: Tooncrafter
3
- emoji: 🏃
4
- colorFrom: pink
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 4.32.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## ___***ToonCrafter: Generative Cartoon Interpolation***___
2
+ <!-- ![](./assets/logo_long.png#gh-light-mode-only){: width="50%"} -->
3
+ <!-- ![](./assets/logo_long_dark.png#gh-dark-mode-only=100x20) -->
4
+ <div align="center">
5
+
6
+
7
+
8
+ </div>
9
+
10
+ ## 🔆 Introduction
11
+
12
+ ⚠️ Please check our [disclaimer](#disc) first.
13
+
14
+ 🤗 ToonCrafter can interpolate two cartoon images by leveraging the pre-trained image-to-video diffusion priors. Please check our project page and paper for more information. <br>
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ ### 1.1 Showcases (512x320)
23
+ <table class="center">
24
+ <tr style="font-weight: bolder;text-align:center;">
25
+ <td>Input starting frame</td>
26
+ <td>Input ending frame</td>
27
+ <td>Generated video</td>
28
+ </tr>
29
+ <tr>
30
+ <td>
31
+ <img src=assets/72109_125.mp4_00-00.png width="250">
32
+ </td>
33
+ <td>
34
+ <img src=assets/72109_125.mp4_00-01.png width="250">
35
+ </td>
36
+ <td>
37
+ <img src=assets/00.gif width="250">
38
+ </td>
39
+ </tr>
40
+
41
+
42
+ <tr>
43
+ <td>
44
+ <img src=assets/Japan_v2_2_062266_s2_frame1.png width="250">
45
+ </td>
46
+ <td>
47
+ <img src=assets/Japan_v2_2_062266_s2_frame3.png width="250">
48
+ </td>
49
+ <td>
50
+ <img src=assets/03.gif width="250">
51
+ </td>
52
+ </tr>
53
+ <tr>
54
+ <td>
55
+ <img src=assets/Japan_v2_1_070321_s3_frame1.png width="250">
56
+ </td>
57
+ <td>
58
+ <img src=assets/Japan_v2_1_070321_s3_frame3.png width="250">
59
+ </td>
60
+ <td>
61
+ <img src=assets/02.gif width="250">
62
+ </td>
63
+ </tr>
64
+ <tr>
65
+ <td>
66
+ <img src=assets/74302_1349_frame1.png width="250">
67
+ </td>
68
+ <td>
69
+ <img src=assets/74302_1349_frame3.png width="250">
70
+ </td>
71
+ <td>
72
+ <img src=assets/01.gif width="250">
73
+ </td>
74
+ </tr>
75
+ </table>
76
+
77
+ ### 1.2 Sparse sketch guidance
78
+ <table class="center">
79
+ <tr style="font-weight: bolder;text-align:center;">
80
+ <td>Input starting frame</td>
81
+ <td>Input ending frame</td>
82
+ <td>Input sketch guidance</td>
83
+ <td>Generated video</td>
84
+ </tr>
85
+ <tr>
86
+ <td>
87
+ <img src=assets/72105_388.mp4_00-00.png width="200">
88
+ </td>
89
+ <td>
90
+ <img src=assets/72105_388.mp4_00-01.png width="200">
91
+ </td>
92
+ <td>
93
+ <img src=assets/06.gif width="200">
94
+ </td>
95
+ <td>
96
+ <img src=assets/07.gif width="200">
97
+ </td>
98
+ </tr>
99
+
100
+ <tr>
101
+ <td>
102
+ <img src=assets/72110_255.mp4_00-00.png width="200">
103
+ </td>
104
+ <td>
105
+ <img src=assets/72110_255.mp4_00-01.png width="200">
106
+ </td>
107
+ <td>
108
+ <img src=assets/12.gif width="200">
109
+ </td>
110
+ <td>
111
+ <img src=assets/13.gif width="200">
112
+ </td>
113
+ </tr>
114
+
115
+
116
+ </table>
117
+
118
+
119
+ ### 2. Applications
120
+ #### 2.1 Cartoon Sketch Interpolation (see project page for more details)
121
+ <table class="center">
122
+ <tr style="font-weight: bolder;text-align:center;">
123
+ <td>Input starting frame</td>
124
+ <td>Input ending frame</td>
125
+ <td>Generated video</td>
126
+ </tr>
127
+
128
+ <tr>
129
+ <td>
130
+ <img src=assets/frame0001_10.png width="250">
131
+ </td>
132
+ <td>
133
+ <img src=assets/frame0016_10.png width="250">
134
+ </td>
135
+ <td>
136
+ <img src=assets/10.gif width="250">
137
+ </td>
138
+ </tr>
139
+
140
+
141
+ <tr>
142
+ <td>
143
+ <img src=assets/frame0001_11.png width="250">
144
+ </td>
145
+ <td>
146
+ <img src=assets/frame0016_11.png width="250">
147
+ </td>
148
+ <td>
149
+ <img src=assets/11.gif width="250">
150
+ </td>
151
+ </tr>
152
+
153
+ </table>
154
+
155
+
156
+ #### 2.2 Reference-based Sketch Colorization
157
+ <table class="center">
158
+ <tr style="font-weight: bolder;text-align:center;">
159
+ <td>Input sketch</td>
160
+ <td>Input reference</td>
161
+ <td>Colorization results</td>
162
+ </tr>
163
+
164
+ <tr>
165
+ <td>
166
+ <img src=assets/04.gif width="250">
167
+ </td>
168
+ <td>
169
+ <img src=assets/frame0001_05.png width="250">
170
+ </td>
171
+ <td>
172
+ <img src=assets/05.gif width="250">
173
+ </td>
174
+ </tr>
175
+
176
+
177
+ <tr>
178
+ <td>
179
+ <img src=assets/08.gif width="250">
180
+ </td>
181
+ <td>
182
+ <img src=assets/frame0001_09.png width="250">
183
+ </td>
184
+ <td>
185
+ <img src=assets/09.gif width="250">
186
+ </td>
187
+ </tr>
188
+
189
+ </table>
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+ ## 📝 Changelog
198
+ - [ ] Add sketch control and colorization function.
199
+ - __[2024.05.29]__: 🔥🔥 Release code and model weights.
200
+ - __[2024.05.28]__: Launch the project page and update the arXiv preprint.
201
+ <br>
202
+
203
+
204
+ ## 🧰 Models
205
+
206
+ |Model|Resolution|GPU Mem. & Inference Time (A100, ddim 50steps)|Checkpoint|
207
+ |:---------|:---------|:--------|:--------|
208
+ |ToonCrafter_512|320x512| TBD (`perframe_ae=True`)|[Hugging Face](https://huggingface.co/Doubiiu/ToonCrafter/blob/main/model.ckpt)|
209
+
210
+
211
+ Currently, our ToonCrafter can support generating videos of up to 16 frames with a resolution of 512x320. The inference time can be reduced by using fewer DDIM steps.
212
+
213
+
214
+
215
+ ## ⚙️ Setup
216
+
217
+ ### Install Environment via Anaconda (Recommended)
218
+ ```bash
219
+ conda create -n tooncrafter python=3.8.5
220
+ conda activate tooncrafter
221
+ pip install -r requirements.txt
222
+ ```
223
+
224
+
225
+ ## 💫 Inference
226
+ ### 1. Command line
227
+
228
+ Download pretrained ToonCrafter_512 and put the `model.ckpt` in `checkpoints/tooncrafter_512_interp_v1/model.ckpt`.
229
+ ```bash
230
+ sh scripts/run.sh
231
+ ```
232
+
233
+
234
+ ### 2. Local Gradio demo
235
+
236
+ Download the pretrained model and put it in the corresponding directory according to the previous guidelines.
237
+ ```bash
238
+ python gradio_app.py
239
+ ```
240
+
241
+
242
+
243
+
244
+
245
+
246
+ <!-- ## 🤝 Community Support -->
247
+
248
+
249
+
250
+ <a name="disc"></a>
251
+ ## 📢 Disclaimer
252
+ Calm down. Our framework opens up the era of generative cartoon interpolation, but due to the variaity of generative video prior, the success rate is not guaranteed.
253
+
254
+ ⚠️This is an open-source research exploration, instead of commercial products. It can't meet all your expectations.
255
+
256
+ This project strives to impact the domain of AI-driven video generation positively. Users are granted the freedom to create videos using this tool, but they are expected to comply with local laws and utilize it responsibly. The developers do not assume any responsibility for potential misuse by users.
257
+ ****
assets/00.gif ADDED
assets/01.gif ADDED
assets/02.gif ADDED
assets/03.gif ADDED
assets/04.gif ADDED
assets/05.gif ADDED
assets/06.gif ADDED
assets/07.gif ADDED
assets/08.gif ADDED
assets/09.gif ADDED
assets/10.gif ADDED
assets/11.gif ADDED
assets/12.gif ADDED
assets/13.gif ADDED

Git LFS Details

  • SHA256: 179af7d265d8790c0ca31a5898f870961b0a738b02d9fd0c991a3a75651cbb56
  • Pointer size: 132 Bytes
  • Size of remote file: 1.03 MB
assets/72105_388.mp4_00-00.png ADDED
assets/72105_388.mp4_00-01.png ADDED
assets/72109_125.mp4_00-00.png ADDED
assets/72109_125.mp4_00-01.png ADDED
assets/72110_255.mp4_00-00.png ADDED
assets/72110_255.mp4_00-01.png ADDED
assets/74302_1349_frame1.png ADDED
assets/74302_1349_frame3.png ADDED
assets/Japan_v2_1_070321_s3_frame1.png ADDED
assets/Japan_v2_1_070321_s3_frame3.png ADDED
assets/Japan_v2_2_062266_s2_frame1.png ADDED
assets/Japan_v2_2_062266_s2_frame3.png ADDED
assets/frame0001_05.png ADDED
assets/frame0001_09.png ADDED
assets/frame0001_10.png ADDED
assets/frame0001_11.png ADDED
assets/frame0016_10.png ADDED
assets/frame0016_11.png ADDED
configs/inference_512_v1.0.yaml ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ target: lvdm.models.ddpm3d.LatentVisualDiffusion
3
+ params:
4
+ rescale_betas_zero_snr: True
5
+ parameterization: "v"
6
+ linear_start: 0.00085
7
+ linear_end: 0.012
8
+ num_timesteps_cond: 1
9
+ timesteps: 1000
10
+ first_stage_key: video
11
+ cond_stage_key: caption
12
+ cond_stage_trainable: False
13
+ conditioning_key: hybrid
14
+ image_size: [40, 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_dynamic_rescale: true
21
+ base_scale: 0.7
22
+ fps_condition_type: 'fps'
23
+ perframe_ae: True
24
+ loop_video: true
25
+ unet_config:
26
+ target: lvdm.modules.networks.openaimodel3d.UNetModel
27
+ params:
28
+ in_channels: 8
29
+ out_channels: 4
30
+ model_channels: 320
31
+ attention_resolutions:
32
+ - 4
33
+ - 2
34
+ - 1
35
+ num_res_blocks: 2
36
+ channel_mult:
37
+ - 1
38
+ - 2
39
+ - 4
40
+ - 4
41
+ dropout: 0.1
42
+ num_head_channels: 64
43
+ transformer_depth: 1
44
+ context_dim: 1024
45
+ use_linear: true
46
+ use_checkpoint: True
47
+ temporal_conv: True
48
+ temporal_attention: True
49
+ temporal_selfatt_only: true
50
+ use_relative_position: false
51
+ use_causal_attention: False
52
+ temporal_length: 16
53
+ addition_attention: true
54
+ image_cross_attention: true
55
+ default_fs: 24
56
+ fs_condition: true
57
+
58
+ first_stage_config:
59
+ target: lvdm.models.autoencoder.AutoencoderKL_Dualref
60
+ params:
61
+ embed_dim: 4
62
+ monitor: val/rec_loss
63
+ ddconfig:
64
+ double_z: True
65
+ z_channels: 4
66
+ resolution: 256
67
+ in_channels: 3
68
+ out_ch: 3
69
+ ch: 128
70
+ ch_mult:
71
+ - 1
72
+ - 2
73
+ - 4
74
+ - 4
75
+ num_res_blocks: 2
76
+ attn_resolutions: []
77
+ dropout: 0.0
78
+ lossconfig:
79
+ target: torch.nn.Identity
80
+
81
+ cond_stage_config:
82
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
83
+ params:
84
+ freeze: true
85
+ layer: "penultimate"
86
+
87
+ img_cond_stage_config:
88
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
89
+ params:
90
+ freeze: true
91
+
92
+ image_proj_stage_config:
93
+ target: lvdm.modules.encoders.resampler.Resampler
94
+ params:
95
+ dim: 1024
96
+ depth: 4
97
+ dim_head: 64
98
+ heads: 12
99
+ num_queries: 16
100
+ embedding_dim: 1280
101
+ output_dim: 1024
102
+ ff_mult: 4
103
+ video_length: 16
configs/training_1024_v1.0/config.yaml ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ pretrained_checkpoint: checkpoints/dynamicrafter_1024_v1/model.ckpt
3
+ base_learning_rate: 1.0e-05
4
+ scale_lr: False
5
+ target: lvdm.models.ddpm3d.LatentVisualDiffusion
6
+ params:
7
+ rescale_betas_zero_snr: True
8
+ parameterization: "v"
9
+ linear_start: 0.00085
10
+ linear_end: 0.012
11
+ num_timesteps_cond: 1
12
+ log_every_t: 200
13
+ timesteps: 1000
14
+ first_stage_key: video
15
+ cond_stage_key: caption
16
+ cond_stage_trainable: False
17
+ image_proj_model_trainable: True
18
+ conditioning_key: hybrid
19
+ image_size: [72, 128]
20
+ channels: 4
21
+ scale_by_std: False
22
+ scale_factor: 0.18215
23
+ use_ema: False
24
+ uncond_prob: 0.05
25
+ uncond_type: 'empty_seq'
26
+ rand_cond_frame: true
27
+ use_dynamic_rescale: true
28
+ base_scale: 0.3
29
+ fps_condition_type: 'fps'
30
+ perframe_ae: True
31
+
32
+ unet_config:
33
+ target: lvdm.modules.networks.openaimodel3d.UNetModel
34
+ params:
35
+ in_channels: 8
36
+ out_channels: 4
37
+ model_channels: 320
38
+ attention_resolutions:
39
+ - 4
40
+ - 2
41
+ - 1
42
+ num_res_blocks: 2
43
+ channel_mult:
44
+ - 1
45
+ - 2
46
+ - 4
47
+ - 4
48
+ dropout: 0.1
49
+ num_head_channels: 64
50
+ transformer_depth: 1
51
+ context_dim: 1024
52
+ use_linear: true
53
+ use_checkpoint: True
54
+ temporal_conv: True
55
+ temporal_attention: True
56
+ temporal_selfatt_only: true
57
+ use_relative_position: false
58
+ use_causal_attention: False
59
+ temporal_length: 16
60
+ addition_attention: true
61
+ image_cross_attention: true
62
+ default_fs: 10
63
+ fs_condition: true
64
+
65
+ first_stage_config:
66
+ target: lvdm.models.autoencoder.AutoencoderKL
67
+ params:
68
+ embed_dim: 4
69
+ monitor: val/rec_loss
70
+ ddconfig:
71
+ double_z: True
72
+ z_channels: 4
73
+ resolution: 256
74
+ in_channels: 3
75
+ out_ch: 3
76
+ ch: 128
77
+ ch_mult:
78
+ - 1
79
+ - 2
80
+ - 4
81
+ - 4
82
+ num_res_blocks: 2
83
+ attn_resolutions: []
84
+ dropout: 0.0
85
+ lossconfig:
86
+ target: torch.nn.Identity
87
+
88
+ cond_stage_config:
89
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
90
+ params:
91
+ freeze: true
92
+ layer: "penultimate"
93
+
94
+ img_cond_stage_config:
95
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
96
+ params:
97
+ freeze: true
98
+
99
+ image_proj_stage_config:
100
+ target: lvdm.modules.encoders.resampler.Resampler
101
+ params:
102
+ dim: 1024
103
+ depth: 4
104
+ dim_head: 64
105
+ heads: 12
106
+ num_queries: 16
107
+ embedding_dim: 1280
108
+ output_dim: 1024
109
+ ff_mult: 4
110
+ video_length: 16
111
+
112
+ data:
113
+ target: utils_data.DataModuleFromConfig
114
+ params:
115
+ batch_size: 1
116
+ num_workers: 12
117
+ wrap: false
118
+ train:
119
+ target: lvdm.data.webvid.WebVid
120
+ params:
121
+ data_dir: <WebVid10M DATA>
122
+ meta_path: <.csv FILE>
123
+ video_length: 16
124
+ frame_stride: 6
125
+ load_raw_resolution: true
126
+ resolution: [576, 1024]
127
+ spatial_transform: resize_center_crop
128
+ random_fs: true ## if true, we uniformly sample fs with max_fs=frame_stride (above)
129
+
130
+ lightning:
131
+ precision: 16
132
+ # strategy: deepspeed_stage_2
133
+ trainer:
134
+ benchmark: True
135
+ accumulate_grad_batches: 2
136
+ max_steps: 100000
137
+ # logger
138
+ log_every_n_steps: 50
139
+ # val
140
+ val_check_interval: 0.5
141
+ gradient_clip_algorithm: 'norm'
142
+ gradient_clip_val: 0.5
143
+ callbacks:
144
+ model_checkpoint:
145
+ target: pytorch_lightning.callbacks.ModelCheckpoint
146
+ params:
147
+ every_n_train_steps: 9000 #1000
148
+ filename: "{epoch}-{step}"
149
+ save_weights_only: True
150
+ metrics_over_trainsteps_checkpoint:
151
+ target: pytorch_lightning.callbacks.ModelCheckpoint
152
+ params:
153
+ filename: '{epoch}-{step}'
154
+ save_weights_only: True
155
+ every_n_train_steps: 10000 #20000 # 3s/step*2w=
156
+ batch_logger:
157
+ target: callbacks.ImageLogger
158
+ params:
159
+ batch_frequency: 500
160
+ to_local: False
161
+ max_images: 8
162
+ log_images_kwargs:
163
+ ddim_steps: 50
164
+ unconditional_guidance_scale: 7.5
165
+ timestep_spacing: uniform_trailing
166
+ guidance_rescale: 0.7
configs/training_1024_v1.0/run.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NCCL configuration
2
+ # export NCCL_DEBUG=INFO
3
+ # export NCCL_IB_DISABLE=0
4
+ # export NCCL_IB_GID_INDEX=3
5
+ # export NCCL_NET_GDR_LEVEL=3
6
+ # export NCCL_TOPO_FILE=/tmp/topo.txt
7
+
8
+ # args
9
+ name="training_1024_v1.0"
10
+ config_file=configs/${name}/config.yaml
11
+
12
+ # save root dir for logs, checkpoints, tensorboard record, etc.
13
+ save_root="<YOUR_SAVE_ROOT_DIR>"
14
+
15
+ mkdir -p $save_root/$name
16
+
17
+ ## run
18
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python3 -m torch.distributed.launch \
19
+ --nproc_per_node=$HOST_GPU_NUM --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
20
+ ./main/trainer.py \
21
+ --base $config_file \
22
+ --train \
23
+ --name $name \
24
+ --logdir $save_root \
25
+ --devices $HOST_GPU_NUM \
26
+ lightning.trainer.num_nodes=1
27
+
28
+ ## debugging
29
+ # CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch \
30
+ # --nproc_per_node=4 --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
31
+ # ./main/trainer.py \
32
+ # --base $config_file \
33
+ # --train \
34
+ # --name $name \
35
+ # --logdir $save_root \
36
+ # --devices 4 \
37
+ # lightning.trainer.num_nodes=1
configs/training_512_v1.0/config.yaml ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ pretrained_checkpoint: checkpoints/dynamicrafter_512_v1/model.ckpt
3
+ base_learning_rate: 1.0e-05
4
+ scale_lr: False
5
+ target: lvdm.models.ddpm3d.LatentVisualDiffusion
6
+ params:
7
+ rescale_betas_zero_snr: True
8
+ parameterization: "v"
9
+ linear_start: 0.00085
10
+ linear_end: 0.012
11
+ num_timesteps_cond: 1
12
+ log_every_t: 200
13
+ timesteps: 1000
14
+ first_stage_key: video
15
+ cond_stage_key: caption
16
+ cond_stage_trainable: False
17
+ image_proj_model_trainable: True
18
+ conditioning_key: hybrid
19
+ image_size: [40, 64]
20
+ channels: 4
21
+ scale_by_std: False
22
+ scale_factor: 0.18215
23
+ use_ema: False
24
+ uncond_prob: 0.05
25
+ uncond_type: 'empty_seq'
26
+ rand_cond_frame: true
27
+ use_dynamic_rescale: true
28
+ base_scale: 0.7
29
+ fps_condition_type: 'fps'
30
+ perframe_ae: True
31
+
32
+ unet_config:
33
+ target: lvdm.modules.networks.openaimodel3d.UNetModel
34
+ params:
35
+ in_channels: 8
36
+ out_channels: 4
37
+ model_channels: 320
38
+ attention_resolutions:
39
+ - 4
40
+ - 2
41
+ - 1
42
+ num_res_blocks: 2
43
+ channel_mult:
44
+ - 1
45
+ - 2
46
+ - 4
47
+ - 4
48
+ dropout: 0.1
49
+ num_head_channels: 64
50
+ transformer_depth: 1
51
+ context_dim: 1024
52
+ use_linear: true
53
+ use_checkpoint: True
54
+ temporal_conv: True
55
+ temporal_attention: True
56
+ temporal_selfatt_only: true
57
+ use_relative_position: false
58
+ use_causal_attention: False
59
+ temporal_length: 16
60
+ addition_attention: true
61
+ image_cross_attention: true
62
+ default_fs: 10
63
+ fs_condition: true
64
+
65
+ first_stage_config:
66
+ target: lvdm.models.autoencoder.AutoencoderKL
67
+ params:
68
+ embed_dim: 4
69
+ monitor: val/rec_loss
70
+ ddconfig:
71
+ double_z: True
72
+ z_channels: 4
73
+ resolution: 256
74
+ in_channels: 3
75
+ out_ch: 3
76
+ ch: 128
77
+ ch_mult:
78
+ - 1
79
+ - 2
80
+ - 4
81
+ - 4
82
+ num_res_blocks: 2
83
+ attn_resolutions: []
84
+ dropout: 0.0
85
+ lossconfig:
86
+ target: torch.nn.Identity
87
+
88
+ cond_stage_config:
89
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
90
+ params:
91
+ freeze: true
92
+ layer: "penultimate"
93
+
94
+ img_cond_stage_config:
95
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
96
+ params:
97
+ freeze: true
98
+
99
+ image_proj_stage_config:
100
+ target: lvdm.modules.encoders.resampler.Resampler
101
+ params:
102
+ dim: 1024
103
+ depth: 4
104
+ dim_head: 64
105
+ heads: 12
106
+ num_queries: 16
107
+ embedding_dim: 1280
108
+ output_dim: 1024
109
+ ff_mult: 4
110
+ video_length: 16
111
+
112
+ data:
113
+ target: utils_data.DataModuleFromConfig
114
+ params:
115
+ batch_size: 2
116
+ num_workers: 12
117
+ wrap: false
118
+ train:
119
+ target: lvdm.data.webvid.WebVid
120
+ params:
121
+ data_dir: <WebVid10M DATA>
122
+ meta_path: <.csv FILE>
123
+ video_length: 16
124
+ frame_stride: 6
125
+ load_raw_resolution: true
126
+ resolution: [320, 512]
127
+ spatial_transform: resize_center_crop
128
+ random_fs: true ## if true, we uniformly sample fs with max_fs=frame_stride (above)
129
+
130
+ lightning:
131
+ precision: 16
132
+ # strategy: deepspeed_stage_2
133
+ trainer:
134
+ benchmark: True
135
+ accumulate_grad_batches: 2
136
+ max_steps: 100000
137
+ # logger
138
+ log_every_n_steps: 50
139
+ # val
140
+ val_check_interval: 0.5
141
+ gradient_clip_algorithm: 'norm'
142
+ gradient_clip_val: 0.5
143
+ callbacks:
144
+ model_checkpoint:
145
+ target: pytorch_lightning.callbacks.ModelCheckpoint
146
+ params:
147
+ every_n_train_steps: 9000 #1000
148
+ filename: "{epoch}-{step}"
149
+ save_weights_only: True
150
+ metrics_over_trainsteps_checkpoint:
151
+ target: pytorch_lightning.callbacks.ModelCheckpoint
152
+ params:
153
+ filename: '{epoch}-{step}'
154
+ save_weights_only: True
155
+ every_n_train_steps: 10000 #20000 # 3s/step*2w=
156
+ batch_logger:
157
+ target: callbacks.ImageLogger
158
+ params:
159
+ batch_frequency: 500
160
+ to_local: False
161
+ max_images: 8
162
+ log_images_kwargs:
163
+ ddim_steps: 50
164
+ unconditional_guidance_scale: 7.5
165
+ timestep_spacing: uniform_trailing
166
+ guidance_rescale: 0.7
configs/training_512_v1.0/run.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NCCL configuration
2
+ # export NCCL_DEBUG=INFO
3
+ # export NCCL_IB_DISABLE=0
4
+ # export NCCL_IB_GID_INDEX=3
5
+ # export NCCL_NET_GDR_LEVEL=3
6
+ # export NCCL_TOPO_FILE=/tmp/topo.txt
7
+
8
+ # args
9
+ name="training_512_v1.0"
10
+ config_file=configs/${name}/config.yaml
11
+
12
+ # save root dir for logs, checkpoints, tensorboard record, etc.
13
+ save_root="<YOUR_SAVE_ROOT_DIR>"
14
+
15
+ mkdir -p $save_root/$name
16
+
17
+ ## run
18
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python3 -m torch.distributed.launch \
19
+ --nproc_per_node=$HOST_GPU_NUM --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
20
+ ./main/trainer.py \
21
+ --base $config_file \
22
+ --train \
23
+ --name $name \
24
+ --logdir $save_root \
25
+ --devices $HOST_GPU_NUM \
26
+ lightning.trainer.num_nodes=1
27
+
28
+ ## debugging
29
+ # CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch \
30
+ # --nproc_per_node=4 --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
31
+ # ./main/trainer.py \
32
+ # --base $config_file \
33
+ # --train \
34
+ # --name $name \
35
+ # --logdir $save_root \
36
+ # --devices 4 \
37
+ # lightning.trainer.num_nodes=1
gradio_app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, argparse
2
+ import sys
3
+ import gradio as gr
4
+ from scripts.gradio.i2v_test_application import Image2Video
5
+ sys.path.insert(1, os.path.join(sys.path[0], 'lvdm'))
6
+
7
+
8
+ i2v_examples_interp_512 = [
9
+ ['prompts/512_interp/74906_1462_frame1.png', 'walking man', 50, 7.5, 1.0, 10, 123, 'prompts/512_interp/74906_1462_frame3.png'],
10
+ ['prompts/512_interp/Japan_v2_2_062266_s2_frame1.png', 'an anime scene', 50, 7.5, 1.0, 10, 789, 'prompts/512_interp/Japan_v2_2_062266_s2_frame3.png'],
11
+ ['prompts/512_interp/Japan_v2_3_119235_s2_frame1.png', 'an anime scene', 50, 7.5, 1.0, 10, 123, 'prompts/512_interp/Japan_v2_3_119235_s2_frame3.png'],
12
+ ]
13
+
14
+
15
+
16
+
17
+ def dynamicrafter_demo(result_dir='./tmp/', res=512):
18
+ if res == 1024:
19
+ resolution = '576_1024'
20
+ css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height:576px}"""
21
+ elif res == 512:
22
+ resolution = '320_512'
23
+ css = """#input_img {max-width: 512px !important} #output_vid {max-width: 512px; max-height: 320px} #input_img2 {max-width: 512px !important} #output_vid {max-width: 512px; max-height: 320px}"""
24
+ elif res == 256:
25
+ resolution = '256_256'
26
+ css = """#input_img {max-width: 256px !important} #output_vid {max-width: 256px; max-height: 256px}"""
27
+ else:
28
+ raise NotImplementedError(f"Unsupported resolution: {res}")
29
+ image2video = Image2Video(result_dir, resolution=resolution)
30
+ with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface:
31
+
32
+
33
+
34
+ with gr.Tab(label='ToonCrafter_320x512'):
35
+ with gr.Column():
36
+ with gr.Row():
37
+ with gr.Column():
38
+ with gr.Row():
39
+ i2v_input_image = gr.Image(label="Input Image1",elem_id="input_img")
40
+ with gr.Row():
41
+ i2v_input_text = gr.Text(label='Prompts')
42
+ with gr.Row():
43
+ i2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=50000, step=1, value=123)
44
+ i2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0, elem_id="i2v_eta")
45
+ i2v_cfg_scale = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, label='CFG Scale', value=7.5, elem_id="i2v_cfg_scale")
46
+ with gr.Row():
47
+ i2v_steps = gr.Slider(minimum=1, maximum=60, step=1, elem_id="i2v_steps", label="Sampling steps", value=50)
48
+ i2v_motion = gr.Slider(minimum=5, maximum=30, step=1, elem_id="i2v_motion", label="FPS", value=10)
49
+ i2v_end_btn = gr.Button("Generate")
50
+ with gr.Column():
51
+ with gr.Row():
52
+ i2v_input_image2 = gr.Image(label="Input Image2",elem_id="input_img2")
53
+ with gr.Row():
54
+ i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True)
55
+
56
+ gr.Examples(examples=i2v_examples_interp_512,
57
+ inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, i2v_input_image2],
58
+ outputs=[i2v_output_video],
59
+ fn = image2video.get_image,
60
+ cache_examples=False,
61
+ )
62
+ i2v_end_btn.click(inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, i2v_input_image2],
63
+ outputs=[i2v_output_video],
64
+ fn = image2video.get_image
65
+ )
66
+
67
+
68
+ return dynamicrafter_iface
69
+
70
+ def get_parser():
71
+ parser = argparse.ArgumentParser()
72
+ return parser
73
+
74
+ if __name__ == "__main__":
75
+ parser = get_parser()
76
+ args = parser.parse_args()
77
+
78
+ result_dir = os.path.join('./', 'results')
79
+ dynamicrafter_iface = dynamicrafter_demo(result_dir)
80
+ dynamicrafter_iface.queue(max_size=12)
81
+ dynamicrafter_iface.launch(max_threads=1)
82
+ # dynamicrafter_iface.launch(server_name='0.0.0.0', server_port=80, max_threads=1)
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]}
lvdm/common.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from inspect import isfunction
3
+ import torch
4
+ from torch import nn
5
+ import torch.distributed as dist
6
+
7
+
8
+ def gather_data(data, return_np=True):
9
+ ''' gather data from multiple processes to one list '''
10
+ data_list = [torch.zeros_like(data) for _ in range(dist.get_world_size())]
11
+ dist.all_gather(data_list, data) # gather not supported with NCCL
12
+ if return_np:
13
+ data_list = [data.cpu().numpy() for data in data_list]
14
+ return data_list
15
+
16
+ def autocast(f):
17
+ def do_autocast(*args, **kwargs):
18
+ with torch.cuda.amp.autocast(enabled=True,
19
+ dtype=torch.get_autocast_gpu_dtype(),
20
+ cache_enabled=torch.is_autocast_cache_enabled()):
21
+ return f(*args, **kwargs)
22
+ return do_autocast
23
+
24
+
25
+ def extract_into_tensor(a, t, x_shape):
26
+ b, *_ = t.shape
27
+ out = a.gather(-1, t)
28
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
29
+
30
+
31
+ def noise_like(shape, device, repeat=False):
32
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
33
+ noise = lambda: torch.randn(shape, device=device)
34
+ return repeat_noise() if repeat else noise()
35
+
36
+
37
+ def default(val, d):
38
+ if exists(val):
39
+ return val
40
+ return d() if isfunction(d) else d
41
+
42
+ def exists(val):
43
+ return val is not None
44
+
45
+ def identity(*args, **kwargs):
46
+ return nn.Identity()
47
+
48
+ def uniq(arr):
49
+ return{el: True for el in arr}.keys()
50
+
51
+ def mean_flat(tensor):
52
+ """
53
+ Take the mean over all non-batch dimensions.
54
+ """
55
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
56
+
57
+ def ismap(x):
58
+ if not isinstance(x, torch.Tensor):
59
+ return False
60
+ return (len(x.shape) == 4) and (x.shape[1] > 3)
61
+
62
+ def isimage(x):
63
+ if not isinstance(x,torch.Tensor):
64
+ return False
65
+ return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
66
+
67
+ def max_neg_value(t):
68
+ return -torch.finfo(t.dtype).max
69
+
70
+ def shape_to_str(x):
71
+ shape_str = "x".join([str(x) for x in x.shape])
72
+ return shape_str
73
+
74
+ def init_(tensor):
75
+ dim = tensor.shape[-1]
76
+ std = 1 / math.sqrt(dim)
77
+ tensor.uniform_(-std, std)
78
+ return tensor
79
+
80
+ ckpt = torch.utils.checkpoint.checkpoint
81
+ def checkpoint(func, inputs, params, flag):
82
+ """
83
+ Evaluate a function without caching intermediate activations, allowing for
84
+ reduced memory at the expense of extra compute in the backward pass.
85
+ :param func: the function to evaluate.
86
+ :param inputs: the argument sequence to pass to `func`.
87
+ :param params: a sequence of parameters `func` depends on but does not
88
+ explicitly take as arguments.
89
+ :param flag: if False, disable gradient checkpointing.
90
+ """
91
+ if flag:
92
+ return ckpt(func, *inputs, use_reentrant=False)
93
+ else:
94
+ return func(*inputs)
lvdm/data/base.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+ from torch.utils.data import IterableDataset
3
+
4
+
5
+ class Txt2ImgIterableBaseDataset(IterableDataset):
6
+ '''
7
+ Define an interface to make the IterableDatasets for text2img data chainable
8
+ '''
9
+ def __init__(self, num_records=0, valid_ids=None, size=256):
10
+ super().__init__()
11
+ self.num_records = num_records
12
+ self.valid_ids = valid_ids
13
+ self.sample_ids = valid_ids
14
+ self.size = size
15
+
16
+ print(f'{self.__class__.__name__} dataset contains {self.__len__()} examples.')
17
+
18
+ def __len__(self):
19
+ return self.num_records
20
+
21
+ @abstractmethod
22
+ def __iter__(self):
23
+ pass
lvdm/data/webvid.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ from tqdm import tqdm
4
+ import pandas as pd
5
+ from decord import VideoReader, cpu
6
+
7
+ import torch
8
+ from torch.utils.data import Dataset
9
+ from torch.utils.data import DataLoader
10
+ from torchvision import transforms
11
+
12
+
13
+ class WebVid(Dataset):
14
+ """
15
+ WebVid Dataset.
16
+ Assumes webvid data is structured as follows.
17
+ Webvid/
18
+ videos/
19
+ 000001_000050/ ($page_dir)
20
+ 1.mp4 (videoid.mp4)
21
+ ...
22
+ 5000.mp4
23
+ ...
24
+ """
25
+ def __init__(self,
26
+ meta_path,
27
+ data_dir,
28
+ subsample=None,
29
+ video_length=16,
30
+ resolution=[256, 512],
31
+ frame_stride=1,
32
+ frame_stride_min=1,
33
+ spatial_transform=None,
34
+ crop_resolution=None,
35
+ fps_max=None,
36
+ load_raw_resolution=False,
37
+ fixed_fps=None,
38
+ random_fs=False,
39
+ ):
40
+ self.meta_path = meta_path
41
+ self.data_dir = data_dir
42
+ self.subsample = subsample
43
+ self.video_length = video_length
44
+ self.resolution = [resolution, resolution] if isinstance(resolution, int) else resolution
45
+ self.fps_max = fps_max
46
+ self.frame_stride = frame_stride
47
+ self.frame_stride_min = frame_stride_min
48
+ self.fixed_fps = fixed_fps
49
+ self.load_raw_resolution = load_raw_resolution
50
+ self.random_fs = random_fs
51
+ self._load_metadata()
52
+ if spatial_transform is not None:
53
+ if spatial_transform == "random_crop":
54
+ self.spatial_transform = transforms.RandomCrop(crop_resolution)
55
+ elif spatial_transform == "center_crop":
56
+ self.spatial_transform = transforms.Compose([
57
+ transforms.CenterCrop(resolution),
58
+ ])
59
+ elif spatial_transform == "resize_center_crop":
60
+ # assert(self.resolution[0] == self.resolution[1])
61
+ self.spatial_transform = transforms.Compose([
62
+ transforms.Resize(min(self.resolution)),
63
+ transforms.CenterCrop(self.resolution),
64
+ ])
65
+ elif spatial_transform == "resize":
66
+ self.spatial_transform = transforms.Resize(self.resolution)
67
+ else:
68
+ raise NotImplementedError
69
+ else:
70
+ self.spatial_transform = None
71
+
72
+ def _load_metadata(self):
73
+ metadata = pd.read_csv(self.meta_path)
74
+ print(f'>>> {len(metadata)} data samples loaded.')
75
+ if self.subsample is not None:
76
+ metadata = metadata.sample(self.subsample, random_state=0)
77
+
78
+ metadata['caption'] = metadata['name']
79
+ del metadata['name']
80
+ self.metadata = metadata
81
+ self.metadata.dropna(inplace=True)
82
+
83
+ def _get_video_path(self, sample):
84
+ rel_video_fp = os.path.join(sample['page_dir'], str(sample['videoid']) + '.mp4')
85
+ full_video_fp = os.path.join(self.data_dir, 'videos', rel_video_fp)
86
+ return full_video_fp
87
+
88
+ def __getitem__(self, index):
89
+ if self.random_fs:
90
+ frame_stride = random.randint(self.frame_stride_min, self.frame_stride)
91
+ else:
92
+ frame_stride = self.frame_stride
93
+
94
+ ## get frames until success
95
+ while True:
96
+ index = index % len(self.metadata)
97
+ sample = self.metadata.iloc[index]
98
+ video_path = self._get_video_path(sample)
99
+ ## video_path should be in the format of "....../WebVid/videos/$page_dir/$videoid.mp4"
100
+ caption = sample['caption']
101
+
102
+ try:
103
+ if self.load_raw_resolution:
104
+ video_reader = VideoReader(video_path, ctx=cpu(0))
105
+ else:
106
+ video_reader = VideoReader(video_path, ctx=cpu(0), width=530, height=300)
107
+ if len(video_reader) < self.video_length:
108
+ print(f"video length ({len(video_reader)}) is smaller than target length({self.video_length})")
109
+ index += 1
110
+ continue
111
+ else:
112
+ pass
113
+ except:
114
+ index += 1
115
+ print(f"Load video failed! path = {video_path}")
116
+ continue
117
+
118
+ fps_ori = video_reader.get_avg_fps()
119
+ if self.fixed_fps is not None:
120
+ frame_stride = int(frame_stride * (1.0 * fps_ori / self.fixed_fps))
121
+
122
+ ## to avoid extreme cases when fixed_fps is used
123
+ frame_stride = max(frame_stride, 1)
124
+
125
+ ## get valid range (adapting case by case)
126
+ required_frame_num = frame_stride * (self.video_length-1) + 1
127
+ frame_num = len(video_reader)
128
+ if frame_num < required_frame_num:
129
+ ## drop extra samples if fixed fps is required
130
+ if self.fixed_fps is not None and frame_num < required_frame_num * 0.5:
131
+ index += 1
132
+ continue
133
+ else:
134
+ frame_stride = frame_num // self.video_length
135
+ required_frame_num = frame_stride * (self.video_length-1) + 1
136
+
137
+ ## select a random clip
138
+ random_range = frame_num - required_frame_num
139
+ start_idx = random.randint(0, random_range) if random_range > 0 else 0
140
+
141
+ ## calculate frame indices
142
+ frame_indices = [start_idx + frame_stride*i for i in range(self.video_length)]
143
+ try:
144
+ frames = video_reader.get_batch(frame_indices)
145
+ break
146
+ except:
147
+ print(f"Get frames failed! path = {video_path}; [max_ind vs frame_total:{max(frame_indices)} / {frame_num}]")
148
+ index += 1
149
+ continue
150
+
151
+ ## process data
152
+ assert(frames.shape[0] == self.video_length),f'{len(frames)}, self.video_length={self.video_length}'
153
+ frames = torch.tensor(frames.asnumpy()).permute(3, 0, 1, 2).float() # [t,h,w,c] -> [c,t,h,w]
154
+
155
+ if self.spatial_transform is not None:
156
+ frames = self.spatial_transform(frames)
157
+
158
+ if self.resolution is not None:
159
+ assert (frames.shape[2], frames.shape[3]) == (self.resolution[0], self.resolution[1]), f'frames={frames.shape}, self.resolution={self.resolution}'
160
+
161
+ ## turn frames tensors to [-1,1]
162
+ frames = (frames / 255 - 0.5) * 2
163
+ fps_clip = fps_ori // frame_stride
164
+ if self.fps_max is not None and fps_clip > self.fps_max:
165
+ fps_clip = self.fps_max
166
+
167
+ data = {'video': frames, 'caption': caption, 'path': video_path, 'fps': fps_clip, 'frame_stride': frame_stride}
168
+ return data
169
+
170
+ def __len__(self):
171
+ return len(self.metadata)
172
+
173
+
174
+ if __name__== "__main__":
175
+ meta_path = "" ## path to the meta file
176
+ data_dir = "" ## path to the data directory
177
+ save_dir = "" ## path to the save directory
178
+ dataset = WebVid(meta_path,
179
+ data_dir,
180
+ subsample=None,
181
+ video_length=16,
182
+ resolution=[256,448],
183
+ frame_stride=4,
184
+ spatial_transform="resize_center_crop",
185
+ crop_resolution=None,
186
+ fps_max=None,
187
+ load_raw_resolution=True
188
+ )
189
+ dataloader = DataLoader(dataset,
190
+ batch_size=1,
191
+ num_workers=0,
192
+ shuffle=False)
193
+
194
+
195
+ import sys
196
+ sys.path.insert(1, os.path.join(sys.path[0], '..', '..'))
197
+ from utils.save_video import tensor_to_mp4
198
+ for i, batch in tqdm(enumerate(dataloader), desc="Data Batch"):
199
+ video = batch['video']
200
+ name = batch['path'][0].split('videos/')[-1].replace('/','_')
201
+ tensor_to_mp4(video, save_dir+'/'+name, fps=8)
202
+
lvdm/distributions.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ class AbstractDistribution:
6
+ def sample(self):
7
+ raise NotImplementedError()
8
+
9
+ def mode(self):
10
+ raise NotImplementedError()
11
+
12
+
13
+ class DiracDistribution(AbstractDistribution):
14
+ def __init__(self, value):
15
+ self.value = value
16
+
17
+ def sample(self):
18
+ return self.value
19
+
20
+ def mode(self):
21
+ return self.value
22
+
23
+
24
+ class DiagonalGaussianDistribution(object):
25
+ def __init__(self, parameters, deterministic=False):
26
+ self.parameters = parameters
27
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
28
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
29
+ self.deterministic = deterministic
30
+ self.std = torch.exp(0.5 * self.logvar)
31
+ self.var = torch.exp(self.logvar)
32
+ if self.deterministic:
33
+ self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
34
+
35
+ def sample(self, noise=None):
36
+ if noise is None:
37
+ noise = torch.randn(self.mean.shape)
38
+
39
+ x = self.mean + self.std * noise.to(device=self.parameters.device)
40
+ return x
41
+
42
+ def kl(self, other=None):
43
+ if self.deterministic:
44
+ return torch.Tensor([0.])
45
+ else:
46
+ if other is None:
47
+ return 0.5 * torch.sum(torch.pow(self.mean, 2)
48
+ + self.var - 1.0 - self.logvar,
49
+ dim=[1, 2, 3])
50
+ else:
51
+ return 0.5 * torch.sum(
52
+ torch.pow(self.mean - other.mean, 2) / other.var
53
+ + self.var / other.var - 1.0 - self.logvar + other.logvar,
54
+ dim=[1, 2, 3])
55
+
56
+ def nll(self, sample, dims=[1,2,3]):
57
+ if self.deterministic:
58
+ return torch.Tensor([0.])
59
+ logtwopi = np.log(2.0 * np.pi)
60
+ return 0.5 * torch.sum(
61
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
62
+ dim=dims)
63
+
64
+ def mode(self):
65
+ return self.mean
66
+
67
+
68
+ def normal_kl(mean1, logvar1, mean2, logvar2):
69
+ """
70
+ source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
71
+ Compute the KL divergence between two gaussians.
72
+ Shapes are automatically broadcasted, so batches can be compared to
73
+ scalars, among other use cases.
74
+ """
75
+ tensor = None
76
+ for obj in (mean1, logvar1, mean2, logvar2):
77
+ if isinstance(obj, torch.Tensor):
78
+ tensor = obj
79
+ break
80
+ assert tensor is not None, "at least one argument must be a Tensor"
81
+
82
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
83
+ # Tensors, but it does not work for torch.exp().
84
+ logvar1, logvar2 = [
85
+ x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
86
+ for x in (logvar1, logvar2)
87
+ ]
88
+
89
+ return 0.5 * (
90
+ -1.0
91
+ + logvar2
92
+ - logvar1
93
+ + torch.exp(logvar1 - logvar2)
94
+ + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
95
+ )
lvdm/ema.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class LitEma(nn.Module):
6
+ def __init__(self, model, decay=0.9999, use_num_upates=True):
7
+ super().__init__()
8
+ if decay < 0.0 or decay > 1.0:
9
+ raise ValueError('Decay must be between 0 and 1')
10
+
11
+ self.m_name2s_name = {}
12
+ self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
13
+ self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates
14
+ else torch.tensor(-1,dtype=torch.int))
15
+
16
+ for name, p in model.named_parameters():
17
+ if p.requires_grad:
18
+ #remove as '.'-character is not allowed in buffers
19
+ s_name = name.replace('.','')
20
+ self.m_name2s_name.update({name:s_name})
21
+ self.register_buffer(s_name,p.clone().detach().data)
22
+
23
+ self.collected_params = []
24
+
25
+ def forward(self,model):
26
+ decay = self.decay
27
+
28
+ if self.num_updates >= 0:
29
+ self.num_updates += 1
30
+ decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))
31
+
32
+ one_minus_decay = 1.0 - decay
33
+
34
+ with torch.no_grad():
35
+ m_param = dict(model.named_parameters())
36
+ shadow_params = dict(self.named_buffers())
37
+
38
+ for key in m_param:
39
+ if m_param[key].requires_grad:
40
+ sname = self.m_name2s_name[key]
41
+ shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
42
+ shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
43
+ else:
44
+ assert not key in self.m_name2s_name
45
+
46
+ def copy_to(self, model):
47
+ m_param = dict(model.named_parameters())
48
+ shadow_params = dict(self.named_buffers())
49
+ for key in m_param:
50
+ if m_param[key].requires_grad:
51
+ m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
52
+ else:
53
+ assert not key in self.m_name2s_name
54
+
55
+ def store(self, parameters):
56
+ """
57
+ Save the current parameters for restoring later.
58
+ Args:
59
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
60
+ temporarily stored.
61
+ """
62
+ self.collected_params = [param.clone() for param in parameters]
63
+
64
+ def restore(self, parameters):
65
+ """
66
+ Restore the parameters stored with the `store` method.
67
+ Useful to validate the model with EMA parameters without affecting the
68
+ original optimization process. Store the parameters before the
69
+ `copy_to` method. After validation (or model saving), use this to
70
+ restore the former parameters.
71
+ Args:
72
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
73
+ updated with the stored parameters.
74
+ """
75
+ for c_param, param in zip(self.collected_params, parameters):
76
+ param.data.copy_(c_param.data)
lvdm/models/autoencoder.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from contextlib import contextmanager
3
+ import torch
4
+ import numpy as np
5
+ from einops import rearrange
6
+ import torch.nn.functional as F
7
+ import pytorch_lightning as pl
8
+ from lvdm.modules.networks.ae_modules import Encoder, Decoder
9
+ from lvdm.distributions import DiagonalGaussianDistribution
10
+ from utils.utils import instantiate_from_config
11
+
12
+ TIMESTEPS=16
13
+ class AutoencoderKL(pl.LightningModule):
14
+ def __init__(self,
15
+ ddconfig,
16
+ lossconfig,
17
+ embed_dim,
18
+ ckpt_path=None,
19
+ ignore_keys=[],
20
+ image_key="image",
21
+ colorize_nlabels=None,
22
+ monitor=None,
23
+ test=False,
24
+ logdir=None,
25
+ input_dim=4,
26
+ test_args=None,
27
+ additional_decode_keys=None,
28
+ use_checkpoint=False,
29
+ diff_boost_factor=3.0,
30
+ ):
31
+ super().__init__()
32
+ self.image_key = image_key
33
+ self.encoder = Encoder(**ddconfig)
34
+ self.decoder = Decoder(**ddconfig)
35
+ self.loss = instantiate_from_config(lossconfig)
36
+ assert ddconfig["double_z"]
37
+ self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
38
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
39
+ self.embed_dim = embed_dim
40
+ self.input_dim = input_dim
41
+ self.test = test
42
+ self.test_args = test_args
43
+ self.logdir = logdir
44
+ if colorize_nlabels is not None:
45
+ assert type(colorize_nlabels)==int
46
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
47
+ if monitor is not None:
48
+ self.monitor = monitor
49
+ if ckpt_path is not None:
50
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
51
+ if self.test:
52
+ self.init_test()
53
+
54
+ def init_test(self,):
55
+ self.test = True
56
+ save_dir = os.path.join(self.logdir, "test")
57
+ if 'ckpt' in self.test_args:
58
+ ckpt_name = os.path.basename(self.test_args.ckpt).split('.ckpt')[0] + f'_epoch{self._cur_epoch}'
59
+ self.root = os.path.join(save_dir, ckpt_name)
60
+ else:
61
+ self.root = save_dir
62
+ if 'test_subdir' in self.test_args:
63
+ self.root = os.path.join(save_dir, self.test_args.test_subdir)
64
+
65
+ self.root_zs = os.path.join(self.root, "zs")
66
+ self.root_dec = os.path.join(self.root, "reconstructions")
67
+ self.root_inputs = os.path.join(self.root, "inputs")
68
+ os.makedirs(self.root, exist_ok=True)
69
+
70
+ if self.test_args.save_z:
71
+ os.makedirs(self.root_zs, exist_ok=True)
72
+ if self.test_args.save_reconstruction:
73
+ os.makedirs(self.root_dec, exist_ok=True)
74
+ if self.test_args.save_input:
75
+ os.makedirs(self.root_inputs, exist_ok=True)
76
+ assert(self.test_args is not None)
77
+ self.test_maximum = getattr(self.test_args, 'test_maximum', None)
78
+ self.count = 0
79
+ self.eval_metrics = {}
80
+ self.decodes = []
81
+ self.save_decode_samples = 2048
82
+
83
+ def init_from_ckpt(self, path, ignore_keys=list()):
84
+ sd = torch.load(path, map_location="cpu")
85
+ try:
86
+ self._cur_epoch = sd['epoch']
87
+ sd = sd["state_dict"]
88
+ except:
89
+ self._cur_epoch = 'null'
90
+ keys = list(sd.keys())
91
+ for k in keys:
92
+ for ik in ignore_keys:
93
+ if k.startswith(ik):
94
+ print("Deleting key {} from state_dict.".format(k))
95
+ del sd[k]
96
+ self.load_state_dict(sd, strict=False)
97
+ # self.load_state_dict(sd, strict=True)
98
+ print(f"Restored from {path}")
99
+
100
+ def encode(self, x, return_hidden_states=False, **kwargs):
101
+ if return_hidden_states:
102
+ h, hidden = self.encoder(x, return_hidden_states)
103
+ moments = self.quant_conv(h)
104
+ posterior = DiagonalGaussianDistribution(moments)
105
+ return posterior, hidden
106
+ else:
107
+ h = self.encoder(x)
108
+ moments = self.quant_conv(h)
109
+ posterior = DiagonalGaussianDistribution(moments)
110
+ return posterior
111
+
112
+ def decode(self, z, **kwargs):
113
+ if len(kwargs) == 0: ## use the original decoder in AutoencoderKL
114
+ z = self.post_quant_conv(z)
115
+ dec = self.decoder(z, **kwargs) ##change for SVD decoder by adding **kwargs
116
+ return dec
117
+
118
+ def forward(self, input, sample_posterior=True, **additional_decode_kwargs):
119
+ input_tuple = (input, )
120
+ forward_temp = partial(self._forward, sample_posterior=sample_posterior, **additional_decode_kwargs)
121
+ return checkpoint(forward_temp, input_tuple, self.parameters(), self.use_checkpoint)
122
+
123
+
124
+ def _forward(self, input, sample_posterior=True, **additional_decode_kwargs):
125
+ posterior = self.encode(input)
126
+ if sample_posterior:
127
+ z = posterior.sample()
128
+ else:
129
+ z = posterior.mode()
130
+ dec = self.decode(z, **additional_decode_kwargs)
131
+ ## print(input.shape, dec.shape) torch.Size([16, 3, 256, 256]) torch.Size([16, 3, 256, 256])
132
+ return dec, posterior
133
+
134
+ def get_input(self, batch, k):
135
+ x = batch[k]
136
+ if x.dim() == 5 and self.input_dim == 4:
137
+ b,c,t,h,w = x.shape
138
+ self.b = b
139
+ self.t = t
140
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
141
+
142
+ return x
143
+
144
+ def training_step(self, batch, batch_idx, optimizer_idx):
145
+ inputs = self.get_input(batch, self.image_key)
146
+ reconstructions, posterior = self(inputs)
147
+
148
+ if optimizer_idx == 0:
149
+ # train encoder+decoder+logvar
150
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
151
+ last_layer=self.get_last_layer(), split="train")
152
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
153
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
154
+ return aeloss
155
+
156
+ if optimizer_idx == 1:
157
+ # train the discriminator
158
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
159
+ last_layer=self.get_last_layer(), split="train")
160
+
161
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
162
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
163
+ return discloss
164
+
165
+ def validation_step(self, batch, batch_idx):
166
+ inputs = self.get_input(batch, self.image_key)
167
+ reconstructions, posterior = self(inputs)
168
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
169
+ last_layer=self.get_last_layer(), split="val")
170
+
171
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
172
+ last_layer=self.get_last_layer(), split="val")
173
+
174
+ self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
175
+ self.log_dict(log_dict_ae)
176
+ self.log_dict(log_dict_disc)
177
+ return self.log_dict
178
+
179
+ def configure_optimizers(self):
180
+ lr = self.learning_rate
181
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
182
+ list(self.decoder.parameters())+
183
+ list(self.quant_conv.parameters())+
184
+ list(self.post_quant_conv.parameters()),
185
+ lr=lr, betas=(0.5, 0.9))
186
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
187
+ lr=lr, betas=(0.5, 0.9))
188
+ return [opt_ae, opt_disc], []
189
+
190
+ def get_last_layer(self):
191
+ return self.decoder.conv_out.weight
192
+
193
+ @torch.no_grad()
194
+ def log_images(self, batch, only_inputs=False, **kwargs):
195
+ log = dict()
196
+ x = self.get_input(batch, self.image_key)
197
+ x = x.to(self.device)
198
+ if not only_inputs:
199
+ xrec, posterior = self(x)
200
+ if x.shape[1] > 3:
201
+ # colorize with random projection
202
+ assert xrec.shape[1] > 3
203
+ x = self.to_rgb(x)
204
+ xrec = self.to_rgb(xrec)
205
+ log["samples"] = self.decode(torch.randn_like(posterior.sample()))
206
+ log["reconstructions"] = xrec
207
+ log["inputs"] = x
208
+ return log
209
+
210
+ def to_rgb(self, x):
211
+ assert self.image_key == "segmentation"
212
+ if not hasattr(self, "colorize"):
213
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
214
+ x = F.conv2d(x, weight=self.colorize)
215
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
216
+ return x
217
+
218
+ class IdentityFirstStage(torch.nn.Module):
219
+ def __init__(self, *args, vq_interface=False, **kwargs):
220
+ self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
221
+ super().__init__()
222
+
223
+ def encode(self, x, *args, **kwargs):
224
+ return x
225
+
226
+ def decode(self, x, *args, **kwargs):
227
+ return x
228
+
229
+ def quantize(self, x, *args, **kwargs):
230
+ if self.vq_interface:
231
+ return x, None, [None, None, None]
232
+ return x
233
+
234
+ def forward(self, x, *args, **kwargs):
235
+ return x
236
+
237
+ from lvdm.models.autoencoder_dualref import VideoDecoder
238
+ class AutoencoderKL_Dualref(AutoencoderKL):
239
+ def __init__(self,
240
+ ddconfig,
241
+ lossconfig,
242
+ embed_dim,
243
+ ckpt_path=None,
244
+ ignore_keys=[],
245
+ image_key="image",
246
+ colorize_nlabels=None,
247
+ monitor=None,
248
+ test=False,
249
+ logdir=None,
250
+ input_dim=4,
251
+ test_args=None,
252
+ additional_decode_keys=None,
253
+ use_checkpoint=False,
254
+ diff_boost_factor=3.0,
255
+ ):
256
+ super().__init__(ddconfig, lossconfig, embed_dim, ckpt_path, ignore_keys, image_key, colorize_nlabels, monitor, test, logdir, input_dim, test_args, additional_decode_keys, use_checkpoint, diff_boost_factor)
257
+ self.decoder = VideoDecoder(**ddconfig)
258
+
259
+ def _forward(self, input, sample_posterior=True, **additional_decode_kwargs):
260
+ posterior, hidden_states = self.encode(input, return_hidden_states=True)
261
+
262
+ hidden_states_first_last = []
263
+ ### use only the first and last hidden states
264
+ for hid in hidden_states:
265
+ hid = rearrange(hid, '(b t) c h w -> b c t h w', t=TIMESTEPS)
266
+ hid_new = torch.cat([hid[:, :, 0:1], hid[:, :, -1:]], dim=2)
267
+ hidden_states_first_last.append(hid_new)
268
+
269
+ if sample_posterior:
270
+ z = posterior.sample()
271
+ else:
272
+ z = posterior.mode()
273
+ dec = self.decode(z, ref_context=hidden_states_first_last, **additional_decode_kwargs)
274
+ ## print(input.shape, dec.shape) torch.Size([16, 3, 256, 256]) torch.Size([16, 3, 256, 256])
275
+ return dec, posterior
lvdm/models/autoencoder_dualref.py ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #### https://github.com/Stability-AI/generative-models
2
+ from einops import rearrange, repeat
3
+ import logging
4
+ from typing import Any, Callable, Optional, Iterable, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn as nn
9
+ from packaging import version
10
+ logpy = logging.getLogger(__name__)
11
+
12
+ try:
13
+ import xformers
14
+ import xformers.ops
15
+
16
+ XFORMERS_IS_AVAILABLE = True
17
+ except:
18
+ XFORMERS_IS_AVAILABLE = False
19
+ logpy.warning("no module 'xformers'. Processing without...")
20
+
21
+ from lvdm.modules.attention_svd import LinearAttention, MemoryEfficientCrossAttention
22
+
23
+
24
+ def nonlinearity(x):
25
+ # swish
26
+ return x * torch.sigmoid(x)
27
+
28
+
29
+ def Normalize(in_channels, num_groups=32):
30
+ return torch.nn.GroupNorm(
31
+ num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True
32
+ )
33
+
34
+
35
+ class ResnetBlock(nn.Module):
36
+ def __init__(
37
+ self,
38
+ *,
39
+ in_channels,
40
+ out_channels=None,
41
+ conv_shortcut=False,
42
+ dropout,
43
+ temb_channels=512,
44
+ ):
45
+ super().__init__()
46
+ self.in_channels = in_channels
47
+ out_channels = in_channels if out_channels is None else out_channels
48
+ self.out_channels = out_channels
49
+ self.use_conv_shortcut = conv_shortcut
50
+
51
+ self.norm1 = Normalize(in_channels)
52
+ self.conv1 = torch.nn.Conv2d(
53
+ in_channels, out_channels, kernel_size=3, stride=1, padding=1
54
+ )
55
+ if temb_channels > 0:
56
+ self.temb_proj = torch.nn.Linear(temb_channels, out_channels)
57
+ self.norm2 = Normalize(out_channels)
58
+ self.dropout = torch.nn.Dropout(dropout)
59
+ self.conv2 = torch.nn.Conv2d(
60
+ out_channels, out_channels, kernel_size=3, stride=1, padding=1
61
+ )
62
+ if self.in_channels != self.out_channels:
63
+ if self.use_conv_shortcut:
64
+ self.conv_shortcut = torch.nn.Conv2d(
65
+ in_channels, out_channels, kernel_size=3, stride=1, padding=1
66
+ )
67
+ else:
68
+ self.nin_shortcut = torch.nn.Conv2d(
69
+ in_channels, out_channels, kernel_size=1, stride=1, padding=0
70
+ )
71
+
72
+ def forward(self, x, temb):
73
+ h = x
74
+ h = self.norm1(h)
75
+ h = nonlinearity(h)
76
+ h = self.conv1(h)
77
+
78
+ if temb is not None:
79
+ h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None]
80
+
81
+ h = self.norm2(h)
82
+ h = nonlinearity(h)
83
+ h = self.dropout(h)
84
+ h = self.conv2(h)
85
+
86
+ if self.in_channels != self.out_channels:
87
+ if self.use_conv_shortcut:
88
+ x = self.conv_shortcut(x)
89
+ else:
90
+ x = self.nin_shortcut(x)
91
+
92
+ return x + h
93
+
94
+
95
+ class LinAttnBlock(LinearAttention):
96
+ """to match AttnBlock usage"""
97
+
98
+ def __init__(self, in_channels):
99
+ super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
100
+
101
+
102
+ class AttnBlock(nn.Module):
103
+ def __init__(self, in_channels):
104
+ super().__init__()
105
+ self.in_channels = in_channels
106
+
107
+ self.norm = Normalize(in_channels)
108
+ self.q = torch.nn.Conv2d(
109
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
110
+ )
111
+ self.k = torch.nn.Conv2d(
112
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
113
+ )
114
+ self.v = torch.nn.Conv2d(
115
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
116
+ )
117
+ self.proj_out = torch.nn.Conv2d(
118
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
119
+ )
120
+
121
+ def attention(self, h_: torch.Tensor) -> torch.Tensor:
122
+ h_ = self.norm(h_)
123
+ q = self.q(h_)
124
+ k = self.k(h_)
125
+ v = self.v(h_)
126
+
127
+ b, c, h, w = q.shape
128
+ q, k, v = map(
129
+ lambda x: rearrange(x, "b c h w -> b 1 (h w) c").contiguous(), (q, k, v)
130
+ )
131
+ h_ = torch.nn.functional.scaled_dot_product_attention(
132
+ q, k, v
133
+ ) # scale is dim ** -0.5 per default
134
+ # compute attention
135
+
136
+ return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
137
+
138
+ def forward(self, x, **kwargs):
139
+ h_ = x
140
+ h_ = self.attention(h_)
141
+ h_ = self.proj_out(h_)
142
+ return x + h_
143
+
144
+
145
+ class MemoryEfficientAttnBlock(nn.Module):
146
+ """
147
+ Uses xformers efficient implementation,
148
+ see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
149
+ Note: this is a single-head self-attention operation
150
+ """
151
+
152
+ #
153
+ def __init__(self, in_channels):
154
+ super().__init__()
155
+ self.in_channels = in_channels
156
+
157
+ self.norm = Normalize(in_channels)
158
+ self.q = torch.nn.Conv2d(
159
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
160
+ )
161
+ self.k = torch.nn.Conv2d(
162
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
163
+ )
164
+ self.v = torch.nn.Conv2d(
165
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
166
+ )
167
+ self.proj_out = torch.nn.Conv2d(
168
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
169
+ )
170
+ self.attention_op: Optional[Any] = None
171
+
172
+ def attention(self, h_: torch.Tensor) -> torch.Tensor:
173
+ h_ = self.norm(h_)
174
+ q = self.q(h_)
175
+ k = self.k(h_)
176
+ v = self.v(h_)
177
+
178
+ # compute attention
179
+ B, C, H, W = q.shape
180
+ q, k, v = map(lambda x: rearrange(x, "b c h w -> b (h w) c"), (q, k, v))
181
+
182
+ q, k, v = map(
183
+ lambda t: t.unsqueeze(3)
184
+ .reshape(B, t.shape[1], 1, C)
185
+ .permute(0, 2, 1, 3)
186
+ .reshape(B * 1, t.shape[1], C)
187
+ .contiguous(),
188
+ (q, k, v),
189
+ )
190
+ out = xformers.ops.memory_efficient_attention(
191
+ q, k, v, attn_bias=None, op=self.attention_op
192
+ )
193
+
194
+ out = (
195
+ out.unsqueeze(0)
196
+ .reshape(B, 1, out.shape[1], C)
197
+ .permute(0, 2, 1, 3)
198
+ .reshape(B, out.shape[1], C)
199
+ )
200
+ return rearrange(out, "b (h w) c -> b c h w", b=B, h=H, w=W, c=C)
201
+
202
+ def forward(self, x, **kwargs):
203
+ h_ = x
204
+ h_ = self.attention(h_)
205
+ h_ = self.proj_out(h_)
206
+ return x + h_
207
+
208
+
209
+ class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention):
210
+ def forward(self, x, context=None, mask=None, **unused_kwargs):
211
+ b, c, h, w = x.shape
212
+ x = rearrange(x, "b c h w -> b (h w) c")
213
+ out = super().forward(x, context=context, mask=mask)
214
+ out = rearrange(out, "b (h w) c -> b c h w", h=h, w=w, c=c)
215
+ return x + out
216
+
217
+
218
+ def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
219
+ assert attn_type in [
220
+ "vanilla",
221
+ "vanilla-xformers",
222
+ "memory-efficient-cross-attn",
223
+ "linear",
224
+ "none",
225
+ "memory-efficient-cross-attn-fusion",
226
+ ], f"attn_type {attn_type} unknown"
227
+ if (
228
+ version.parse(torch.__version__) < version.parse("2.0.0")
229
+ and attn_type != "none"
230
+ ):
231
+ assert XFORMERS_IS_AVAILABLE, (
232
+ f"We do not support vanilla attention in {torch.__version__} anymore, "
233
+ f"as it is too expensive. Please install xformers via e.g. 'pip install xformers==0.0.16'"
234
+ )
235
+ # attn_type = "vanilla-xformers"
236
+ logpy.info(f"making attention of type '{attn_type}' with {in_channels} in_channels")
237
+ if attn_type == "vanilla":
238
+ assert attn_kwargs is None
239
+ return AttnBlock(in_channels)
240
+ elif attn_type == "vanilla-xformers":
241
+ logpy.info(
242
+ f"building MemoryEfficientAttnBlock with {in_channels} in_channels..."
243
+ )
244
+ return MemoryEfficientAttnBlock(in_channels)
245
+ elif attn_type == "memory-efficient-cross-attn":
246
+ attn_kwargs["query_dim"] = in_channels
247
+ return MemoryEfficientCrossAttentionWrapper(**attn_kwargs)
248
+ elif attn_type == "memory-efficient-cross-attn-fusion":
249
+ attn_kwargs["query_dim"] = in_channels
250
+ return MemoryEfficientCrossAttentionWrapperFusion(**attn_kwargs)
251
+ elif attn_type == "none":
252
+ return nn.Identity(in_channels)
253
+ else:
254
+ return LinAttnBlock(in_channels)
255
+
256
+ class MemoryEfficientCrossAttentionWrapperFusion(MemoryEfficientCrossAttention):
257
+ # print('x.shape: ',x.shape, 'context.shape: ',context.shape) ##torch.Size([8, 128, 256, 256]) torch.Size([1, 128, 2, 256, 256])
258
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0, **kwargs):
259
+ super().__init__(query_dim, context_dim, heads, dim_head, dropout, **kwargs)
260
+ self.norm = Normalize(query_dim)
261
+ nn.init.zeros_(self.to_out[0].weight)
262
+ nn.init.zeros_(self.to_out[0].bias)
263
+
264
+ def forward(self, x, context=None, mask=None):
265
+ if self.training:
266
+ return checkpoint(self._forward, x, context, mask, use_reentrant=False)
267
+ else:
268
+ return self._forward(x, context, mask)
269
+
270
+ def _forward(
271
+ self,
272
+ x,
273
+ context=None,
274
+ mask=None,
275
+ ):
276
+ bt, c, h, w = x.shape
277
+ h_ = self.norm(x)
278
+ h_ = rearrange(h_, "b c h w -> b (h w) c")
279
+ q = self.to_q(h_)
280
+
281
+
282
+ b, c, l, h, w = context.shape
283
+ context = rearrange(context, "b c l h w -> (b l) (h w) c")
284
+ k = self.to_k(context)
285
+ v = self.to_v(context)
286
+ k = rearrange(k, "(b l) d c -> b l d c", l=l)
287
+ k = torch.cat([k[:, [0] * (bt//b)], k[:, [1]*(bt//b)]], dim=2)
288
+ k = rearrange(k, "b l d c -> (b l) d c")
289
+
290
+ v = rearrange(v, "(b l) d c -> b l d c", l=l)
291
+ v = torch.cat([v[:, [0] * (bt//b)], v[:, [1]*(bt//b)]], dim=2)
292
+ v = rearrange(v, "b l d c -> (b l) d c")
293
+
294
+
295
+ b, _, _ = q.shape ##actually bt
296
+ q, k, v = map(
297
+ lambda t: t.unsqueeze(3)
298
+ .reshape(b, t.shape[1], self.heads, self.dim_head)
299
+ .permute(0, 2, 1, 3)
300
+ .reshape(b * self.heads, t.shape[1], self.dim_head)
301
+ .contiguous(),
302
+ (q, k, v),
303
+ )
304
+
305
+ # actually compute the attention, what we cannot get enough of
306
+ if version.parse(xformers.__version__) >= version.parse("0.0.21"):
307
+ # NOTE: workaround for
308
+ # https://github.com/facebookresearch/xformers/issues/845
309
+ max_bs = 32768
310
+ N = q.shape[0]
311
+ n_batches = math.ceil(N / max_bs)
312
+ out = list()
313
+ for i_batch in range(n_batches):
314
+ batch = slice(i_batch * max_bs, (i_batch + 1) * max_bs)
315
+ out.append(
316
+ xformers.ops.memory_efficient_attention(
317
+ q[batch],
318
+ k[batch],
319
+ v[batch],
320
+ attn_bias=None,
321
+ op=self.attention_op,
322
+ )
323
+ )
324
+ out = torch.cat(out, 0)
325
+ else:
326
+ out = xformers.ops.memory_efficient_attention(
327
+ q, k, v, attn_bias=None, op=self.attention_op
328
+ )
329
+
330
+ # TODO: Use this directly in the attention operation, as a bias
331
+ if exists(mask):
332
+ raise NotImplementedError
333
+ out = (
334
+ out.unsqueeze(0)
335
+ .reshape(b, self.heads, out.shape[1], self.dim_head)
336
+ .permute(0, 2, 1, 3)
337
+ .reshape(b, out.shape[1], self.heads * self.dim_head)
338
+ )
339
+ out = self.to_out(out)
340
+ out = rearrange(out, "bt (h w) c -> bt c h w", h=h, w=w, c=c)
341
+ return x + out
342
+
343
+ class Combiner(nn.Module):
344
+ def __init__(self, ch) -> None:
345
+ super().__init__()
346
+ self.conv = nn.Conv2d(ch,ch,1,padding=0)
347
+
348
+ nn.init.zeros_(self.conv.weight)
349
+ nn.init.zeros_(self.conv.bias)
350
+
351
+ def forward(self, x, context):
352
+ if self.training:
353
+ return checkpoint(self._forward, x, context, use_reentrant=False)
354
+ else:
355
+ return self._forward(x, context)
356
+
357
+ def _forward(self, x, context):
358
+ ## x: b c h w, context: b c 2 h w
359
+ b, c, l, h, w = context.shape
360
+ bt, c, h, w = x.shape
361
+ context = rearrange(context, "b c l h w -> (b l) c h w")
362
+ context = self.conv(context)
363
+ context = rearrange(context, "(b l) c h w -> b c l h w", l=l)
364
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=bt//b)
365
+ x[:,:,0] = x[:,:,0] + context[:,:,0]
366
+ x[:,:,-1] = x[:,:,-1] + context[:,:,1]
367
+ x = rearrange(x, "b c t h w -> (b t) c h w")
368
+ return x
369
+
370
+
371
+ class Decoder(nn.Module):
372
+ def __init__(
373
+ self,
374
+ *,
375
+ ch,
376
+ out_ch,
377
+ ch_mult=(1, 2, 4, 8),
378
+ num_res_blocks,
379
+ attn_resolutions,
380
+ dropout=0.0,
381
+ resamp_with_conv=True,
382
+ in_channels,
383
+ resolution,
384
+ z_channels,
385
+ give_pre_end=False,
386
+ tanh_out=False,
387
+ use_linear_attn=False,
388
+ attn_type="vanilla-xformers",
389
+ attn_level=[2,3],
390
+ **ignorekwargs,
391
+ ):
392
+ super().__init__()
393
+ if use_linear_attn:
394
+ attn_type = "linear"
395
+ self.ch = ch
396
+ self.temb_ch = 0
397
+ self.num_resolutions = len(ch_mult)
398
+ self.num_res_blocks = num_res_blocks
399
+ self.resolution = resolution
400
+ self.in_channels = in_channels
401
+ self.give_pre_end = give_pre_end
402
+ self.tanh_out = tanh_out
403
+ self.attn_level = attn_level
404
+ # compute in_ch_mult, block_in and curr_res at lowest res
405
+ in_ch_mult = (1,) + tuple(ch_mult)
406
+ block_in = ch * ch_mult[self.num_resolutions - 1]
407
+ curr_res = resolution // 2 ** (self.num_resolutions - 1)
408
+ self.z_shape = (1, z_channels, curr_res, curr_res)
409
+ logpy.info(
410
+ "Working with z of shape {} = {} dimensions.".format(
411
+ self.z_shape, np.prod(self.z_shape)
412
+ )
413
+ )
414
+
415
+ make_attn_cls = self._make_attn()
416
+ make_resblock_cls = self._make_resblock()
417
+ make_conv_cls = self._make_conv()
418
+ # z to block_in
419
+ self.conv_in = torch.nn.Conv2d(
420
+ z_channels, block_in, kernel_size=3, stride=1, padding=1
421
+ )
422
+
423
+ # middle
424
+ self.mid = nn.Module()
425
+ self.mid.block_1 = make_resblock_cls(
426
+ in_channels=block_in,
427
+ out_channels=block_in,
428
+ temb_channels=self.temb_ch,
429
+ dropout=dropout,
430
+ )
431
+ self.mid.attn_1 = make_attn_cls(block_in, attn_type=attn_type)
432
+ self.mid.block_2 = make_resblock_cls(
433
+ in_channels=block_in,
434
+ out_channels=block_in,
435
+ temb_channels=self.temb_ch,
436
+ dropout=dropout,
437
+ )
438
+
439
+ # upsampling
440
+ self.up = nn.ModuleList()
441
+ self.attn_refinement = nn.ModuleList()
442
+ for i_level in reversed(range(self.num_resolutions)):
443
+ block = nn.ModuleList()
444
+ attn = nn.ModuleList()
445
+ block_out = ch * ch_mult[i_level]
446
+ for i_block in range(self.num_res_blocks + 1):
447
+ block.append(
448
+ make_resblock_cls(
449
+ in_channels=block_in,
450
+ out_channels=block_out,
451
+ temb_channels=self.temb_ch,
452
+ dropout=dropout,
453
+ )
454
+ )
455
+ block_in = block_out
456
+ if curr_res in attn_resolutions:
457
+ attn.append(make_attn_cls(block_in, attn_type=attn_type))
458
+ up = nn.Module()
459
+ up.block = block
460
+ up.attn = attn
461
+ if i_level != 0:
462
+ up.upsample = Upsample(block_in, resamp_with_conv)
463
+ curr_res = curr_res * 2
464
+ self.up.insert(0, up) # prepend to get consistent order
465
+
466
+ if i_level in self.attn_level:
467
+ self.attn_refinement.insert(0, make_attn_cls(block_in, attn_type='memory-efficient-cross-attn-fusion', attn_kwargs={}))
468
+ else:
469
+ self.attn_refinement.insert(0, Combiner(block_in))
470
+ # end
471
+ self.norm_out = Normalize(block_in)
472
+ self.attn_refinement.append(Combiner(block_in))
473
+ self.conv_out = make_conv_cls(
474
+ block_in, out_ch, kernel_size=3, stride=1, padding=1
475
+ )
476
+
477
+ def _make_attn(self) -> Callable:
478
+ return make_attn
479
+
480
+ def _make_resblock(self) -> Callable:
481
+ return ResnetBlock
482
+
483
+ def _make_conv(self) -> Callable:
484
+ return torch.nn.Conv2d
485
+
486
+ def get_last_layer(self, **kwargs):
487
+ return self.conv_out.weight
488
+
489
+ def forward(self, z, ref_context=None, **kwargs):
490
+ ## ref_context: b c 2 h w, 2 means starting and ending frame
491
+ # assert z.shape[1:] == self.z_shape[1:]
492
+ self.last_z_shape = z.shape
493
+ # timestep embedding
494
+ temb = None
495
+
496
+ # z to block_in
497
+ h = self.conv_in(z)
498
+
499
+ # middle
500
+ h = self.mid.block_1(h, temb, **kwargs)
501
+ h = self.mid.attn_1(h, **kwargs)
502
+ h = self.mid.block_2(h, temb, **kwargs)
503
+
504
+ # upsampling
505
+ for i_level in reversed(range(self.num_resolutions)):
506
+ for i_block in range(self.num_res_blocks + 1):
507
+ h = self.up[i_level].block[i_block](h, temb, **kwargs)
508
+ if len(self.up[i_level].attn) > 0:
509
+ h = self.up[i_level].attn[i_block](h, **kwargs)
510
+ if ref_context:
511
+ h = self.attn_refinement[i_level](x=h, context=ref_context[i_level])
512
+ if i_level != 0:
513
+ h = self.up[i_level].upsample(h)
514
+
515
+ # end
516
+ if self.give_pre_end:
517
+ return h
518
+
519
+ h = self.norm_out(h)
520
+ h = nonlinearity(h)
521
+ if ref_context:
522
+ # print(h.shape, ref_context[i_level].shape) #torch.Size([8, 128, 256, 256]) torch.Size([1, 128, 2, 256, 256])
523
+ h = self.attn_refinement[-1](x=h, context=ref_context[-1])
524
+ h = self.conv_out(h, **kwargs)
525
+ if self.tanh_out:
526
+ h = torch.tanh(h)
527
+ return h
528
+
529
+ #####
530
+
531
+
532
+ from abc import abstractmethod
533
+ from lvdm.models.utils_diffusion import timestep_embedding
534
+
535
+ from torch.utils.checkpoint import checkpoint
536
+ from lvdm.basics import (
537
+ zero_module,
538
+ conv_nd,
539
+ linear,
540
+ normalization,
541
+ )
542
+ from lvdm.modules.networks.openaimodel3d import Upsample, Downsample
543
+ class TimestepBlock(nn.Module):
544
+ """
545
+ Any module where forward() takes timestep embeddings as a second argument.
546
+ """
547
+
548
+ @abstractmethod
549
+ def forward(self, x: torch.Tensor, emb: torch.Tensor):
550
+ """
551
+ Apply the module to `x` given `emb` timestep embeddings.
552
+ """
553
+
554
+ class ResBlock(TimestepBlock):
555
+ """
556
+ A residual block that can optionally change the number of channels.
557
+ :param channels: the number of input channels.
558
+ :param emb_channels: the number of timestep embedding channels.
559
+ :param dropout: the rate of dropout.
560
+ :param out_channels: if specified, the number of out channels.
561
+ :param use_conv: if True and out_channels is specified, use a spatial
562
+ convolution instead of a smaller 1x1 convolution to change the
563
+ channels in the skip connection.
564
+ :param dims: determines if the signal is 1D, 2D, or 3D.
565
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
566
+ :param up: if True, use this block for upsampling.
567
+ :param down: if True, use this block for downsampling.
568
+ """
569
+
570
+ def __init__(
571
+ self,
572
+ channels: int,
573
+ emb_channels: int,
574
+ dropout: float,
575
+ out_channels: Optional[int] = None,
576
+ use_conv: bool = False,
577
+ use_scale_shift_norm: bool = False,
578
+ dims: int = 2,
579
+ use_checkpoint: bool = False,
580
+ up: bool = False,
581
+ down: bool = False,
582
+ kernel_size: int = 3,
583
+ exchange_temb_dims: bool = False,
584
+ skip_t_emb: bool = False,
585
+ ):
586
+ super().__init__()
587
+ self.channels = channels
588
+ self.emb_channels = emb_channels
589
+ self.dropout = dropout
590
+ self.out_channels = out_channels or channels
591
+ self.use_conv = use_conv
592
+ self.use_checkpoint = use_checkpoint
593
+ self.use_scale_shift_norm = use_scale_shift_norm
594
+ self.exchange_temb_dims = exchange_temb_dims
595
+
596
+ if isinstance(kernel_size, Iterable):
597
+ padding = [k // 2 for k in kernel_size]
598
+ else:
599
+ padding = kernel_size // 2
600
+
601
+ self.in_layers = nn.Sequential(
602
+ normalization(channels),
603
+ nn.SiLU(),
604
+ conv_nd(dims, channels, self.out_channels, kernel_size, padding=padding),
605
+ )
606
+
607
+ self.updown = up or down
608
+
609
+ if up:
610
+ self.h_upd = Upsample(channels, False, dims)
611
+ self.x_upd = Upsample(channels, False, dims)
612
+ elif down:
613
+ self.h_upd = Downsample(channels, False, dims)
614
+ self.x_upd = Downsample(channels, False, dims)
615
+ else:
616
+ self.h_upd = self.x_upd = nn.Identity()
617
+
618
+ self.skip_t_emb = skip_t_emb
619
+ self.emb_out_channels = (
620
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels
621
+ )
622
+ if self.skip_t_emb:
623
+ # print(f"Skipping timestep embedding in {self.__class__.__name__}")
624
+ assert not self.use_scale_shift_norm
625
+ self.emb_layers = None
626
+ self.exchange_temb_dims = False
627
+ else:
628
+ self.emb_layers = nn.Sequential(
629
+ nn.SiLU(),
630
+ linear(
631
+ emb_channels,
632
+ self.emb_out_channels,
633
+ ),
634
+ )
635
+
636
+ self.out_layers = nn.Sequential(
637
+ normalization(self.out_channels),
638
+ nn.SiLU(),
639
+ nn.Dropout(p=dropout),
640
+ zero_module(
641
+ conv_nd(
642
+ dims,
643
+ self.out_channels,
644
+ self.out_channels,
645
+ kernel_size,
646
+ padding=padding,
647
+ )
648
+ ),
649
+ )
650
+
651
+ if self.out_channels == channels:
652
+ self.skip_connection = nn.Identity()
653
+ elif use_conv:
654
+ self.skip_connection = conv_nd(
655
+ dims, channels, self.out_channels, kernel_size, padding=padding
656
+ )
657
+ else:
658
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
659
+
660
+ def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
661
+ """
662
+ Apply the block to a Tensor, conditioned on a timestep embedding.
663
+ :param x: an [N x C x ...] Tensor of features.
664
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
665
+ :return: an [N x C x ...] Tensor of outputs.
666
+ """
667
+ if self.use_checkpoint:
668
+ return checkpoint(self._forward, x, emb, use_reentrant=False)
669
+ else:
670
+ return self._forward(x, emb)
671
+
672
+ def _forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
673
+ if self.updown:
674
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
675
+ h = in_rest(x)
676
+ h = self.h_upd(h)
677
+ x = self.x_upd(x)
678
+ h = in_conv(h)
679
+ else:
680
+ h = self.in_layers(x)
681
+
682
+ if self.skip_t_emb:
683
+ emb_out = torch.zeros_like(h)
684
+ else:
685
+ emb_out = self.emb_layers(emb).type(h.dtype)
686
+ while len(emb_out.shape) < len(h.shape):
687
+ emb_out = emb_out[..., None]
688
+ if self.use_scale_shift_norm:
689
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
690
+ scale, shift = torch.chunk(emb_out, 2, dim=1)
691
+ h = out_norm(h) * (1 + scale) + shift
692
+ h = out_rest(h)
693
+ else:
694
+ if self.exchange_temb_dims:
695
+ emb_out = rearrange(emb_out, "b t c ... -> b c t ...")
696
+ h = h + emb_out
697
+ h = self.out_layers(h)
698
+ return self.skip_connection(x) + h
699
+ #####
700
+
701
+ #####
702
+ from lvdm.modules.attention_svd import *
703
+ class VideoTransformerBlock(nn.Module):
704
+ ATTENTION_MODES = {
705
+ "softmax": CrossAttention,
706
+ "softmax-xformers": MemoryEfficientCrossAttention,
707
+ }
708
+
709
+ def __init__(
710
+ self,
711
+ dim,
712
+ n_heads,
713
+ d_head,
714
+ dropout=0.0,
715
+ context_dim=None,
716
+ gated_ff=True,
717
+ checkpoint=True,
718
+ timesteps=None,
719
+ ff_in=False,
720
+ inner_dim=None,
721
+ attn_mode="softmax",
722
+ disable_self_attn=False,
723
+ disable_temporal_crossattention=False,
724
+ switch_temporal_ca_to_sa=False,
725
+ ):
726
+ super().__init__()
727
+
728
+ attn_cls = self.ATTENTION_MODES[attn_mode]
729
+
730
+ self.ff_in = ff_in or inner_dim is not None
731
+ if inner_dim is None:
732
+ inner_dim = dim
733
+
734
+ assert int(n_heads * d_head) == inner_dim
735
+
736
+ self.is_res = inner_dim == dim
737
+
738
+ if self.ff_in:
739
+ self.norm_in = nn.LayerNorm(dim)
740
+ self.ff_in = FeedForward(
741
+ dim, dim_out=inner_dim, dropout=dropout, glu=gated_ff
742
+ )
743
+
744
+ self.timesteps = timesteps
745
+ self.disable_self_attn = disable_self_attn
746
+ if self.disable_self_attn:
747
+ self.attn1 = attn_cls(
748
+ query_dim=inner_dim,
749
+ heads=n_heads,
750
+ dim_head=d_head,
751
+ context_dim=context_dim,
752
+ dropout=dropout,
753
+ ) # is a cross-attention
754
+ else:
755
+ self.attn1 = attn_cls(
756
+ query_dim=inner_dim, heads=n_heads, dim_head=d_head, dropout=dropout
757
+ ) # is a self-attention
758
+
759
+ self.ff = FeedForward(inner_dim, dim_out=dim, dropout=dropout, glu=gated_ff)
760
+
761
+ if disable_temporal_crossattention:
762
+ if switch_temporal_ca_to_sa:
763
+ raise ValueError
764
+ else:
765
+ self.attn2 = None
766
+ else:
767
+ self.norm2 = nn.LayerNorm(inner_dim)
768
+ if switch_temporal_ca_to_sa:
769
+ self.attn2 = attn_cls(
770
+ query_dim=inner_dim, heads=n_heads, dim_head=d_head, dropout=dropout
771
+ ) # is a self-attention
772
+ else:
773
+ self.attn2 = attn_cls(
774
+ query_dim=inner_dim,
775
+ context_dim=context_dim,
776
+ heads=n_heads,
777
+ dim_head=d_head,
778
+ dropout=dropout,
779
+ ) # is self-attn if context is none
780
+
781
+ self.norm1 = nn.LayerNorm(inner_dim)
782
+ self.norm3 = nn.LayerNorm(inner_dim)
783
+ self.switch_temporal_ca_to_sa = switch_temporal_ca_to_sa
784
+
785
+ self.checkpoint = checkpoint
786
+ if self.checkpoint:
787
+ print(f"====>{self.__class__.__name__} is using checkpointing")
788
+ else:
789
+ print(f"====>{self.__class__.__name__} is NOT using checkpointing")
790
+
791
+ def forward(
792
+ self, x: torch.Tensor, context: torch.Tensor = None, timesteps: int = None
793
+ ) -> torch.Tensor:
794
+ if self.checkpoint:
795
+ return checkpoint(self._forward, x, context, timesteps, use_reentrant=False)
796
+ else:
797
+ return self._forward(x, context, timesteps=timesteps)
798
+
799
+ def _forward(self, x, context=None, timesteps=None):
800
+ assert self.timesteps or timesteps
801
+ assert not (self.timesteps and timesteps) or self.timesteps == timesteps
802
+ timesteps = self.timesteps or timesteps
803
+ B, S, C = x.shape
804
+ x = rearrange(x, "(b t) s c -> (b s) t c", t=timesteps)
805
+
806
+ if self.ff_in:
807
+ x_skip = x
808
+ x = self.ff_in(self.norm_in(x))
809
+ if self.is_res:
810
+ x += x_skip
811
+
812
+ if self.disable_self_attn:
813
+ x = self.attn1(self.norm1(x), context=context) + x
814
+ else:
815
+ x = self.attn1(self.norm1(x)) + x
816
+
817
+ if self.attn2 is not None:
818
+ if self.switch_temporal_ca_to_sa:
819
+ x = self.attn2(self.norm2(x)) + x
820
+ else:
821
+ x = self.attn2(self.norm2(x), context=context) + x
822
+ x_skip = x
823
+ x = self.ff(self.norm3(x))
824
+ if self.is_res:
825
+ x += x_skip
826
+
827
+ x = rearrange(
828
+ x, "(b s) t c -> (b t) s c", s=S, b=B // timesteps, c=C, t=timesteps
829
+ )
830
+ return x
831
+
832
+ def get_last_layer(self):
833
+ return self.ff.net[-1].weight
834
+
835
+ #####
836
+
837
+ #####
838
+ import functools
839
+ def partialclass(cls, *args, **kwargs):
840
+ class NewCls(cls):
841
+ __init__ = functools.partialmethod(cls.__init__, *args, **kwargs)
842
+
843
+ return NewCls
844
+ ######
845
+
846
+ class VideoResBlock(ResnetBlock):
847
+ def __init__(
848
+ self,
849
+ out_channels,
850
+ *args,
851
+ dropout=0.0,
852
+ video_kernel_size=3,
853
+ alpha=0.0,
854
+ merge_strategy="learned",
855
+ **kwargs,
856
+ ):
857
+ super().__init__(out_channels=out_channels, dropout=dropout, *args, **kwargs)
858
+ if video_kernel_size is None:
859
+ video_kernel_size = [3, 1, 1]
860
+ self.time_stack = ResBlock(
861
+ channels=out_channels,
862
+ emb_channels=0,
863
+ dropout=dropout,
864
+ dims=3,
865
+ use_scale_shift_norm=False,
866
+ use_conv=False,
867
+ up=False,
868
+ down=False,
869
+ kernel_size=video_kernel_size,
870
+ use_checkpoint=True,
871
+ skip_t_emb=True,
872
+ )
873
+
874
+ self.merge_strategy = merge_strategy
875
+ if self.merge_strategy == "fixed":
876
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
877
+ elif self.merge_strategy == "learned":
878
+ self.register_parameter(
879
+ "mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
880
+ )
881
+ else:
882
+ raise ValueError(f"unknown merge strategy {self.merge_strategy}")
883
+
884
+ def get_alpha(self, bs):
885
+ if self.merge_strategy == "fixed":
886
+ return self.mix_factor
887
+ elif self.merge_strategy == "learned":
888
+ return torch.sigmoid(self.mix_factor)
889
+ else:
890
+ raise NotImplementedError()
891
+
892
+ def forward(self, x, temb, skip_video=False, timesteps=None):
893
+ if timesteps is None:
894
+ timesteps = self.timesteps
895
+
896
+ b, c, h, w = x.shape
897
+
898
+ x = super().forward(x, temb)
899
+
900
+ if not skip_video:
901
+ x_mix = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
902
+
903
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
904
+
905
+ x = self.time_stack(x, temb)
906
+
907
+ alpha = self.get_alpha(bs=b // timesteps)
908
+ x = alpha * x + (1.0 - alpha) * x_mix
909
+
910
+ x = rearrange(x, "b c t h w -> (b t) c h w")
911
+ return x
912
+
913
+
914
+ class AE3DConv(torch.nn.Conv2d):
915
+ def __init__(self, in_channels, out_channels, video_kernel_size=3, *args, **kwargs):
916
+ super().__init__(in_channels, out_channels, *args, **kwargs)
917
+ if isinstance(video_kernel_size, Iterable):
918
+ padding = [int(k // 2) for k in video_kernel_size]
919
+ else:
920
+ padding = int(video_kernel_size // 2)
921
+
922
+ self.time_mix_conv = torch.nn.Conv3d(
923
+ in_channels=out_channels,
924
+ out_channels=out_channels,
925
+ kernel_size=video_kernel_size,
926
+ padding=padding,
927
+ )
928
+
929
+ def forward(self, input, timesteps, skip_video=False):
930
+ x = super().forward(input)
931
+ if skip_video:
932
+ return x
933
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
934
+ x = self.time_mix_conv(x)
935
+ return rearrange(x, "b c t h w -> (b t) c h w")
936
+
937
+
938
+ class VideoBlock(AttnBlock):
939
+ def __init__(
940
+ self, in_channels: int, alpha: float = 0, merge_strategy: str = "learned"
941
+ ):
942
+ super().__init__(in_channels)
943
+ # no context, single headed, as in base class
944
+ self.time_mix_block = VideoTransformerBlock(
945
+ dim=in_channels,
946
+ n_heads=1,
947
+ d_head=in_channels,
948
+ checkpoint=True,
949
+ ff_in=True,
950
+ attn_mode="softmax",
951
+ )
952
+
953
+ time_embed_dim = self.in_channels * 4
954
+ self.video_time_embed = torch.nn.Sequential(
955
+ torch.nn.Linear(self.in_channels, time_embed_dim),
956
+ torch.nn.SiLU(),
957
+ torch.nn.Linear(time_embed_dim, self.in_channels),
958
+ )
959
+
960
+ self.merge_strategy = merge_strategy
961
+ if self.merge_strategy == "fixed":
962
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
963
+ elif self.merge_strategy == "learned":
964
+ self.register_parameter(
965
+ "mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
966
+ )
967
+ else:
968
+ raise ValueError(f"unknown merge strategy {self.merge_strategy}")
969
+
970
+ def forward(self, x, timesteps, skip_video=False):
971
+ if skip_video:
972
+ return super().forward(x)
973
+
974
+ x_in = x
975
+ x = self.attention(x)
976
+ h, w = x.shape[2:]
977
+ x = rearrange(x, "b c h w -> b (h w) c")
978
+
979
+ x_mix = x
980
+ num_frames = torch.arange(timesteps, device=x.device)
981
+ num_frames = repeat(num_frames, "t -> b t", b=x.shape[0] // timesteps)
982
+ num_frames = rearrange(num_frames, "b t -> (b t)")
983
+ t_emb = timestep_embedding(num_frames, self.in_channels, repeat_only=False)
984
+ emb = self.video_time_embed(t_emb) # b, n_channels
985
+ emb = emb[:, None, :]
986
+ x_mix = x_mix + emb
987
+
988
+ alpha = self.get_alpha()
989
+ x_mix = self.time_mix_block(x_mix, timesteps=timesteps)
990
+ x = alpha * x + (1.0 - alpha) * x_mix # alpha merge
991
+
992
+ x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w)
993
+ x = self.proj_out(x)
994
+
995
+ return x_in + x
996
+
997
+ def get_alpha(
998
+ self,
999
+ ):
1000
+ if self.merge_strategy == "fixed":
1001
+ return self.mix_factor
1002
+ elif self.merge_strategy == "learned":
1003
+ return torch.sigmoid(self.mix_factor)
1004
+ else:
1005
+ raise NotImplementedError(f"unknown merge strategy {self.merge_strategy}")
1006
+
1007
+
1008
+ class MemoryEfficientVideoBlock(MemoryEfficientAttnBlock):
1009
+ def __init__(
1010
+ self, in_channels: int, alpha: float = 0, merge_strategy: str = "learned"
1011
+ ):
1012
+ super().__init__(in_channels)
1013
+ # no context, single headed, as in base class
1014
+ self.time_mix_block = VideoTransformerBlock(
1015
+ dim=in_channels,
1016
+ n_heads=1,
1017
+ d_head=in_channels,
1018
+ checkpoint=True,
1019
+ ff_in=True,
1020
+ attn_mode="softmax-xformers",
1021
+ )
1022
+
1023
+ time_embed_dim = self.in_channels * 4
1024
+ self.video_time_embed = torch.nn.Sequential(
1025
+ torch.nn.Linear(self.in_channels, time_embed_dim),
1026
+ torch.nn.SiLU(),
1027
+ torch.nn.Linear(time_embed_dim, self.in_channels),
1028
+ )
1029
+
1030
+ self.merge_strategy = merge_strategy
1031
+ if self.merge_strategy == "fixed":
1032
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
1033
+ elif self.merge_strategy == "learned":
1034
+ self.register_parameter(
1035
+ "mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
1036
+ )
1037
+ else:
1038
+ raise ValueError(f"unknown merge strategy {self.merge_strategy}")
1039
+
1040
+ def forward(self, x, timesteps, skip_time_block=False):
1041
+ if skip_time_block:
1042
+ return super().forward(x)
1043
+
1044
+ x_in = x
1045
+ x = self.attention(x)
1046
+ h, w = x.shape[2:]
1047
+ x = rearrange(x, "b c h w -> b (h w) c")
1048
+
1049
+ x_mix = x
1050
+ num_frames = torch.arange(timesteps, device=x.device)
1051
+ num_frames = repeat(num_frames, "t -> b t", b=x.shape[0] // timesteps)
1052
+ num_frames = rearrange(num_frames, "b t -> (b t)")
1053
+ t_emb = timestep_embedding(num_frames, self.in_channels, repeat_only=False)
1054
+ emb = self.video_time_embed(t_emb) # b, n_channels
1055
+ emb = emb[:, None, :]
1056
+ x_mix = x_mix + emb
1057
+
1058
+ alpha = self.get_alpha()
1059
+ x_mix = self.time_mix_block(x_mix, timesteps=timesteps)
1060
+ x = alpha * x + (1.0 - alpha) * x_mix # alpha merge
1061
+
1062
+ x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w)
1063
+ x = self.proj_out(x)
1064
+
1065
+ return x_in + x
1066
+
1067
+ def get_alpha(
1068
+ self,
1069
+ ):
1070
+ if self.merge_strategy == "fixed":
1071
+ return self.mix_factor
1072
+ elif self.merge_strategy == "learned":
1073
+ return torch.sigmoid(self.mix_factor)
1074
+ else:
1075
+ raise NotImplementedError(f"unknown merge strategy {self.merge_strategy}")
1076
+
1077
+
1078
+ def make_time_attn(
1079
+ in_channels,
1080
+ attn_type="vanilla",
1081
+ attn_kwargs=None,
1082
+ alpha: float = 0,
1083
+ merge_strategy: str = "learned",
1084
+ ):
1085
+ assert attn_type in [
1086
+ "vanilla",
1087
+ "vanilla-xformers",
1088
+ ], f"attn_type {attn_type} not supported for spatio-temporal attention"
1089
+ print(
1090
+ f"making spatial and temporal attention of type '{attn_type}' with {in_channels} in_channels"
1091
+ )
1092
+ if not XFORMERS_IS_AVAILABLE and attn_type == "vanilla-xformers":
1093
+ print(
1094
+ f"Attention mode '{attn_type}' is not available. Falling back to vanilla attention. "
1095
+ f"This is not a problem in Pytorch >= 2.0. FYI, you are running with PyTorch version {torch.__version__}"
1096
+ )
1097
+ attn_type = "vanilla"
1098
+
1099
+ if attn_type == "vanilla":
1100
+ assert attn_kwargs is None
1101
+ return partialclass(
1102
+ VideoBlock, in_channels, alpha=alpha, merge_strategy=merge_strategy
1103
+ )
1104
+ elif attn_type == "vanilla-xformers":
1105
+ print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...")
1106
+ return partialclass(
1107
+ MemoryEfficientVideoBlock,
1108
+ in_channels,
1109
+ alpha=alpha,
1110
+ merge_strategy=merge_strategy,
1111
+ )
1112
+ else:
1113
+ return NotImplementedError()
1114
+
1115
+
1116
+ class Conv2DWrapper(torch.nn.Conv2d):
1117
+ def forward(self, input: torch.Tensor, **kwargs) -> torch.Tensor:
1118
+ return super().forward(input)
1119
+
1120
+
1121
+ class VideoDecoder(Decoder):
1122
+ available_time_modes = ["all", "conv-only", "attn-only"]
1123
+
1124
+ def __init__(
1125
+ self,
1126
+ *args,
1127
+ video_kernel_size: Union[int, list] = [3,1,1],
1128
+ alpha: float = 0.0,
1129
+ merge_strategy: str = "learned",
1130
+ time_mode: str = "conv-only",
1131
+ **kwargs,
1132
+ ):
1133
+ self.video_kernel_size = video_kernel_size
1134
+ self.alpha = alpha
1135
+ self.merge_strategy = merge_strategy
1136
+ self.time_mode = time_mode
1137
+ assert (
1138
+ self.time_mode in self.available_time_modes
1139
+ ), f"time_mode parameter has to be in {self.available_time_modes}"
1140
+ super().__init__(*args, **kwargs)
1141
+
1142
+ def get_last_layer(self, skip_time_mix=False, **kwargs):
1143
+ if self.time_mode == "attn-only":
1144
+ raise NotImplementedError("TODO")
1145
+ else:
1146
+ return (
1147
+ self.conv_out.time_mix_conv.weight
1148
+ if not skip_time_mix
1149
+ else self.conv_out.weight
1150
+ )
1151
+
1152
+ def _make_attn(self) -> Callable:
1153
+ if self.time_mode not in ["conv-only", "only-last-conv"]:
1154
+ return partialclass(
1155
+ make_time_attn,
1156
+ alpha=self.alpha,
1157
+ merge_strategy=self.merge_strategy,
1158
+ )
1159
+ else:
1160
+ return super()._make_attn()
1161
+
1162
+ def _make_conv(self) -> Callable:
1163
+ if self.time_mode != "attn-only":
1164
+ return partialclass(AE3DConv, video_kernel_size=self.video_kernel_size)
1165
+ else:
1166
+ return Conv2DWrapper
1167
+
1168
+ def _make_resblock(self) -> Callable:
1169
+ if self.time_mode not in ["attn-only", "only-last-conv"]:
1170
+ return partialclass(
1171
+ VideoResBlock,
1172
+ video_kernel_size=self.video_kernel_size,
1173
+ alpha=self.alpha,
1174
+ merge_strategy=self.merge_strategy,
1175
+ )
1176
+ else:
1177
+ return super()._make_resblock()