├── LICENSE
├── README.md
├── convlstm.py
├── dataloader.py
├── model.py
├── requirements.txt
├── test.py
├── train.py
└── utils.py
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2021-present, Sangmin Lee
2 |
3 | Attribution-NonCommercial 4.0 International
4 |
5 | =======================================================================
6 |
7 | Creative Commons Corporation ("Creative Commons") is not a law firm and
8 | does not provide legal services or legal advice. Distribution of
9 | Creative Commons public licenses does not create a lawyer-client or
10 | other relationship. Creative Commons makes its licenses and related
11 | information available on an "as-is" basis. Creative Commons gives no
12 | warranties regarding its licenses, any material licensed under their
13 | terms and conditions, or any related information. Creative Commons
14 | disclaims all liability for damages resulting from their use to the
15 | fullest extent possible.
16 |
17 | Using Creative Commons Public Licenses
18 |
19 | Creative Commons public licenses provide a standard set of terms and
20 | conditions that creators and other rights holders may use to share
21 | original works of authorship and other material subject to copyright
22 | and certain other rights specified in the public license below. The
23 | following considerations are for informational purposes only, are not
24 | exhaustive, and do not form part of our licenses.
25 |
26 | Considerations for licensors: Our public licenses are
27 | intended for use by those authorized to give the public
28 | permission to use material in ways otherwise restricted by
29 | copyright and certain other rights. Our licenses are
30 | irrevocable. Licensors should read and understand the terms
31 | and conditions of the license they choose before applying it.
32 | Licensors should also secure all rights necessary before
33 | applying our licenses so that the public can reuse the
34 | material as expected. Licensors should clearly mark any
35 | material not subject to the license. This includes other CC-
36 | licensed material, or material used under an exception or
37 | limitation to copyright. More considerations for licensors:
38 | wiki.creativecommons.org/Considerations_for_licensors
39 |
40 | Considerations for the public: By using one of our public
41 | licenses, a licensor grants the public permission to use the
42 | licensed material under specified terms and conditions. If
43 | the licensor's permission is not necessary for any reason--for
44 | example, because of any applicable exception or limitation to
45 | copyright--then that use is not regulated by the license. Our
46 | licenses grant only permissions under copyright and certain
47 | other rights that a licensor has authority to grant. Use of
48 | the licensed material may still be restricted for other
49 | reasons, including because others have copyright or other
50 | rights in the material. A licensor may make special requests,
51 | such as asking that all changes be marked or described.
52 | Although not required by our licenses, you are encouraged to
53 | respect those requests where reasonable. More considerations
54 | for the public:
55 | wiki.creativecommons.org/Considerations_for_licensees
56 |
57 | =======================================================================
58 |
59 | Creative Commons Attribution-NonCommercial 4.0 International Public
60 | License
61 |
62 | By exercising the Licensed Rights (defined below), You accept and agree
63 | to be bound by the terms and conditions of this Creative Commons
64 | Attribution-NonCommercial 4.0 International Public License ("Public
65 | License"). To the extent this Public License may be interpreted as a
66 | contract, You are granted the Licensed Rights in consideration of Your
67 | acceptance of these terms and conditions, and the Licensor grants You
68 | such rights in consideration of benefits the Licensor receives from
69 | making the Licensed Material available under these terms and
70 | conditions.
71 |
72 |
73 | Section 1 -- Definitions.
74 |
75 | a. Adapted Material means material subject to Copyright and Similar
76 | Rights that is derived from or based upon the Licensed Material
77 | and in which the Licensed Material is translated, altered,
78 | arranged, transformed, or otherwise modified in a manner requiring
79 | permission under the Copyright and Similar Rights held by the
80 | Licensor. For purposes of this Public License, where the Licensed
81 | Material is a musical work, performance, or sound recording,
82 | Adapted Material is always produced where the Licensed Material is
83 | synched in timed relation with a moving image.
84 |
85 | b. Adapter's License means the license You apply to Your Copyright
86 | and Similar Rights in Your contributions to Adapted Material in
87 | accordance with the terms and conditions of this Public License.
88 |
89 | c. Copyright and Similar Rights means copyright and/or similar rights
90 | closely related to copyright including, without limitation,
91 | performance, broadcast, sound recording, and Sui Generis Database
92 | Rights, without regard to how the rights are labeled or
93 | categorized. For purposes of this Public License, the rights
94 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
95 | Rights.
96 | d. Effective Technological Measures means those measures that, in the
97 | absence of proper authority, may not be circumvented under laws
98 | fulfilling obligations under Article 11 of the WIPO Copyright
99 | Treaty adopted on December 20, 1996, and/or similar international
100 | agreements.
101 |
102 | e. Exceptions and Limitations means fair use, fair dealing, and/or
103 | any other exception or limitation to Copyright and Similar Rights
104 | that applies to Your use of the Licensed Material.
105 |
106 | f. Licensed Material means the artistic or literary work, database,
107 | or other material to which the Licensor applied this Public
108 | License.
109 |
110 | g. Licensed Rights means the rights granted to You subject to the
111 | terms and conditions of this Public License, which are limited to
112 | all Copyright and Similar Rights that apply to Your use of the
113 | Licensed Material and that the Licensor has authority to license.
114 |
115 | h. Licensor means the individual(s) or entity(ies) granting rights
116 | under this Public License.
117 |
118 | i. NonCommercial means not primarily intended for or directed towards
119 | commercial advantage or monetary compensation. For purposes of
120 | this Public License, the exchange of the Licensed Material for
121 | other material subject to Copyright and Similar Rights by digital
122 | file-sharing or similar means is NonCommercial provided there is
123 | no payment of monetary compensation in connection with the
124 | exchange.
125 |
126 | j. Share means to provide material to the public by any means or
127 | process that requires permission under the Licensed Rights, such
128 | as reproduction, public display, public performance, distribution,
129 | dissemination, communication, or importation, and to make material
130 | available to the public including in ways that members of the
131 | public may access the material from a place and at a time
132 | individually chosen by them.
133 |
134 | k. Sui Generis Database Rights means rights other than copyright
135 | resulting from Directive 96/9/EC of the European Parliament and of
136 | the Council of 11 March 1996 on the legal protection of databases,
137 | as amended and/or succeeded, as well as other essentially
138 | equivalent rights anywhere in the world.
139 |
140 | l. You means the individual or entity exercising the Licensed Rights
141 | under this Public License. Your has a corresponding meaning.
142 |
143 |
144 | Section 2 -- Scope.
145 |
146 | a. License grant.
147 |
148 | 1. Subject to the terms and conditions of this Public License,
149 | the Licensor hereby grants You a worldwide, royalty-free,
150 | non-sublicensable, non-exclusive, irrevocable license to
151 | exercise the Licensed Rights in the Licensed Material to:
152 |
153 | a. reproduce and Share the Licensed Material, in whole or
154 | in part, for NonCommercial purposes only; and
155 |
156 | b. produce, reproduce, and Share Adapted Material for
157 | NonCommercial purposes only.
158 |
159 | 2. Exceptions and Limitations. For the avoidance of doubt, where
160 | Exceptions and Limitations apply to Your use, this Public
161 | License does not apply, and You do not need to comply with
162 | its terms and conditions.
163 |
164 | 3. Term. The term of this Public License is specified in Section
165 | 6(a).
166 |
167 | 4. Media and formats; technical modifications allowed. The
168 | Licensor authorizes You to exercise the Licensed Rights in
169 | all media and formats whether now known or hereafter created,
170 | and to make technical modifications necessary to do so. The
171 | Licensor waives and/or agrees not to assert any right or
172 | authority to forbid You from making technical modifications
173 | necessary to exercise the Licensed Rights, including
174 | technical modifications necessary to circumvent Effective
175 | Technological Measures. For purposes of this Public License,
176 | simply making modifications authorized by this Section 2(a)
177 | (4) never produces Adapted Material.
178 |
179 | 5. Downstream recipients.
180 |
181 | a. Offer from the Licensor -- Licensed Material. Every
182 | recipient of the Licensed Material automatically
183 | receives an offer from the Licensor to exercise the
184 | Licensed Rights under the terms and conditions of this
185 | Public License.
186 |
187 | b. No downstream restrictions. You may not offer or impose
188 | any additional or different terms or conditions on, or
189 | apply any Effective Technological Measures to, the
190 | Licensed Material if doing so restricts exercise of the
191 | Licensed Rights by any recipient of the Licensed
192 | Material.
193 |
194 | 6. No endorsement. Nothing in this Public License constitutes or
195 | may be construed as permission to assert or imply that You
196 | are, or that Your use of the Licensed Material is, connected
197 | with, or sponsored, endorsed, or granted official status by,
198 | the Licensor or others designated to receive attribution as
199 | provided in Section 3(a)(1)(A)(i).
200 |
201 | b. Other rights.
202 |
203 | 1. Moral rights, such as the right of integrity, are not
204 | licensed under this Public License, nor are publicity,
205 | privacy, and/or other similar personality rights; however, to
206 | the extent possible, the Licensor waives and/or agrees not to
207 | assert any such rights held by the Licensor to the limited
208 | extent necessary to allow You to exercise the Licensed
209 | Rights, but not otherwise.
210 |
211 | 2. Patent and trademark rights are not licensed under this
212 | Public License.
213 |
214 | 3. To the extent possible, the Licensor waives any right to
215 | collect royalties from You for the exercise of the Licensed
216 | Rights, whether directly or through a collecting society
217 | under any voluntary or waivable statutory or compulsory
218 | licensing scheme. In all other cases the Licensor expressly
219 | reserves any right to collect such royalties, including when
220 | the Licensed Material is used other than for NonCommercial
221 | purposes.
222 |
223 |
224 | Section 3 -- License Conditions.
225 |
226 | Your exercise of the Licensed Rights is expressly made subject to the
227 | following conditions.
228 |
229 | a. Attribution.
230 |
231 | 1. If You Share the Licensed Material (including in modified
232 | form), You must:
233 |
234 | a. retain the following if it is supplied by the Licensor
235 | with the Licensed Material:
236 |
237 | i. identification of the creator(s) of the Licensed
238 | Material and any others designated to receive
239 | attribution, in any reasonable manner requested by
240 | the Licensor (including by pseudonym if
241 | designated);
242 |
243 | ii. a copyright notice;
244 |
245 | iii. a notice that refers to this Public License;
246 |
247 | iv. a notice that refers to the disclaimer of
248 | warranties;
249 |
250 | v. a URI or hyperlink to the Licensed Material to the
251 | extent reasonably practicable;
252 |
253 | b. indicate if You modified the Licensed Material and
254 | retain an indication of any previous modifications; and
255 |
256 | c. indicate the Licensed Material is licensed under this
257 | Public License, and include the text of, or the URI or
258 | hyperlink to, this Public License.
259 |
260 | 2. You may satisfy the conditions in Section 3(a)(1) in any
261 | reasonable manner based on the medium, means, and context in
262 | which You Share the Licensed Material. For example, it may be
263 | reasonable to satisfy the conditions by providing a URI or
264 | hyperlink to a resource that includes the required
265 | information.
266 |
267 | 3. If requested by the Licensor, You must remove any of the
268 | information required by Section 3(a)(1)(A) to the extent
269 | reasonably practicable.
270 |
271 | 4. If You Share Adapted Material You produce, the Adapter's
272 | License You apply must not prevent recipients of the Adapted
273 | Material from complying with this Public License.
274 |
275 |
276 | Section 4 -- Sui Generis Database Rights.
277 |
278 | Where the Licensed Rights include Sui Generis Database Rights that
279 | apply to Your use of the Licensed Material:
280 |
281 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
282 | to extract, reuse, reproduce, and Share all or a substantial
283 | portion of the contents of the database for NonCommercial purposes
284 | only;
285 |
286 | b. if You include all or a substantial portion of the database
287 | contents in a database in which You have Sui Generis Database
288 | Rights, then the database in which You have Sui Generis Database
289 | Rights (but not its individual contents) is Adapted Material; and
290 |
291 | c. You must comply with the conditions in Section 3(a) if You Share
292 | all or a substantial portion of the contents of the database.
293 |
294 | For the avoidance of doubt, this Section 4 supplements and does not
295 | replace Your obligations under this Public License where the Licensed
296 | Rights include other Copyright and Similar Rights.
297 |
298 |
299 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
300 |
301 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
302 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
303 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
304 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
305 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
306 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
307 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
308 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
309 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
310 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
311 |
312 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
313 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
314 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
315 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
316 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
317 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
318 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
319 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
320 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
321 |
322 | c. The disclaimer of warranties and limitation of liability provided
323 | above shall be interpreted in a manner that, to the extent
324 | possible, most closely approximates an absolute disclaimer and
325 | waiver of all liability.
326 |
327 |
328 | Section 6 -- Term and Termination.
329 |
330 | a. This Public License applies for the term of the Copyright and
331 | Similar Rights licensed here. However, if You fail to comply with
332 | this Public License, then Your rights under this Public License
333 | terminate automatically.
334 |
335 | b. Where Your right to use the Licensed Material has terminated under
336 | Section 6(a), it reinstates:
337 |
338 | 1. automatically as of the date the violation is cured, provided
339 | it is cured within 30 days of Your discovery of the
340 | violation; or
341 |
342 | 2. upon express reinstatement by the Licensor.
343 |
344 | For the avoidance of doubt, this Section 6(b) does not affect any
345 | right the Licensor may have to seek remedies for Your violations
346 | of this Public License.
347 |
348 | c. For the avoidance of doubt, the Licensor may also offer the
349 | Licensed Material under separate terms or conditions or stop
350 | distributing the Licensed Material at any time; however, doing so
351 | will not terminate this Public License.
352 |
353 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
354 | License.
355 |
356 |
357 | Section 7 -- Other Terms and Conditions.
358 |
359 | a. The Licensor shall not be bound by any additional or different
360 | terms or conditions communicated by You unless expressly agreed.
361 |
362 | b. Any arrangements, understandings, or agreements regarding the
363 | Licensed Material not stated herein are separate from and
364 | independent of the terms and conditions of this Public License.
365 |
366 |
367 | Section 8 -- Interpretation.
368 |
369 | a. For the avoidance of doubt, this Public License does not, and
370 | shall not be interpreted to, reduce, limit, restrict, or impose
371 | conditions on any use of the Licensed Material that could lawfully
372 | be made without permission under this Public License.
373 |
374 | b. To the extent possible, if any provision of this Public License is
375 | deemed unenforceable, it shall be automatically reformed to the
376 | minimum extent necessary to make it enforceable. If the provision
377 | cannot be reformed, it shall be severed from this Public License
378 | without affecting the enforceability of the remaining terms and
379 | conditions.
380 |
381 | c. No term or condition of this Public License will be waived and no
382 | failure to comply consented to unless expressly agreed to by the
383 | Licensor.
384 |
385 | d. Nothing in this Public License constitutes or may be interpreted
386 | as a limitation upon, or waiver of, any privileges and immunities
387 | that apply to the Licensor or You, including from the legal
388 | processes of any jurisdiction or authority.
389 |
390 | =======================================================================
391 |
392 | Creative Commons is not a party to its public
393 | licenses. Notwithstanding, Creative Commons may elect to apply one of
394 | its public licenses to material it publishes and in those instances
395 | will be considered the “Licensor.” The text of the Creative Commons
396 | public licenses is dedicated to the public domain under the CC0 Public
397 | Domain Dedication. Except for the limited purpose of indicating that
398 | material is shared under a Creative Commons public license or as
399 | otherwise permitted by the Creative Commons policies published at
400 | creativecommons.org/policies, Creative Commons does not authorize the
401 | use of the trademark "Creative Commons" or any other trademark or logo
402 | of Creative Commons without its prior written consent including,
403 | without limitation, in connection with any unauthorized modifications
404 | to any of its public licenses or any other arrangements,
405 | understandings, or agreements concerning use of licensed material. For
406 | the avoidance of doubt, this paragraph does not form part of the
407 | public licenses.
408 |
409 | Creative Commons may be contacted at creativecommons.org.
410 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Video Prediction Recalling Long-term Motion Context via Memory Alignment Learning
2 |
3 |
4 |

5 |
6 |
7 | >
8 | This repository contains the official PyTorch implementation of the following paper:
9 | > **Video Prediction Recalling Long-term Motion Context via Memory Alignment Learning (CVPR 2021 Oral)**
10 | > Sangmin Lee, Hak Gu Kim, Dae Hwi Choi, Hyung-Il Kim, and Yong Man Ro
11 | > Paper: https://arxiv.org/abs/2104.00924
12 | >
13 | > **Abstract** *Our work addresses long-term motion context issues for predicting future frames. To predict the future precisely, it is required to capture which long-term motion context (e.g., walking or running) the input motion (e.g., leg movement) belongs to. The bottlenecks arising when dealing with the long-term motion context are: (i) how to predict the long-term motion context naturally matching input sequences with limited dynamics, (ii) how to predict the long-term motion context with high-dimensionality (e.g., complex motion). To address the issues, we propose novel motion context-aware video prediction. To solve the bottleneck (i), we introduce a long-term motion context memory (LMC-Memory) with memory alignment learning. The proposed memory alignment learning enables to store long-term motion contexts into the memory and to match them with sequences including limited dynamics. As a result, the long-term context can be recalled from the limited input sequence. In addition, to resolve the bottleneck (ii), we propose memory query decomposition to store local motion context (i.e., low-dimensional dynamics) and recall the suitable local context for each local part of the input individually. It enables to boost the alignment effects of the memory. Experimental results show that the proposed method outperforms other sophisticated RNN-based methods, especially in long-term condition. Further, we validate the effectiveness of the proposed network designs by conducting ablation studies and memory feature analysis. The source code of this work is available.*
14 |
15 | ## Preparation
16 |
17 | ### Requirements
18 | - python 3
19 | - pytorch 1.6+
20 | - opencv-python
21 | - scikit-image
22 | - lpips
23 | - numpy
24 |
25 | ### Datasets
26 | This repository supports Moving-MNIST and KTH-Action datasets.
27 | - [Moving-MNIST](https://github.com/jthsieh/DDPAE-video-prediction/blob/master/data/moving_mnist.py)
28 | - [KTH-Action](https://www.csc.kth.se/cvap/actions/)
29 |
30 | After obtaining the datasets, preprocess the data as image files (refer to below).
31 | ```shell
32 | # Dataset preparation example:
33 | movingmnist
34 | ├── train
35 | │ ├── video_00000
36 | │ │ ├── frame_00000.jpg
37 | ...
38 | │ │ ├── frame_xxxxx.jpg
39 | ...
40 | │ ├── video_xxxxx
41 | ```
42 |
43 | ## Training the Model
44 | `train.py` saves the weights in `--checkpoint_save_dir` and shows the training logs.
45 |
46 | To train the model, run following command:
47 | ```shell
48 | # Training example for Moving-MNIST
49 | python train.py \
50 | --dataset 'movingmnist' \
51 | --train_data_dir 'enter_the_path' --valid_data_dir 'enter_the_path' \
52 | --checkpoint_save_dir './checkpoints' \
53 | --img_size 64 --img_channel 1 --memory_size 100 \
54 | --short_len 10 --long_len 30 --out_len 30 \
55 | --batch_size 128 --lr 0.0002 --iterations 300000
56 | ```
57 | ```shell
58 | # Training example for KTH-Action
59 | python train.py \
60 | --dataset 'kth' \
61 | --train_data_dir 'enter_the_path' --valid_data_dir 'enter_the_path' \
62 | --checkpoint_save_dir './checkpoints' \
63 | --img_size 128 --img_channel 1 --memory_size 100 \
64 | --short_len 10 --long_len 40 --out_len 40 \
65 | --batch_size 32 --lr 0.0002 --iterations 300000
66 | ```
67 | Descriptions of training parameters are as follows:
68 | - `--dataset`: training dataset (movingmnist or kth)
69 | - `--train_data_dir`: directory of training set `--valid_data_dir`: directory of validation set
70 | - `--checkpoint_save_dir`: directory for saving checkpoints
71 | - `--img_size`: height and width of frame `--img_channel`: channel of frame `--memory_size`: memory slot size
72 | - `--short_len`: number of short frames `--long_len`: number of long frames `--out_len`: number of output frames
73 | - `--batch_size`: mini-batch size `--lr`: learning rate `--iterations`: number of total iterations
74 | - Refer to `train.py` for the other training parameters
75 |
76 | ## Testing the Model
77 | `test.py` saves the predicted frames in `--test_result_dir` or evalute the performances.
78 |
79 | To test the model, run following command:
80 | ```shell
81 | # Testing example for Moving-MNIST
82 | python test.py \
83 | --dataset 'movingmnist' --make_frame True \
84 | --test_data_dir 'enter_the_path' --test_result_dir 'enter_the_path' \
85 | --checkpoint_load_file 'enter_the_path' \
86 | --img_size 64 --img_channel 1 --memory_size 100 \
87 | --short_len 10 --out_len 30 \
88 | --batch_size 8
89 | ```
90 | ```shell
91 | # Testing example for KTH-Action
92 | python test.py \
93 | --dataset 'kth' --make_frame True \
94 | --test_data_dir 'enter_the_path' --test_result_dir 'enter_the_path' \
95 | --checkpoint_load_file 'enter_the_path' \
96 | --img_size 128 --img_channel 1 --memory_size 100 \
97 | --short_len 10 --out_len 40 \
98 | --batch_size 8
99 | ```
100 | Descriptions of testing parameters are as follows:
101 | - `--dataset`: test dataset (movingmnist or kth) `--make_frame`: whether to generate predicted frames
102 | - `--test_data_dir`: directory of test set `--test_result_dir`: directory for saving predicted frames
103 | - `--checkpoint_load_file`: file path for loading checkpoint
104 | - `--img_size`: height and width of frame `--img_channel`: channel of frame `--memory_size`: memory slot size
105 | - `--short_len`: number of short frames `--out_len`: number of output frames
106 | - `--batch_size`: mini-batch size
107 | - Refer to `test.py` for the other testing parameters
108 |
109 | ## Pretrained Models
110 | You can download the pretrained models.
111 | - [Pretrained model for Moving-MNIST](https://www.dropbox.com/s/c2yl2f7znzmj8mf/trained_file_movingmnist.pt?dl=0)
112 | - [Pretrained model for KTH-Action](https://www.dropbox.com/s/nt015y70moqgy76/trained_file_kth.pt?dl=0)
113 |
114 | ## Citation
115 | If you find this work useful in your research, please cite the paper:
116 | ```
117 | @inproceedings{lee2021video,
118 | title={Video Prediction Recalling Long-term Motion Context via Memory Alignment Learning},
119 | author={Lee, Sangmin and Kim, Hak Gu and Choi, Dae Hwi and Kim, Hyung-Il and Ro, Yong Man},
120 | booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
121 | year={2021}
122 | }
123 | ```
124 |
--------------------------------------------------------------------------------
/convlstm.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 |
5 | class NPUnit(nn.Module):
6 | def __init__(self, in_channels, out_channels, kernel_size):
7 | super(NPUnit, self).__init__()
8 | same_padding = int((kernel_size[0]-1)/2)
9 | self.conv2d_x = nn.Conv2d(in_channels=in_channels, out_channels=4*out_channels,
10 | kernel_size=kernel_size, stride=1, padding=same_padding, bias=True)
11 | self.conv2d_h = nn.Conv2d(in_channels=out_channels, out_channels=4*out_channels,
12 | kernel_size=kernel_size, stride=1, padding=same_padding, bias=True)
13 |
14 | def forward(self, x, h, c):
15 | x_after_conv = self.conv2d_x(x)
16 | h_after_conv = self.conv2d_h(h)
17 | xi, xc, xf, xo = torch.chunk(x_after_conv, 4, dim=1)
18 | hi, hc, hf, ho = torch.chunk(h_after_conv, 4, dim=1)
19 |
20 | it = torch.sigmoid(xi+hi)
21 | ft = torch.sigmoid(xf+hf)
22 | new_c = (ft*c)+(it*torch.tanh(xc+hc))
23 | ot = torch.sigmoid(xo+ho)
24 | new_h = ot*torch.tanh(new_c)
25 |
26 | return new_h, new_c
27 |
--------------------------------------------------------------------------------
/dataloader.py:
--------------------------------------------------------------------------------
1 | from torch.utils.data import Dataset
2 |
3 | import cv2
4 | import os
5 | import numpy as np
6 |
7 |
8 | def make_dataset(dataset_dir):
9 | frame_path = []
10 | # Find and loop over all the clips in root `dir`.
11 | for index, folder in enumerate(sorted(os.listdir(dataset_dir))):
12 | clipsFolderPath = os.path.join(dataset_dir, folder)
13 | # Skip items which are not folders.
14 | if not (os.path.isdir(clipsFolderPath)):
15 | continue
16 | frame_path.append([])
17 | # Find and loop over all the frames inside the clip.
18 | for image in sorted(os.listdir(clipsFolderPath)):
19 | # Add path to list.
20 | frame_path[index].append(os.path.join(clipsFolderPath, image))
21 | return frame_path
22 |
23 | class MovingMNIST(Dataset):
24 | def __init__(self, dataset_dir, seq_len, train=True):
25 | self.frame_path = make_dataset(dataset_dir)
26 | self.seq_len = seq_len
27 | self.train = train
28 |
29 | self.clips = []
30 | for video_i in range(len(self.frame_path)):
31 | video_frame_num = len(self.frame_path[video_i])
32 | self.clips += [(video_i, t) for t in range(video_frame_num - seq_len + 1)] if train \
33 | else [(video_i, t * seq_len) for t in range(video_frame_num // seq_len)]
34 |
35 | def __getitem__(self, idx):
36 | (video_idx, data_start) = self.clips[idx]
37 | sample = []
38 | for frame_range_i in range(data_start, data_start+self.seq_len):
39 | frame = cv2.imread(self.frame_path[video_idx][frame_range_i], cv2.IMREAD_GRAYSCALE)
40 | frame = np.expand_dims(frame, axis=0)
41 | frame = frame.astype(np.float32)
42 | frame = frame/255.0
43 | sample.append(frame)
44 | return sample
45 |
46 | def __len__(self):
47 | return len(self.clips)
48 |
49 | class KTH(Dataset):
50 | def __init__(self, dataset_dir, seq_len, train=True):
51 | self.frame_path = make_dataset(dataset_dir)
52 | self.seq_len = seq_len
53 | self.train = train
54 |
55 | self.clips = []
56 | for video_i in range(len(self.frame_path)):
57 | video_frame_num = len(self.frame_path[video_i])
58 | self.clips += [(video_i, t) for t in range(video_frame_num - seq_len + 1)] if train \
59 | else [(video_i, t * seq_len) for t in range(video_frame_num // seq_len)]
60 |
61 | def __getitem__(self, idx):
62 | (video_idx, data_start) = self.clips[idx]
63 | sample = []
64 | for frame_range_i in range(data_start, data_start+self.seq_len):
65 | frame = cv2.imread(self.frame_path[video_idx][frame_range_i], cv2.IMREAD_GRAYSCALE)
66 | frame = np.expand_dims(frame, axis=0)
67 | frame = frame.astype(np.float32)
68 | frame = frame/255.0
69 | sample.append(frame)
70 | return sample
71 |
72 | def __len__(self):
73 | return len(self.clips)
74 |
75 |
--------------------------------------------------------------------------------
/model.py:
--------------------------------------------------------------------------------
1 | import convlstm
2 |
3 | import torch
4 | import torch.nn as nn
5 | from torch.nn import functional as F
6 |
7 | import copy
8 |
9 |
10 | class Predictor(nn.Module):
11 | def __init__(self, args):
12 | super(Predictor, self).__init__()
13 | self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
14 | self.encoder = nn.Sequential(
15 | nn.Conv2d(in_channels=1, out_channels=64, kernel_size=(3, 3), stride=2, padding=1),
16 | nn.ELU(),
17 | nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), stride=1, padding=1),
18 | nn.ELU(),
19 | nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3), stride=2, padding=1),
20 | nn.ELU(),
21 | nn.Conv2d(in_channels=128, out_channels=128, kernel_size=(3, 3), stride=1, padding=1),
22 | nn.ELU())
23 | self.decoder = nn.Sequential(
24 | nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=(3, 3), stride=1, padding=1, output_padding=0),
25 | nn.ELU(),
26 | nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=(3, 3), stride=2, padding=1, output_padding=1),
27 | nn.ELU(),
28 | nn.ConvTranspose2d(in_channels=64, out_channels=64, kernel_size=(3, 3), stride=1, padding=1, output_padding=0),
29 | nn.ELU(),
30 | nn.ConvTranspose2d(in_channels=64, out_channels=1, kernel_size=(3, 3), stride=2, padding=1, output_padding=1))
31 |
32 | if args.dataset == 'kth':
33 | self.decoder.add_module("last_activation", nn.Sigmoid())
34 |
35 | self.convlstm_num = 4
36 | self.convlstm_in_c = [128, 128, 128, 128]
37 | self.convlstm_out_c = [128, 128, 128, 128]
38 | self.convlstm_list = []
39 | for layer_i in range(self.convlstm_num):
40 | self.convlstm_list.append(convlstm.NPUnit(in_channels=self.convlstm_in_c[layer_i],
41 | out_channels=self.convlstm_out_c[layer_i],
42 | kernel_size=[3, 3]))
43 | self.convlstm_list = nn.ModuleList(self.convlstm_list)
44 |
45 | self.memory = Memory(args.memory_size)
46 |
47 | self.attention_size = 128
48 | self.attention_func = nn.Sequential(
49 | nn.AdaptiveAvgPool2d([1, 1]),
50 | nn.Flatten(),
51 | nn.Linear(256, 16),
52 | nn.ReLU(),
53 | nn.Linear(16, self.attention_size),
54 | nn.Sigmoid())
55 |
56 | def forward(self, short_x, long_x, out_len, phase):
57 | batch_size = short_x.size()[0]
58 | input_len= short_x.size()[1]
59 |
60 | # long-term motion context recall
61 | memory_x = long_x if phase == 1 else short_x
62 | memory_feature = self.memory(memory_x, phase)
63 |
64 | # motion context-aware video prediction
65 | h, c, out_pred = [], [], []
66 | for layer_i in range(self.convlstm_num):
67 | zero_state = torch.zeros(batch_size, self.convlstm_in_c[layer_i], memory_feature.size()[2], memory_feature.size()[3]).to(self.device)
68 | h.append(zero_state)
69 | c.append(zero_state)
70 | for seq_i in range(input_len+out_len-1):
71 | if seq_i < input_len:
72 | input_x = short_x[:, seq_i, :, :, :]
73 | input_x = self.encoder(input_x)
74 | else:
75 | input_x = self.encoder(out_pred[-1])
76 |
77 | for layer_i in range(self.convlstm_num):
78 | if layer_i == 0:
79 | h[layer_i], c[layer_i] = self.convlstm_list[layer_i](input_x, h[layer_i], c[layer_i])
80 | else:
81 | h[layer_i], c[layer_i] = self.convlstm_list[layer_i](h[layer_i-1], h[layer_i], c[layer_i])
82 |
83 | if seq_i >= input_len-1:
84 | attention = self.attention_func(torch.cat([c[-1], memory_feature], dim=1))
85 | attention = torch.reshape(attention, (-1, self.attention_size, 1, 1))
86 | memory_feature_att = memory_feature * attention
87 | out_pred.append(self.decoder(torch.cat([h[-1], memory_feature_att], dim=1)))
88 |
89 | out_pred = torch.stack(out_pred)
90 | out_pred = out_pred.transpose(dim0=0, dim1=1)
91 | out_pred = out_pred[:, -out_len:, :, :, :]
92 |
93 | return out_pred
94 |
95 |
96 | class Memory(nn.Module):
97 | def __init__(self, memory_size):
98 | super(Memory, self).__init__()
99 | self.motion_matching_encoder = nn.Sequential(
100 | nn.Conv3d(1, 64, kernel_size=(3, 3, 3), padding=(1, 1, 1)),
101 | nn.ReLU(),
102 | nn.MaxPool3d(kernel_size=(1, 2, 2), stride=(1, 2, 2)),
103 | nn.Conv3d(64, 128, kernel_size=(3, 3, 3), padding=(1, 1, 1)),
104 | nn.ReLU(),
105 | nn.MaxPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2)),
106 | nn.Conv3d(128, 256, kernel_size=(3, 3, 3), padding=(1, 1, 1)),
107 | nn.ReLU(),
108 | nn.Conv3d(256, 256, kernel_size=(3, 3, 3), padding=(1, 1, 1)),
109 | nn.ReLU(),
110 | nn.MaxPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2)),
111 | nn.Conv3d(256, 512, kernel_size=(3, 3, 3), padding=(1, 1, 1)),
112 | nn.ReLU(),
113 | nn.Conv3d(512, 512, kernel_size=(3, 3, 3), padding=(1, 1, 1)),
114 | nn.ReLU(),
115 | nn.MaxPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2)),
116 | nn.AdaptiveAvgPool3d([1, None, None]))
117 |
118 | self.motion_context_encoder = copy.deepcopy(self.motion_matching_encoder)
119 |
120 | self.embedder = nn.Sequential(
121 | nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=(3, 3), stride=2, padding=1, output_padding=1),
122 | nn.ReLU(),
123 | nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=(3, 3), stride=2, padding=1, output_padding=1),
124 | nn.ReLU())
125 |
126 | self.memory_shape = [memory_size, 512]
127 | self.memory_w = nn.init.normal_(torch.empty(self.memory_shape), mean=0.0, std=1.0)
128 | self.memory_w = nn.Parameter(self.memory_w, requires_grad=True)
129 |
130 | def forward(self, memory_x, phase):
131 | memory_x = memory_x[:, 1:, :, :, :] - memory_x[:, :-1, :, :, :] # make difference frames
132 |
133 | memory_x = memory_x.transpose(dim0=1, dim1=2) # make (N, C, T, H, W) for 3D Conv
134 | motion_encoder = self.motion_context_encoder if phase == 1 else self.motion_matching_encoder
135 | memory_query = torch.squeeze(motion_encoder(memory_x), dim=2) # make (N, C, H, W)
136 |
137 | query_c, query_h, query_w = memory_query.size()[1], memory_query.size()[2], memory_query.size()[3]
138 | memory_query = memory_query.permute(0, 2, 3, 1) # make (N, H, W, C)
139 | memory_query = torch.reshape(memory_query, (-1, query_c)) # make (N*H*W, C)
140 |
141 | # memory addressing
142 | query_norm = F.normalize(memory_query, dim=1)
143 | memory_norm = F.normalize(self.memory_w, dim=1)
144 | s = torch.mm(query_norm, memory_norm.transpose(dim0=0, dim1=1))
145 | addressing_vec = F.softmax(s, dim=1)
146 | memory_feature = torch.mm(addressing_vec, self.memory_w)
147 |
148 | memory_feature = torch.reshape(memory_feature, (-1, query_h, query_w, query_c)) # make (N, H, W, C)
149 | memory_feature = memory_feature.permute(0, 3, 1, 2) # make (N, C, H, W) for 2D DeConv
150 | memory_feature = self.embedder(memory_feature)
151 |
152 | return memory_feature
153 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | torch==1.6.0
2 | opencv-python
3 | scikit-image
4 | lpips
5 | numpy
6 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | from model import Predictor
2 | from dataloader import MovingMNIST, KTH
3 | from utils import *
4 |
5 | import torch
6 | import torch.nn as nn
7 | from torch.utils.data import DataLoader
8 |
9 | import lpips
10 | import argparse
11 | import numpy as np
12 | import os
13 | import cv2
14 |
15 |
16 | parser = argparse.ArgumentParser()
17 | parser.add_argument('--dataset', type=str, default='movingmnist',
18 | help='testing dataset (movingmnist or kth)')
19 | parser.add_argument('--workers', type=int, default=4,
20 | help='number of data loading workers')
21 | parser.add_argument('--make_frame', type=bool, default=True,
22 | help='whether to generate predicted frames')
23 | parser.add_argument('--evaluate', type=bool, default=False,
24 | help='whether to evaluate performance')
25 | parser.add_argument('--test_data_dir', type=str, default='enter_the_path',
26 | help='directory of test set')
27 | parser.add_argument('--test_result_dir', type=str, default='./test_results',
28 | help='directory for saving predicted frames')
29 | parser.add_argument('--checkpoint_load_file', type=str, default='enter_the_path',
30 | help='file path for loading checkpoint')
31 |
32 | parser.add_argument('--img_size', type=int, default=64,
33 | help='height and width of video frame')
34 | parser.add_argument('--img_channel', type=int, default=1,
35 | help='channel of video frame')
36 | parser.add_argument('--memory_size', type=int, default=100,
37 | help='memory slot size')
38 | parser.add_argument('--short_len', type=int, default=10,
39 | help='number of input short-term frames')
40 | parser.add_argument('--out_len', type=int, default=30,
41 | help='number of output predicted frames')
42 |
43 | parser.add_argument('--batch_size', type=int, default=8,
44 | help='mini-batch size')
45 | args = parser.parse_args()
46 |
47 | if __name__ == '__main__':
48 | if not os.path.isdir(args.test_result_dir):
49 | os.makedirs(args.test_result_dir)
50 |
51 | # define the model
52 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
53 | pred_model = Predictor(args).to(device)
54 | pred_model = nn.DataParallel(pred_model)
55 |
56 | # load checkpoint
57 | pred_model.load_state_dict(torch.load(args.checkpoint_load_file))
58 | print('Checkpoint is loaded from ' + args.checkpoint_load_file)
59 |
60 | # prepare dataloader for selected dataset
61 | if args.dataset == 'movingmnist':
62 | test_dataset = MovingMNIST(args.test_data_dir, seq_len=args.short_len+args.out_len, train=False)
63 | testloader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, drop_last=False)
64 | elif args.dataset == 'kth':
65 | test_dataset = KTH(args.test_data_dir, seq_len=args.short_len+args.out_len, train=False)
66 | testloader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, drop_last=False)
67 |
68 | clips = testloader.sampler.data_source.clips
69 | lpips_dist = lpips.LPIPS(net = 'alex').to(device)
70 | valid_mse, valid_psnr, valid_ssim, valid_lpips = AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter()
71 |
72 | print('Start testing...')
73 | pred_model.eval()
74 | with torch.no_grad():
75 | for test_i, test_data in enumerate(testloader):
76 | # define data indexes
77 | short_data_start, short_data_end = 0, args.short_len
78 | out_gt_start, out_gt_end = short_data_end, short_data_end+args.out_len
79 |
80 | # obtain input data and output gt
81 | test_data = torch.stack(test_data).to(device)
82 | test_data = test_data.transpose(dim0=0, dim1=1)
83 | short_data = test_data[:, short_data_start:short_data_end, :, :, :]
84 | out_gt = test_data[:, out_gt_start:out_gt_end, :, :, :]
85 |
86 | # frame prediction
87 | out_pred = pred_model(short_data, None, args.out_len, phase=2)
88 | out_pred = torch.clamp(out_pred, min = 0, max = 1)
89 |
90 | # calculate evaluation metrics
91 | batch_size_current = test_data.shape[0]
92 | if args.evaluate:
93 | mse, psnr, ssim, lpips = calculate_metrics(out_pred, out_gt, lpips_dist, args)
94 | valid_mse.update(np.mean(mse), batch_size_current)
95 | valid_psnr.update(np.mean(psnr), batch_size_current)
96 | valid_ssim.update(np.mean(ssim), batch_size_current)
97 | valid_lpips.update(np.mean(lpips), batch_size_current)
98 |
99 | # generate predicted frames
100 | if args.make_frame:
101 | for batch_i in range(batch_size_current):
102 | video_i, frame_start = clips[test_i*args.batch_size+batch_i]
103 | if not os.path.isdir(args.test_result_dir + '/video_'+ str(video_i)+'_' + str(frame_start)):
104 | os.makedirs(args.test_result_dir + '/video_'+ str(video_i)+'_' + str(frame_start))
105 | for frame_i in range(args.short_len):
106 | cv2.imwrite(args.test_result_dir + '/video_'+ str(video_i)+'_' + str(frame_start)+ '/input_'
107 | +str(frame_i).zfill(5) + '.jpg', short_data[batch_i,frame_i,0,:,:].cpu().numpy()*255)
108 | for frame_i in range(args.out_len):
109 | cv2.imwrite(args.test_result_dir+'/video_'+str(video_i)+'_'+str(frame_start)+'/pred_'+
110 | str(frame_i+args.short_len).zfill(5)+'.jpg', out_pred[batch_i,frame_i,0,:,:].cpu().numpy()*255)
111 |
112 | if args.evaluate:
113 | print('************** test_output_length [{}] **************'
114 | .format(args.out_len))
115 | print('mse: {:.3f}, psnr: {:.3f}, ssim: {:.3f}, lpips: {:.3f}'
116 | .format(valid_mse.avg, valid_psnr.avg, valid_ssim.avg, valid_lpips.avg))
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | from model import Predictor
2 | from dataloader import MovingMNIST, KTH
3 | from utils import *
4 |
5 | import torch
6 | import torch.nn as nn
7 | from torch.utils.data import DataLoader
8 |
9 | import lpips
10 | import argparse
11 | import numpy as np
12 | import time
13 | import os
14 |
15 |
16 | seed = 1234
17 | np.random.seed(seed)
18 | torch.manual_seed(seed)
19 | torch.cuda.manual_seed(seed)
20 | torch.cuda.manual_seed_all(seed)
21 |
22 | parser = argparse.ArgumentParser()
23 | parser.add_argument('--dataset', type=str, default='movingmnist',
24 | help='training dataset (movingmnist or kth)')
25 | parser.add_argument('--workers', type=int, default=4,
26 | help='number of data loading workers')
27 | parser.add_argument('--train_data_dir', type=str, default='enter_the_path',
28 | help='directory of training set')
29 | parser.add_argument('--valid_data_dir', type=str, default='enter_the_path',
30 | help='directory of validation set')
31 | parser.add_argument('--checkpoint_load', type=bool, default=False,
32 | help='whether to load checkpoint')
33 | parser.add_argument('--checkpoint_load_file', type=str, default='enter_the_path',
34 | help='file path for loading checkpoint')
35 | parser.add_argument('--checkpoint_save_dir', type=str, default='./checkpoints',
36 | help='directory for saving checkpoints')
37 |
38 | parser.add_argument('--img_size', type=int, default=64,
39 | help='height and width of video frame')
40 | parser.add_argument('--img_channel', type=int, default=1,
41 | help='channel of video frame')
42 | parser.add_argument('--memory_size', type=int, default=100,
43 | help='memory slot size')
44 | parser.add_argument('--short_len', type=int, default=10,
45 | help='number of input short-term frames')
46 | parser.add_argument('--long_len', type=int, default=30,
47 | help='number of input long-term frames')
48 | parser.add_argument('--out_len', type=int, default=30,
49 | help='number of output predicted frames')
50 |
51 | parser.add_argument('--batch_size', type=int, default=128,
52 | help='mini-batch size')
53 | parser.add_argument('--lr', type=float, default=0.0002,
54 | help='learning rate')
55 | parser.add_argument('--iterations', type=int, default=300000,
56 | help='number of total iterations')
57 | parser.add_argument('--iterations_warmup', type=int, default=5000,
58 | help='number of iterations for warming up model')
59 | parser.add_argument('--print_freq', type=int, default=1000,
60 | help='frequency of printing logs')
61 | args = parser.parse_args()
62 |
63 |
64 | if __name__ == '__main__':
65 | if not os.path.isdir(args.checkpoint_save_dir):
66 | os.makedirs(args.checkpoint_save_dir)
67 |
68 | # define the model
69 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
70 | pred_model = Predictor(args).to(device)
71 | pred_model = nn.DataParallel(pred_model)
72 |
73 | # optionally load checkpoint
74 | if args.checkpoint_load:
75 | pred_model.load_state_dict(torch.load(args.checkpoint_load_file))
76 | print('Checkpoint is loaded from ' + args.checkpoint_load_file)
77 |
78 | # prepare dataloader for selected dataset
79 | if args.dataset == 'movingmnist':
80 | train_dataset = MovingMNIST(args.train_data_dir, seq_len=args.short_len+args.out_len, train=True)
81 | trainloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True)
82 | valid_dataset = MovingMNIST(args.valid_data_dir, seq_len=args.short_len+args.out_len, train=False)
83 | validloader = DataLoader(valid_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, drop_last=False)
84 | elif args.dataset == 'kth':
85 | train_dataset = KTH(args.train_data_dir, seq_len=args.short_len+args.out_len, train=True)
86 | trainloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True)
87 | valid_dataset = KTH(args.valid_data_dir, seq_len=args.short_len+args.out_len, train=False)
88 | validloader = DataLoader(valid_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, drop_last=False)
89 |
90 | # define optimizer and loss function
91 | optimizer = torch.optim.Adam(pred_model.parameters(), lr=args.lr)
92 | l1_loss, l2_loss = nn.L1Loss().to(device), nn.MSELoss().to(device)
93 | lpips_dist = lpips.LPIPS(net = 'alex').to(device)
94 |
95 | mse_min, psnr_max, ssim_max, lpips_min = 99999, 0, 0, 99999
96 | train_loss = AverageMeter()
97 | valid_mse, valid_psnr, valid_ssim, valid_lpips = AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter()
98 |
99 | print('Start training...')
100 | start_time = time.time()
101 | data_iterator = iter(trainloader)
102 | for train_i in range(args.iterations):
103 | try:
104 | train_data = next(data_iterator)
105 | except:
106 | data_iterator = iter(trainloader)
107 | train_data = next(data_iterator)
108 |
109 | # define data indexes
110 | short_start, short_end = 0, args.short_len
111 | long_start = np.random.randint(0, args.short_len+args.out_len-args.long_len+1)
112 | long_end = long_start+args.long_len
113 | out_gt_start, out_gt_end = short_end, short_end+args.out_len
114 |
115 | # obtain input data and output gt
116 | train_data = torch.stack(train_data).to(device)
117 | train_data = train_data.transpose(dim0=0, dim1=1) # make (N, T, C, H, W)
118 | short_data = train_data[:, short_start:short_end, :, :, :]
119 | long_data = train_data[:, long_start:long_end, :, :, :]
120 | out_gt = train_data[:, out_gt_start:out_gt_end, :, :, :]
121 |
122 | # predict only 10 frames in the first few iterations to warm up the model
123 | if (not args.checkpoint_load) and (train_i < args.iterations_warmup):
124 | train_out_len = 10
125 | long_data = train_data[:, short_start:out_gt_start+train_out_len, :, :, :]
126 | out_gt = train_data[:, out_gt_start:out_gt_start+train_out_len, :, :, :]
127 | else:
128 | train_out_len = args.out_len
129 |
130 | pred_model.train()
131 |
132 | # training phase 1 with long-term sequence
133 | pred_model.module.memory.memory_w.requires_grad = True # train memory weights
134 | out_pred = pred_model(short_data, long_data, train_out_len, phase=1)
135 | loss_p1 = l1_loss(out_pred, out_gt) + l2_loss(out_pred, out_gt)
136 | optimizer.zero_grad()
137 | loss_p1.backward()
138 | optimizer.step()
139 | # training phase 2 without long-term sequence
140 | pred_model.module.memory.memory_w.requires_grad = False # do not train memory weights
141 | out_pred = pred_model(short_data, None, train_out_len, phase=2)
142 | loss_p2 = l1_loss(out_pred, out_gt) + l2_loss(out_pred, out_gt)
143 | optimizer.zero_grad()
144 | loss_p2.backward()
145 | optimizer.step()
146 |
147 | train_loss.update(float(loss_p1) +float(loss_p2))
148 |
149 | if (train_i+1) % args.print_freq == 0:
150 | torch.save(pred_model.state_dict(), args.checkpoint_save_dir+'/trained_file_'+str(train_i+1).zfill(6)+'.pt')
151 |
152 | # validation phase
153 | pred_model.eval()
154 | with torch.no_grad():
155 | for valid_data in validloader:
156 | # define data indexes
157 | short_start, short_end = 0, args.short_len
158 | out_gt_start, out_gt_end = short_end, short_end+args.out_len
159 |
160 | # obtain input data and output gt
161 | valid_data = torch.stack(valid_data).to(device)
162 | valid_data = valid_data.transpose(dim0=0, dim1=1) # make (N, T, C, H, W)
163 | short_data = valid_data[:, short_start:short_end, :, :, :]
164 | out_gt = valid_data[:, out_gt_start:out_gt_end, :, :, :]
165 |
166 | # frame prediction and calculate evaluation metrics
167 | out_pred = pred_model(short_data, None, args.out_len, phase=2)
168 | out_pred = torch.clamp(out_pred, min = 0, max = 1)
169 | mse, psnr, ssim, lpips = calculate_metrics(out_pred, out_gt, lpips_dist, args)
170 |
171 | batch_size_current = valid_data.shape[0]
172 | valid_mse.update(np.mean(mse), batch_size_current)
173 | valid_psnr.update(np.mean(psnr), batch_size_current)
174 | valid_ssim.update(np.mean(ssim), batch_size_current)
175 | valid_lpips.update(np.mean(lpips), batch_size_current)
176 |
177 | mse_min = valid_mse.avg if valid_mse.avg < mse_min else mse_min
178 | psnr_max = valid_psnr.avg if valid_psnr.avg > psnr_max else psnr_max
179 | ssim_max = valid_ssim.avg if valid_ssim.avg > ssim_max else ssim_max
180 | lpips_min = valid_lpips.avg if valid_lpips.avg < lpips_min else lpips_min
181 |
182 | elapsed_time = time.time() - start_time; start_time = time.time()
183 | print('******** iter [{}] / epoch [{:.4f}] / loss [{:.4f}] ********'
184 | .format(train_i+1, (train_i+1)/len(trainloader), train_loss.avg))
185 | print('[current] mse: {:.3f}, psnr: {:.3f}, ssim: {:.3f}, lpips: {:.3f}'
186 | .format(valid_mse.avg, valid_psnr.avg, valid_ssim.avg, valid_lpips.avg))
187 | print('[ best ] mse: {:.3f}, psnr: {:.3f}, ssim: {:.3f}, lpips: {:.3f}'
188 | .format(mse_min, psnr_max, ssim_max, lpips_min))
189 | print('elapsed time: {:.0f} sec'.format(elapsed_time))
190 | train_loss.reset(); valid_mse.reset(); valid_psnr.reset(); valid_ssim.reset(); valid_lpips.reset()
191 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | import numpy as np
4 | from skimage.metrics import peak_signal_noise_ratio
5 | from skimage.metrics import structural_similarity
6 | from skimage.metrics import mean_squared_error
7 |
8 |
9 | class AverageMeter(object):
10 | """Computes and stores the average and current value"""
11 | def __init__(self):
12 | self.reset()
13 |
14 | def reset(self):
15 | self.val = 0
16 | self.avg = 0
17 | self.sum = 0
18 | self.count = 0
19 |
20 | def update(self, val, n=1):
21 | self.val = val
22 | self.sum += val * n
23 | self.count += n
24 | self.avg = self.sum / self.count
25 |
26 |
27 | def calculate_metrics(pred, gt, lpips_dist, args):
28 | batch_size = pred.shape[0]
29 | multi_channel = True if args.img_channel > 1 else False
30 |
31 | pred = pred.cpu().numpy()
32 | pred = np.transpose(pred, [0,1,3,4,2])
33 | gt = gt.cpu().numpy()
34 | gt = np.transpose(gt, [0,1,3,4,2])
35 |
36 | mse_mean = np.zeros(args.out_len, dtype=pred.dtype)
37 | psnr_mean = np.zeros(args.out_len, dtype=pred.dtype)
38 | ssim_mean = np.zeros(args.out_len, dtype=pred.dtype)
39 | lpips_mean = np.zeros(args.out_len, dtype=pred.dtype)
40 | gt = gt.astype(dtype=pred.dtype)
41 |
42 | for frame_i in range(-args.out_len, 0):
43 | for batch_i in range(batch_size):
44 | gt_frame = gt[batch_i,frame_i,:,:,:]
45 | pred_frame = pred[batch_i,frame_i,:,:,:]
46 | if args.img_channel == 1:
47 | gt_frame = np.squeeze(gt_frame)
48 | pred_frame = np.squeeze(pred_frame)
49 | mse_mean[frame_i] += mean_squared_error(gt_frame, pred_frame)/batch_size
50 | psnr_mean[frame_i] += peak_signal_noise_ratio(gt_frame, pred_frame)/batch_size
51 | ssim_mean[frame_i] += structural_similarity(gt_frame, pred_frame, multichannel=multi_channel)/batch_size
52 |
53 | batch_gt = gt[:,frame_i,:,:,:]
54 | batch_pred = pred[:,frame_i,:,:,:]
55 | batch_gt = np.transpose(batch_gt, [0,3,1,2])
56 | batch_pred = np.transpose(batch_pred, [0,3,1,2])
57 | if args.img_channel == 1:
58 | batch_gt = np.repeat(batch_gt, 3, axis=1)
59 | batch_pred = np.repeat(batch_pred, 3, axis=1)
60 | batch_gt = torch.from_numpy(batch_gt).float().to('cuda')
61 | batch_pred = torch.from_numpy(batch_pred).float().to('cuda')
62 | lpips_mean[frame_i] += np.mean(lpips_dist(batch_gt, batch_pred).cpu().numpy())
63 |
64 | mse_mean *= args.img_size**2
65 |
66 | return mse_mean, psnr_mean, ssim_mean, lpips_mean
67 |
--------------------------------------------------------------------------------