forked from thuml/predrnn-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
344 lines (287 loc) · 13.7 KB
/
run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
__author__ = 'yunbo'
import os
import shutil
import argparse
import numpy as np
import math
from core.data_provider import datasets_factory
from core.models.model_factory import Model
from core.utils import preprocess
import core.trainer as trainer
from core.data_provider.decouple_metrics import decouple_metrics
from core.data_provider.training_progress import training_progress
# -----------------------------------------------------------------------------
parser = argparse.ArgumentParser(description='PyTorch video prediction model - PredRNN')
# training/test
parser.add_argument('--is_training', type=int, default=1)
parser.add_argument('--device', type=str, default='cpu:0')
# data
parser.add_argument('--dataset_name', type=str, default='mnist')
parser.add_argument('--train_data_paths', type=str, default='data/moving-mnist-example/moving-mnist-train.npz')
parser.add_argument('--valid_data_paths', type=str, default='data/moving-mnist-example/moving-mnist-valid.npz')
parser.add_argument('--save_dir', type=str, default='checkpoints/mnist_predrnn')
parser.add_argument('--gen_frm_dir', type=str, default='results/mnist_predrnn')
parser.add_argument('--input_length', type=int, default=10)
parser.add_argument('--total_length', type=int, default=20)
parser.add_argument('--img_width', type=int, default=64)
parser.add_argument('--img_channel', type=int, default=1)
# model
parser.add_argument('--model_name', type=str, default='predrnn')
parser.add_argument('--pretrained_model', type=str, default='')
parser.add_argument('--num_hidden', type=str, default='64,64,64,64')
parser.add_argument('--filter_size', type=int, default=5)
parser.add_argument('--stride', type=int, default=1)
parser.add_argument('--patch_size', type=int, default=4)
parser.add_argument('--layer_norm', type=int, default=1)
parser.add_argument('--decouple_beta', type=float, default=0.1)
# reverse scheduled sampling
parser.add_argument('--reverse_scheduled_sampling', type=int, default=0)
parser.add_argument('--r_sampling_step_1', type=float, default=25000)
parser.add_argument('--r_sampling_step_2', type=int, default=50000)
parser.add_argument('--r_exp_alpha', type=int, default=5000)
# scheduled sampling
parser.add_argument('--scheduled_sampling', type=int, default=1)
parser.add_argument('--sampling_stop_iter', type=int, default=50000)
parser.add_argument('--sampling_start_value', type=float, default=1.0)
parser.add_argument('--sampling_changing_rate', type=float, default=0.00002)
# optimization
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--reverse_input', type=int, default=1)
parser.add_argument('--batch_size', type=int, default=8)
parser.add_argument('--max_iterations', type=int, default=80000)
parser.add_argument('--display_interval', type=int, default=100)
parser.add_argument('--test_interval', type=int, default=5000)
parser.add_argument('--snapshot_interval', type=int, default=5000)
parser.add_argument('--num_save_samples', type=int, default=10)
parser.add_argument('--n_gpu', type=int, default=1)
# visualization of memory decoupling
parser.add_argument('--visual', type=int, default=0)
parser.add_argument('--visual_path', type=str, default='./decoupling_visual')
# action-based predrnn
parser.add_argument('--injection_action', type=str, default='concat')
parser.add_argument('--conv_on_input', type=int, default=0, help='conv on input')
parser.add_argument('--res_on_conv', type=int, default=0, help='res on conv')
parser.add_argument('--num_action_ch', type=int, default=4, help='num action ch')
args = parser.parse_args()
print(args)
def reserve_schedule_sampling_exp(itr):
if itr < args.r_sampling_step_1:
r_eta = 0.5
elif itr < args.r_sampling_step_2:
r_eta = 1.0 - 0.5 * math.exp(-float(itr - args.r_sampling_step_1) / args.r_exp_alpha)
else:
r_eta = 1.0
if itr < args.r_sampling_step_1:
eta = 0.5
elif itr < args.r_sampling_step_2:
eta = 0.5 - (0.5 / (args.r_sampling_step_2 - args.r_sampling_step_1)) * (itr - args.r_sampling_step_1)
else:
eta = 0.0
r_random_flip = np.random.random_sample(
(args.batch_size, args.input_length - 1))
r_true_token = (r_random_flip < r_eta)
random_flip = np.random.random_sample(
(args.batch_size, args.total_length - args.input_length - 1))
true_token = (random_flip < eta)
ones = np.ones((args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
zeros = np.zeros((args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
real_input_flag = []
for i in range(args.batch_size):
for j in range(args.total_length - 2):
if j < args.input_length - 1:
if r_true_token[i, j]:
real_input_flag.append(ones)
else:
real_input_flag.append(zeros)
else:
if true_token[i, j - (args.input_length - 1)]:
real_input_flag.append(ones)
else:
real_input_flag.append(zeros)
real_input_flag = np.array(real_input_flag)
real_input_flag = np.reshape(real_input_flag,
(args.batch_size,
args.total_length - 2,
args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
return real_input_flag
r_eta_momentum = 0.0
eta_momentum = 0.0
beta1 = 0.9
bias_weight = 0.005
beta3 = 5.0
beta4 = 1.0
beta5 = 0.3
beta6 = 1.0
samples = 12
def adaptive_reserve_schedule_sampling_exp(itr):
global decouple_metrics
delta_c_avg = decouple_metrics['delta_c_avg']
delta_m_avg = decouple_metrics['delta_m_avg']
decouple_loss = decouple_metrics['decouple_loss']
global training_progress
losses = training_progress['loss']
etas = training_progress['eta']
r_etas = training_progress['r_eta']
delta_c_avgs = training_progress['delta_c_avg']
delta_m_avgs = training_progress['delta_m_avg']
decouple_losses = training_progress['decouple_loss']
if itr == 1:
r_eta = 0.5
eta = 0.5
else:
if itr < args.r_sampling_step_1:
eta_bias = 0.5
elif itr < args.r_sampling_step_2:
eta_bias = 0.5 - (0.5 / (args.r_sampling_step_2 - args.r_sampling_step_1)) * (itr - args.r_sampling_step_1)
else:
eta_bias = 0.0
global r_eta_momentum, eta_momentum
step_size = 1.0
if itr == 2:
loss_change = 0.0
decouple_change = 0.0
eta_change = 0.0
else:
loss_change = losses[-1] - losses[-2]
decouple_change = decouple_losses[-1] - decouple_losses[-2]
eta_change = etas[-1] - etas[-2]
std_m = np.std(delta_m_avgs[-samples:])
std_c = np.std(delta_c_avgs[-samples:])
std_decouple = np.std(decouple_losses[-samples:])
eta_bias_pull = bias_weight * (eta_bias - etas[-1])
eta_momentum = (beta1 * eta_momentum + (1 - beta1) * eta_change) * beta5
delta_c_addition = std_c * eta_bias * beta3
delta_m_addition = -std_m * (1.0 - eta_bias) * beta3
decouple_addition = std_decouple * eta_bias * beta4 + eta_bias * decouple_change * beta6
eta = max(0.0, min(1.0, etas[-1] + step_size * (eta_bias_pull + eta_momentum + decouple_addition + delta_c_addition + delta_m_addition)))
r_eta = 1.0 - eta
# afterwards, append every var to list for later analysis
training_progress['eta'].append(eta)
training_progress['r_eta'].append(r_eta)
training_progress['loss'].append(decouple_metrics['loss'])
training_progress['delta_c_avg'].append(decouple_metrics['delta_c_avg'])
training_progress['delta_m_avg'].append(decouple_metrics['delta_m_avg'])
training_progress['decouple_loss'].append(decouple_metrics['decouple_loss'])
r_random_flip = np.random.random_sample(
(args.batch_size, args.input_length - 1))
r_true_token = (r_random_flip < r_eta)
random_flip = np.random.random_sample(
(args.batch_size, args.total_length - args.input_length - 1))
true_token = (random_flip < eta)
ones = np.ones((args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
zeros = np.zeros((args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
real_input_flag = []
for i in range(args.batch_size):
for j in range(args.total_length - 2):
if j < args.input_length - 1:
if r_true_token[i, j]:
real_input_flag.append(ones)
else:
real_input_flag.append(zeros)
else:
if true_token[i, j - (args.input_length - 1)]:
real_input_flag.append(ones)
else:
real_input_flag.append(zeros)
real_input_flag = np.array(real_input_flag)
real_input_flag = np.reshape(real_input_flag,
(args.batch_size,
args.total_length - 2,
args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
return real_input_flag
def schedule_sampling(eta, itr):
zeros = np.zeros((args.batch_size,
args.total_length - args.input_length - 1,
args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
if not args.scheduled_sampling:
return 0.0, zeros
if itr < args.sampling_stop_iter:
eta -= args.sampling_changing_rate
else:
eta = 0.0
random_flip = np.random.random_sample(
(args.batch_size, args.total_length - args.input_length - 1))
true_token = (random_flip < eta)
ones = np.ones((args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
zeros = np.zeros((args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
real_input_flag = []
for i in range(args.batch_size):
for j in range(args.total_length - args.input_length - 1):
if true_token[i, j]:
real_input_flag.append(ones)
else:
real_input_flag.append(zeros)
real_input_flag = np.array(real_input_flag)
real_input_flag = np.reshape(real_input_flag,
(args.batch_size,
args.total_length - args.input_length - 1,
args.img_width // args.patch_size,
args.img_width // args.patch_size,
args.patch_size ** 2 * args.img_channel))
return eta, real_input_flag
def train_wrapper(model):
if args.pretrained_model:
model.load(args.pretrained_model)
# load data
train_input_handle, test_input_handle = datasets_factory.data_provider(
args.dataset_name, args.train_data_paths, args.valid_data_paths, args.batch_size, args.img_width,
seq_length=args.total_length, injection_action=args.injection_action, is_training=True)
eta = args.sampling_start_value
for itr in range(1, args.max_iterations + 1):
if train_input_handle.no_batch_left():
train_input_handle.begin(do_shuffle=True)
ims = train_input_handle.get_batch()
ims = preprocess.reshape_patch(ims, args.patch_size)
if args.reverse_scheduled_sampling == 1:
real_input_flag = reserve_schedule_sampling_exp(itr)
elif args.reverse_scheduled_sampling == 2:
# #TODO not sure if I should calculate the loss metrics here or if I should use the metrics of the previous training epoch
# #TODO Problem with last suggestion: no metrics available for first epoch
# frames_tensor = torch.FloatTensor(frames).to(self.configs.device)
# mask_tensor = torch.FloatTensor(mask).to(self.configs.device)
# next_frames, loss = model.network(frames_tensor, mask_tensor)
real_input_flag = adaptive_reserve_schedule_sampling_exp(itr)
else:
eta, real_input_flag = schedule_sampling(eta, itr)
trainer.train(model, ims, real_input_flag, args, itr)
if itr % args.snapshot_interval == 0:
model.save(itr)
if itr % args.test_interval == 0:
trainer.test(model, test_input_handle, args, itr)
train_input_handle.next()
def test_wrapper(model):
model.load(args.pretrained_model)
test_input_handle = datasets_factory.data_provider(
args.dataset_name, args.train_data_paths, args.valid_data_paths, args.batch_size, args.img_width,
seq_length=args.total_length, injection_action=args.injection_action, is_training=False)
trainer.test(model, test_input_handle, args, 'test_result')
if os.path.exists(args.save_dir):
shutil.rmtree(args.save_dir)
os.makedirs(args.save_dir)
if os.path.exists(args.gen_frm_dir):
shutil.rmtree(args.gen_frm_dir)
os.makedirs(args.gen_frm_dir)
print('Initializing models')
model = Model(args)
if args.is_training:
train_wrapper(model)
else:
test_wrapper(model)