main.py 31.1 KB
Newer Older
BobYeah's avatar
BobYeah committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import torch
import argparse
import os
import glob
import numpy as np
import torchvision.transforms as transforms
from torchvision.utils import save_image

from torchvision import datasets
from torch.utils.data import DataLoader 
from torch.autograd import Variable

import cv2
from gen_image import *
BobYeah's avatar
BobYeah committed
15
from loss import *
BobYeah's avatar
BobYeah committed
16
import json
BobYeah's avatar
BobYeah committed
17
18
from conf import Conf

BobYeah's avatar
BobYeah committed
19
20
from baseline import *
from data import * 
BobYeah's avatar
BobYeah committed
21
22

import torch.autograd.profiler as profiler
BobYeah's avatar
BobYeah committed
23
# param
BobYeah's avatar
BobYeah committed
24
25
BATCH_SIZE = 1
NUM_EPOCH = 1001
BobYeah's avatar
BobYeah committed
26
INTERLEAVE_RATE = 2
BobYeah's avatar
Gaze    
BobYeah committed
27
28
29
30
IM_H = 320
IM_W = 320
Retinal_IM_H = 320
Retinal_IM_W = 320
BobYeah's avatar
BobYeah committed
31
N = 25 # number of input light field stack
BobYeah's avatar
BobYeah committed
32
M = 2 # number of display layers
BobYeah's avatar
BobYeah committed
33
34
35
36
DATA_FILE = "/home/yejiannan/Project/LightField/data/FlowRPG1211"
DATA_JSON = "/home/yejiannan/Project/LightField/data/data_gaze_fovea_seq_flow_RPG.json"
# DATA_VAL_JSON = "/home/yejiannan/Project/LightField/data/data_gaze_fovea_val.json"
OUTPUT_DIR = "/home/yejiannan/Project/LightField/outputE/gaze_fovea_seq_flow_RPG_seq5_same_loss"
BobYeah's avatar
BobYeah committed
37
38
39
40
OUT_CHANNELS_RB = 128
KERNEL_SIZE_RB = 3
KERNEL_SIZE = 3
LAST_LAYER_CHANNELS = 6 * INTERLEAVE_RATE**2
BobYeah's avatar
BobYeah committed
41
FIRSST_LAYER_CHANNELS = 75 * INTERLEAVE_RATE**2
BobYeah's avatar
BobYeah committed
42

BobYeah's avatar
Gaze    
BobYeah committed
43
44
def GenRetinalFromLayersBatch(layers, gen, sample_idx, phi_dict, mask_dict):
    # layers: batchsize, 2*color, height, width 
BobYeah's avatar
BobYeah committed
45
46
    # Phi:torch.Size([batchsize, 480, 640, 2, 41, 2])
    # df : batchsize,..
BobYeah's avatar
Gaze    
BobYeah committed
47
48
49
50
51
52
    
    #  retinal bs x color x height x width
    retinal = torch.zeros(layers.shape[0], 3, Retinal_IM_H, Retinal_IM_W)
    mask = [] # mask shape 480 x 640
    for i in range(0, layers.size()[0]):
        phi = phi_dict[int(sample_idx[i].data)]
BobYeah's avatar
BobYeah committed
53
        # print("phi_i:",phi.shape)
BobYeah's avatar
Gaze    
BobYeah committed
54
55
        phi = var_or_cuda(phi)
        phi.requires_grad = False
BobYeah's avatar
BobYeah committed
56
57
        # print("layers[i]:",layers[i].shape)
        # print("retinal[i]:",retinal[i].shape)
BobYeah's avatar
Gaze    
BobYeah committed
58
59
        retinal[i] = gen.GenRetinalFromLayers(layers[i],phi)
        mask.append(mask_dict[int(sample_idx[i].data)])
BobYeah's avatar
BobYeah committed
60
    retinal = var_or_cuda(retinal)
BobYeah's avatar
Gaze    
BobYeah committed
61
62
    mask = torch.stack(mask,dim = 0).unsqueeze(1) # batch x 1 x height x width
    return retinal, mask
BobYeah's avatar
BobYeah committed
63

BobYeah's avatar
BobYeah committed
64
65
66
67
68
69
70
71
def GenRetinalGazeFromLayersBatch(layers, gen, sample_idx, phi_dict, mask_dict):
    # layers: batchsize, 2*color, height, width 
    # Phi:torch.Size([batchsize, 480, 640, 2, 41, 2])
    # df : batchsize,..
    
    #  retinal bs x color x height x width
    retinal_fovea = torch.empty(layers.shape[0], 6, 160, 160)
    mask_fovea = torch.empty(layers.shape[0], 2, 160, 160)
BobYeah's avatar
BobYeah committed
72

BobYeah's avatar
BobYeah committed
73
74
75
76
77
78
79
80
81
82
83
84
85
    for i in range(0, layers.size()[0]):
        phi = phi_dict[int(sample_idx[i].data)]
        # print("phi_i:",phi.shape)
        phi = var_or_cuda(phi)
        phi.requires_grad = False
        mask_i = var_or_cuda(mask_dict[int(sample_idx[i].data)])
        mask_i.requires_grad = False
        # print("layers[i]:",layers[i].shape)
        # print("retinal[i]:",retinal[i].shape)
        retinal_i = gen.GenRetinalFromLayers(layers[i],phi)
        fovea_layers, fovea_layer_masks = gen.GenFoveaLayers(retinal_i,mask_i)
        retinal_fovea[i] = torch.cat([fovea_layers[0],fovea_layers[1]],dim=0)
        mask_fovea[i] = torch.stack([fovea_layer_masks[0],fovea_layer_masks[1]],dim=0)
BobYeah's avatar
BobYeah committed
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
    

    retinal_fovea = var_or_cuda(retinal_fovea)
    mask_fovea = var_or_cuda(mask_fovea) # batch x 2 x height x width
    # mask = torch.stack(mask,dim = 0).unsqueeze(1) 
    return retinal_fovea, mask_fovea

import time
def GenRetinalGazeFromLayersBatchSpeed(layers, gen, phi, phi_invalid, retinal_invalid):
    # layers: batchsize, 2*color, height, width 
    # Phi:torch.Size([batchsize, Layer, h, w,  41, 2])
    # df : batchsize,..
    # start1 = time.time()
    #  retinal bs x color x height x width
    retinal_fovea = torch.empty((layers.shape[0], 6, 160, 160),device="cuda:2")
    mask_fovea = torch.empty((layers.shape[0], 2, 160, 160),device="cuda:2")
    # start = time.time()
    retinal = gen.GenRetinalFromLayersBatch(layers,phi_batch)
    # print("retinal:",retinal.shape) #retinal: torch.Size([2, 3, 320, 320])
    # print("t2:",time.time() - start)

    # start = time.time()
    fovea_layers, fovea_layer_masks = gen.GenFoveaLayersBatch(retinal,mask_batch)

    mask_fovea = torch.stack([fovea_layer_masks[0],fovea_layer_masks[1]],dim=1)
    retinal_fovea = torch.cat([fovea_layers[0],fovea_layers[1]],dim=1)
    # print("t3:",time.time() - start)

BobYeah's avatar
BobYeah committed
114
115
116
117
118
    retinal_fovea = var_or_cuda(retinal_fovea)
    mask_fovea = var_or_cuda(mask_fovea) # batch x 2 x height x width
    # mask = torch.stack(mask,dim = 0).unsqueeze(1) 
    return retinal_fovea, mask_fovea

BobYeah's avatar
BobYeah committed
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
def MergeBatchSpeed(layers, gen, phi, phi_invalid, retinal_invalid):
    # layers: batchsize, 2*color, height, width 
    # Phi:torch.Size([batchsize, Layer, h, w,  41, 2])
    # df : batchsize,..
    # start1 = time.time()
    #  retinal bs x color x height x width
    # retinal_fovea = torch.empty((layers.shape[0], 6, 160, 160),device="cuda:2")
    # mask_fovea = torch.empty((layers.shape[0], 2, 160, 160),device="cuda:2")
    # start = time.time()
    retinal = gen.GenRetinalFromLayersBatch(layers,phi) #retinal: torch.Size([BatchSize , 3, 320, 320])
    retinal.mul_(~retinal_invalid.to("cuda:2"))
    # print("retinal:",retinal.shape) 
    # print("t2:",time.time() - start)
    
    # start = time.time()
    # fovea_layers, fovea_layer_masks = gen.GenFoveaLayersBatch(retinal,mask_batch)

    # mask_fovea = torch.stack([fovea_layer_masks[0],fovea_layer_masks[1]],dim=1)
    # retinal_fovea = torch.cat([fovea_layers[0],fovea_layers[1]],dim=1)
    # print("t3:",time.time() - start)

    # retinal_fovea = var_or_cuda(retinal_fovea)
    # mask_fovea = var_or_cuda(mask_fovea) # batch x 2 x height x width
    # mask = torch.stack(mask,dim = 0).unsqueeze(1) 
    return retinal

BobYeah's avatar
Gaze    
BobYeah committed
145
146
147
148
149
150
151
152
153
154
155
156
157
def GenRetinalFromLayersBatch_Online(layers, gen, phi, mask):
    # layers: batchsize, 2*color, height, width 
    # Phi:torch.Size([batchsize, 480, 640, 2, 41, 2])
    # df : batchsize,..
    
    #  retinal bs x color x height x width
    # retinal = torch.zeros(layers.shape[0], 3, Retinal_IM_H, Retinal_IM_W)
    # retinal = var_or_cuda(retinal)
    phi = var_or_cuda(phi)
    phi.requires_grad = False
    retinal = gen.GenRetinalFromLayers(layers[0],phi)
    retinal = var_or_cuda(retinal)
    mask_out = mask.unsqueeze(0).unsqueeze(0)
BobYeah's avatar
BobYeah committed
158
159
    # print("maskOUt:",mask_out.shape) # 1,1,240,320
    # mask_out = torch.stack(mask,dim = 0).unsqueeze(1) # batch x 1 x height x width
BobYeah's avatar
Gaze    
BobYeah committed
160
161
    return retinal.unsqueeze(0), mask_out
#### Image Gen End
BobYeah's avatar
BobYeah committed
162

BobYeah's avatar
BobYeah committed
163
from weight_init import weight_init_normal
BobYeah's avatar
BobYeah committed
164
165
166
167
168
169
170
171
172
173

def save_checkpoints(file_path, epoch_idx, model, model_solver):
    print('[INFO] Saving checkpoint to %s ...' % ( file_path))
    checkpoint = {
        'epoch_idx': epoch_idx,
        'model_state_dict': model.state_dict(),
        'model_solver_state_dict': model_solver.state_dict()
    }
    torch.save(checkpoint, file_path)

BobYeah's avatar
BobYeah committed
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
# import pickle
# def save_obj(obj, name ):
#     # with open('./outputF/dict/'+ name + '.pkl', 'wb') as f:
#     #     pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
#     torch.save(obj,'./outputF/dict/'+ name + '.pkl')
# def load_obj(name):
#     # with open('./outputF/dict/' + name + '.pkl', 'rb') as f:
#     #     return pickle.load(f)
#     return torch.load('./outputF/dict/'+ name + '.pkl')

# def generatePhiMaskDict(data_json, generator):
#     phi_dict = {}
#     mask_dict = {}
#     idx_info_dict = {}
#     with open(data_json, encoding='utf-8') as file:
#         dataset_desc = json.loads(file.read())
#         for i in range(len(dataset_desc["focaldepth"])):
#             # if i == 2:
#             #     break
#             idx = dataset_desc["idx"][i] 
#             focaldepth = dataset_desc["focaldepth"][i]
#             gazeX = dataset_desc["gazeX"][i]
#             gazeY = dataset_desc["gazeY"][i]
#             print("focaldepth:",focaldepth," idx:",idx," gazeX:",gazeX," gazeY:",gazeY)
#             phi,mask =  generator.CalculateRetinal2LayerMappings(focaldepth,torch.tensor([gazeX, gazeY]))
#             phi_dict[idx]=phi
#             mask_dict[idx]=mask
#             idx_info_dict[idx]=[idx,focaldepth,gazeX,gazeY]
#     return phi_dict,mask_dict,idx_info_dict

# def generatePhiMaskDictNew(data_json, generator):
#     phi_dict = {}
#     mask_dict = {}
#     idx_info_dict = {}
#     with open(data_json, encoding='utf-8') as file:
#         dataset_desc = json.loads(file.read())
#         for i in range(len(dataset_desc["seq"])):
#             for j in dataset_desc["seq"][i]:
#                 idx = dataset_desc["idx"][j] 
#                 focaldepth = dataset_desc["focaldepth"][j]
#                 gazeX = dataset_desc["gazeX"][j]
#                 gazeY = dataset_desc["gazeY"][j]
#                 print("focaldepth:",focaldepth," idx:",idx," gazeX:",gazeX," gazeY:",gazeY)
#                 phi,mask =  generator.CalculateRetinal2LayerMappings(focaldepth,torch.tensor([gazeX, gazeY]))
#                 phi_dict[idx]=phi
#                 mask_dict[idx]=mask
#                 idx_info_dict[idx]=[idx,focaldepth,gazeX,gazeY]
#     return phi_dict,mask_dict,idx_info_dict

mode = "Silence" #"Perf"
model_type = "RNN" #"RNN"
w_frame = 0.9
w_inter_frame = 0.1
batch_model = "NoSingle"
loss1 = ReconstructionLoss()
loss2 = ReconstructionLoss()
BobYeah's avatar
BobYeah committed
230
231
if __name__ == "__main__":
    ############################## generate phi and mask in pre-training
BobYeah's avatar
BobYeah committed
232
    
BobYeah's avatar
BobYeah committed
233
    # print("generating phi and mask...")
BobYeah's avatar
BobYeah committed
234
235
236
237
    # phi_dict,mask_dict,idx_info_dict = generatePhiMaskDictNew(DATA_JSON,gen)
    # # save_obj(phi_dict,"phi_1204")
    # # save_obj(mask_dict,"mask_1204")
    # # save_obj(idx_info_dict,"idx_info_1204")
BobYeah's avatar
BobYeah committed
238
    # print("generating phi and mask end.")
BobYeah's avatar
Gaze    
BobYeah committed
239
    # exit(0)
BobYeah's avatar
BobYeah committed
240
    ############################# load phi and mask in pre-training
BobYeah's avatar
BobYeah committed
241
242
243
244
245
246
247
248
249
250
251
    # print("loading phi and mask ...")
    # phi_dict = load_obj("phi_1204")
    # mask_dict = load_obj("mask_1204")
    # idx_info_dict = load_obj("idx_info_1204")
    # print(len(phi_dict))
    # print(len(mask_dict))
    # print("loading phi and mask end") 

    #### Image Gen and conf 
    conf = Conf()
    gen = RetinalGen(conf)
BobYeah's avatar
BobYeah committed
252

BobYeah's avatar
BobYeah committed
253
    #train
BobYeah's avatar
BobYeah committed
254
    train_data_loader = torch.utils.data.DataLoader(dataset=lightFieldFlowSeqDataLoader(DATA_FILE,DATA_JSON, gen, conf),
BobYeah's avatar
BobYeah committed
255
                                                    batch_size=BATCH_SIZE,
BobYeah's avatar
BobYeah committed
256
                                                    num_workers=8,
BobYeah's avatar
BobYeah committed
257
                                                    pin_memory=True,
BobYeah's avatar
BobYeah committed
258
                                                    shuffle=True,
BobYeah's avatar
BobYeah committed
259
                                                    drop_last=False)
BobYeah's avatar
BobYeah committed
260
    #Data loader test
BobYeah's avatar
BobYeah committed
261
    print(len(train_data_loader))
BobYeah's avatar
BobYeah committed
262

BobYeah's avatar
BobYeah committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    # # lightfield_images, gt, flow, fd, gazeX, gazeY, posX, posY, sample_idx, phi, mask
    # # lightfield_images, gt, phi, phi_invalid, retinal_invalid, flow, fd, gazeX, gazeY, posX, posY, posZ, sample_idx
    # for batch_idx, (image_set, gt,phi, phi_invalid, retinal_invalid, flow, df, gazeX, gazeY, posX, posY, posZ, sample_idx) in enumerate(train_data_loader):
    #     print(image_set.shape,type(image_set))
    #     print(gt.shape,type(gt))
    #     print(phi.shape,type(phi))
    #     print(phi_invalid.shape,type(phi_invalid))
    #     print(retinal_invalid.shape,type(retinal_invalid))
    #     print(flow.shape,type(flow))
    #     print(df.shape,type(df))
    #     print(gazeX.shape,type(gazeX))
    #     print(posX.shape,type(posX))
    #     print(sample_idx.shape,type(sample_idx))
    #     print("test train dataloader.")
    #     exit(0)
    #Data loader test end
    
BobYeah's avatar
BobYeah committed
280

BobYeah's avatar
BobYeah committed
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

    ################################################ val #########################################################
    # val_data_loader = torch.utils.data.DataLoader(dataset=lightFieldValDataLoader(DATA_FILE,DATA_VAL_JSON),
    #                                                 batch_size=1,
    #                                                 num_workers=0,
    #                                                 pin_memory=True,
    #                                                 shuffle=False,
    #                                                 drop_last=False)

    # print(len(val_data_loader))

    # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # lf_model = baseline.model()
    # if torch.cuda.is_available():
    #     lf_model = torch.nn.DataParallel(lf_model).cuda()

    # checkpoint = torch.load(os.path.join(OUTPUT_DIR,"gaze-ckpt-epoch-0201.pth"))
    # lf_model.load_state_dict(checkpoint["model_state_dict"])
    # lf_model.eval()

    # print("Eval::")
    # for sample_idx, (image_set, df, gazeX, gazeY, sample_idx) in enumerate(val_data_loader):
    #     print("sample_idx::",sample_idx)
    #     with torch.no_grad():
            
    #         #reshape for input
    #         image_set = image_set.permute(0,1,4,2,3) # N LF C H W
    #         image_set = image_set.reshape(image_set.shape[0],-1,image_set.shape[3],image_set.shape[4]) # N, LFxC, H, W
    #         image_set = var_or_cuda(image_set)

    #         # print("Epoch:",epoch,",Iter:",batch_idx,",Input shape:",image_set.shape, ",Input gt:",gt.shape)
    #         output = lf_model(image_set,df,gazeX,gazeY)
    #         output1,mask = GenRetinalGazeFromLayersBatch(output, gen, sample_idx, phi_dict, mask_dict)

    #         for i in range(0, 2):
    #             output1[:,i*3:i*3+3].mul_(mask[:,i:i+1])
    #             output1[:,i*3:i*3+3].clamp_(0., 1.)
            
    #         print("output:",output.shape," df:",df[0].data, ",gazeX:",gazeX[0].data,",gazeY:", gazeY[0].data)
    #         for i in range(output1.size()[0]):
BobYeah's avatar
BobYeah committed
321
322
323
324
    #             save_image(output[i][0:3].data,os.path.join(OUTPUT_DIR,"test_interp_gaze_fac1_o_%.5f_%.5f_%.5f.png"%(df[i].data,gazeX[i].data,gazeY[i].data)))
    #             save_image(output[i][3:6].data,os.path.join(OUTPUT_DIR,"test_interp_gaze_fac2_o_%.5f_%.5f_%.5f.png"%(df[i].data,gazeX[i].data,gazeY[i].data)))
    #             save_image(output1[i][0:3].data,os.path.join(OUTPUT_DIR,"test_interp_gaze_out1_o_%.5f_%.5f_%.5f.png"%(df[i].data,gazeX[i].data,gazeY[i].data)))
    #             save_image(output1[i][3:6].data,os.path.join(OUTPUT_DIR,"test_interp_gaze_out2_o_%.5f_%.5f_%.5f.png"%(df[i].data,gazeX[i].data,gazeY[i].data)))
BobYeah's avatar
BobYeah committed
325

BobYeah's avatar
BobYeah committed
326
327
    #         # save_image(output[0][0:3].data,os.path.join(OUTPUT_DIR,"gaze_fovea_interp_l1_%.5f.png"%(df[0].data)))
    #         # save_image(output[0][3:6].data,os.path.join(OUTPUT_DIR,"gaze_fovea_interp_l2_%.5f.png"%(df[0].data)))
BobYeah's avatar
BobYeah committed
328
    #         # output = GenRetinalFromLayersBatch(output,conf,df,v,u)
BobYeah's avatar
BobYeah committed
329
    #         # save_image(output[0][0:3].data,os.path.join(OUTPUT_DIR,"1113_interp_o%.5f.png"%(df[0].data)))
BobYeah's avatar
BobYeah committed
330
331
    # exit()

BobYeah's avatar
Gaze    
BobYeah committed
332
    ################################################ train #########################################################
BobYeah's avatar
BobYeah committed
333
334
335
336
    if model_type == "RNN": 
        lf_model = model(FIRSST_LAYER_CHANNELS,LAST_LAYER_CHANNELS,OUT_CHANNELS_RB,KERNEL_SIZE,KERNEL_SIZE_RB,INTERLEAVE_RATE)
    else:
        lf_model = model(FIRSST_LAYER_CHANNELS,LAST_LAYER_CHANNELS,OUT_CHANNELS_RB,KERNEL_SIZE,KERNEL_SIZE_RB,INTERLEAVE_RATE,RNN=False)
BobYeah's avatar
Gaze    
BobYeah committed
337
    lf_model.apply(weight_init_normal)
BobYeah's avatar
BobYeah committed
338
    lf_model.train()
BobYeah's avatar
Gaze    
BobYeah committed
339
340
    epoch_begin = 0

BobYeah's avatar
BobYeah committed
341
342
343
344
345
346
347
348
349
350
    ################################ load model file
    # WEIGHTS = os.path.join(OUTPUT_DIR, 'gaze-ckpt-epoch-%04d.pth' % (101))
    # print('[INFO] Recovering from %s ...' % (WEIGHTS))
    # checkpoint = torch.load(WEIGHTS)
    # init_epoch = checkpoint['epoch_idx']
    # lf_model.load_state_dict(checkpoint['model_state_dict'])
    # epoch_begin = init_epoch + 1
    # print(lf_model)
    ############################################################

BobYeah's avatar
BobYeah committed
351
    if torch.cuda.is_available():
BobYeah's avatar
BobYeah committed
352
        # lf_model = torch.nn.DataParallel(lf_model).cuda()
BobYeah's avatar
BobYeah committed
353
354
355
356
        lf_model = lf_model.to('cuda:2')
    
    optimizer = torch.optim.Adam(lf_model.parameters(),lr=5e-3,betas=(0.9,0.999))
    
BobYeah's avatar
BobYeah committed
357
    # lf_model.output_layer.register_backward_hook(hook_fn_back)
BobYeah's avatar
BobYeah committed
358
359
360
361
    if mode=="Perf":
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
BobYeah's avatar
Gaze    
BobYeah committed
362
363
    print("begin training....")
    for epoch in range(epoch_begin, NUM_EPOCH):
BobYeah's avatar
BobYeah committed
364
        for batch_idx, (image_set, gt,phi, phi_invalid, retinal_invalid, flow, flow_invalid_mask, df, gazeX, gazeY, posX, posY, posZ, sample_idx) in enumerate(train_data_loader):
BobYeah's avatar
BobYeah committed
365
366
367
            # print(sample_idx.shape,df.shape,gazeX.shape,gazeY.shape) # torch.Size([2, 5])
            # print(image_set.shape,gt.shape,gt2.shape) #torch.Size([2, 5, 9, 320, 320, 3]) torch.Size([2, 5, 160, 160, 3]) torch.Size([2, 5, 160, 160, 3])
            # print(delta.shape) # delta: torch.Size([2, 4, 160, 160, 3])
BobYeah's avatar
BobYeah committed
368
369
370
371
372
373
            if mode=="Perf":
                end.record()
                torch.cuda.synchronize()
                print("load:",start.elapsed_time(end))

                start.record()
BobYeah's avatar
BobYeah committed
374
            #reshape for input
BobYeah's avatar
BobYeah committed
375
            image_set = image_set.permute(0,1,2,5,3,4) # N Seq 5 LF 25 C 3 H W 
BobYeah's avatar
BobYeah committed
376
            image_set = image_set.reshape(image_set.shape[0],image_set.shape[1],-1,image_set.shape[4],image_set.shape[5]) # N, LFxC, H, W
BobYeah's avatar
BobYeah committed
377
            # N, Seq 5, LF 25 C 3, H, W 
BobYeah's avatar
BobYeah committed
378
            image_set = var_or_cuda(image_set)
BobYeah's avatar
BobYeah committed
379
380
381
            # print(image_set.shape) #torch.Size([2, 5, 75, 320, 320])

            gt = gt.permute(0,1,4,2,3) # BS Seq 5 C 3 H W 
BobYeah's avatar
BobYeah committed
382
            gt = var_or_cuda(gt)
BobYeah's avatar
Gaze    
BobYeah committed
383

BobYeah's avatar
BobYeah committed
384
385
386
387
            flow = var_or_cuda(flow) #BS,Seq-1,H,W,2

            # gt2 = gt2.permute(0,1,4,2,3)
            # gt2 = var_or_cuda(gt2)
BobYeah's avatar
BobYeah committed
388

BobYeah's avatar
BobYeah committed
389
            gen1 = torch.empty(gt.shape) # BS Seq C H W
BobYeah's avatar
BobYeah committed
390
            gen1 = var_or_cuda(gen1)
BobYeah's avatar
BobYeah committed
391
            # print(gen1.shape) #torch.Size([2, 5, 3, 320, 320])
BobYeah's avatar
BobYeah committed
392

BobYeah's avatar
BobYeah committed
393
394
            # gen2 = torch.empty(gt2.shape)
            # gen2 = var_or_cuda(gen2)
BobYeah's avatar
BobYeah committed
395

BobYeah's avatar
BobYeah committed
396
397
            #BS, Seq - 1, C, H, W
            warped = torch.empty(gt.shape[0],gt.shape[1]-1,gt.shape[2],gt.shape[3],gt.shape[4])
BobYeah's avatar
BobYeah committed
398
            warped = var_or_cuda(warped)
BobYeah's avatar
BobYeah committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
            gen_temp = torch.empty(warped.shape)
            gen_temp = var_or_cuda(gen_temp)
            # print("warped:",warped.shape) #warped: torch.Size([2, 4, 3, 320, 320])
            if mode=="Perf":
                end.record()
                torch.cuda.synchronize()
                print("data prepare:",start.elapsed_time(end))

                start.record()
            if model_type == "RNN": 
                if batch_model != "Single":
                    for k in range(image_set.shape[1]):
                        if k == 0:
                            lf_model.reset_hidden(image_set[:,k])
                        output = lf_model(image_set[:,k],df[:,k],gazeX[:,k],gazeY[:,k],posX[:,k],posY[:,k],posZ[:,k]) # batchsize, layer_num x 2 = 6, layer_res: 320, layer_res: 320
                        output1 = MergeBatchSpeed(output, gen, phi[:,k], phi_invalid[:,k], retinal_invalid[:,k])
                        gen1[:,k] = output1[:,0:3]
                        gt[:,k] = gt[:,k].mul_(~retinal_invalid[:,k].to("cuda:2"))

                        if ((epoch%10 == 0 and epoch != 0) or epoch == 2):
                            for i in range(output.shape[0]):
                                save_image(output[i][0:3].data,os.path.join(OUTPUT_DIR,"gaze_fac1_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                                save_image(output[i][3:6].data,os.path.join(OUTPUT_DIR,"gaze_fac2_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                    
                    for i in range(1,gt.shape[1]):
                        # print(flow_invalid_mask.shape) #torch.Size([2, 4, 320, 320])
                        # print(FlowMap(gen1[:,i-1],flow[:,i-1]).shape) #torch.Size([2, 3, 320, 320])
                        warped[:,i-1] = FlowMap(gen1[:,i-1],flow[:,i-1]).mul(~flow_invalid_mask[:,i-1].unsqueeze(1).to("cuda:2"))
                        gen_temp[:,i-1] = gen1[:,i].mul(~flow_invalid_mask[:,i-1].unsqueeze(1).to("cuda:2"))
                else:
                    for k in range(image_set.shape[1]):
                        if k == 0:
                            lf_model.reset_hidden(image_set[:,k])
                        output = lf_model(image_set[:,k],df[:,k],gazeX[:,k],gazeY[:,k],posX[:,k],posY[:,k],posZ[:,k]) # batchsize, layer_num x 2 = 6, layer_res: 320, layer_res: 320
                        output1 = MergeBatchSpeed(output, gen, phi[:,k], phi_invalid[:,k], retinal_invalid[:,k])
                        gen1[:,k] = output1[:,0:3]
                        gt[:,k] = gt[:,k].mul_(~retinal_invalid[:,k].to("cuda:2"))

                        if k != image_set.shape[1]-1:
                            warped[:,k] = FlowMap(output1.detach(),flow[:,k]).mul(~flow_invalid_mask[:,k].unsqueeze(1).to("cuda:2"))
                        loss1 = loss_without_perc(output1,gt[:,k])
                        loss = (w_frame * loss1)
                        if k==0:
                            loss.backward(retain_graph=False)
                            optimizer.step()
                            lf_model.zero_grad()
                            optimizer.zero_grad()
                            print("Epoch:",epoch,",Iter:",batch_idx,",Seq:",k,",loss:",loss.item())
                        else:
                            output1mask = output1.mul(~flow_invalid_mask[:,k-1].unsqueeze(1).to("cuda:2"))
                            loss2 = l1loss(output1mask,warped[:,k-1])
                            loss += (w_inter_frame * loss2)
                            loss.backward(retain_graph=False)
                            optimizer.step()
                            lf_model.zero_grad()
                            optimizer.zero_grad()
                            # print("Epoch:",epoch,",Iter:",batch_idx,",Seq:",k,",loss:",loss.item())
                            print("Epoch:",epoch,",Iter:",batch_idx,",Seq:",k,",frame loss:",loss1.item(),",inter loss:",w_inter_frame * loss2.item())

                        
                        if ((epoch%10 == 0 and epoch != 0) or epoch == 2):
                            for i in range(output.shape[0]):
                                save_image(output[i][0:3].data,os.path.join(OUTPUT_DIR,"gaze_fac1_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                                save_image(output[i][3:6].data,os.path.join(OUTPUT_DIR,"gaze_fac2_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                    
                    # BSxSeq C H W
                    gen1 = gen1.reshape(-1,gen1.shape[2],gen1.shape[3],gen1.shape[4])
                    gt = gt.reshape(-1,gt.shape[2],gt.shape[3],gt.shape[4])
                    
                    if ((epoch%10== 0 and epoch != 0) or epoch == 2): # torch.Size([2, 5, 160, 160, 3])
                        for i in range(gt.size()[0]):
                            save_image(gen1[i].data,os.path.join(OUTPUT_DIR,"gaze_out1_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data,posX[i//5][i%5].data,posY[i//5][i%5].data)))
                            save_image(gt[i].data,os.path.join(OUTPUT_DIR,"gaze_test1_gt0_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data,posX[i//5][i%5].data,posY[i//5][i%5].data)))
                    if ((epoch%100 == 0) and epoch != 0 and batch_idx==len(train_data_loader)-1):
                        save_checkpoints(os.path.join(OUTPUT_DIR, 'gaze-ckpt-epoch-%04d.pth' % (epoch)),epoch,lf_model,optimizer)
            else:
                if batch_model != "Single":
                    for k in range(image_set.shape[1]):
                        output = lf_model(image_set[:,k],df[:,k],gazeX[:,k],gazeY[:,k],posX[:,k],posY[:,k],posZ[:,k]) # batchsize, layer_num x 2 = 6, layer_res: 320, layer_res: 320
                        output1 = MergeBatchSpeed(output, gen, phi[:,k], phi_invalid[:,k], retinal_invalid[:,k])
                        gen1[:,k] = output1[:,0:3]
                        gt[:,k] = gt[:,k].mul_(~retinal_invalid[:,k].to("cuda:2"))
                        
                        if ((epoch%10 == 0 and epoch != 0) or epoch == 2):
                            for i in range(output.shape[0]):
                                save_image(output[i][0:3].data,os.path.join(OUTPUT_DIR,"gaze_fac1_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                                save_image(output[i][3:6].data,os.path.join(OUTPUT_DIR,"gaze_fac2_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                    for i in range(1,gt.shape[1]):
                        # print(flow_invalid_mask.shape) #torch.Size([2, 4, 320, 320])
                        # print(FlowMap(gen1[:,i-1],flow[:,i-1]).shape) #torch.Size([2, 3, 320, 320])
                        warped[:,i-1] = FlowMap(gen1[:,i-1],flow[:,i-1]).mul(~flow_invalid_mask[:,i-1].unsqueeze(1).to("cuda:2"))
                        gen_temp[:,i-1] = gen1[:,i].mul(~flow_invalid_mask[:,i-1].unsqueeze(1).to("cuda:2"))
                else:
                    for k in range(image_set.shape[1]):
                        output = lf_model(image_set[:,k],df[:,k],gazeX[:,k],gazeY[:,k],posX[:,k],posY[:,k],posZ[:,k]) # batchsize, layer_num x 2 = 6, layer_res: 320, layer_res: 320
                        output1 = MergeBatchSpeed(output, gen, phi[:,k], phi_invalid[:,k], retinal_invalid[:,k])
                        gen1[:,k] = output1[:,0:3]
                        gt[:,k] = gt[:,k].mul_(~retinal_invalid[:,k].to("cuda:2"))
                        
                        # print(output1.shape) #torch.Size([BS, 3, 320, 320])
                        loss1 = loss_without_perc(output1,gt[:,k])
                        loss = (w_frame * loss1)
                        # print("loss:",loss1.item())
                        loss.backward(retain_graph=False)
                        optimizer.step()
                        lf_model.zero_grad()
                        optimizer.zero_grad()

                        print("Epoch:",epoch,",Iter:",batch_idx,",Seq:",k,",loss:",loss.item())
                        if ((epoch%10 == 0 and epoch != 0) or epoch == 2):
                            for i in range(output.shape[0]):
                                save_image(output[i][0:3].data,os.path.join(OUTPUT_DIR,"gaze_fac1_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                                save_image(output[i][3:6].data,os.path.join(OUTPUT_DIR,"gaze_fac2_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i][k].data,gazeX[i][k].data,gazeY[i][k].data,posX[i][k].data,posY[i][k].data)))
                    for i in range(1,gt.shape[1]):
                        warped[:,i-1] = FlowMap(gen1[:,i-1],flow[:,i-1]).mul(~flow_invalid_mask[:,i-1].unsqueeze(1).to("cuda:2"))
                        gen_temp[:,i-1] = gen1[:,i].mul(~flow_invalid_mask[:,i-1].unsqueeze(1).to("cuda:2"))

                    warped = warped.reshape(-1,warped.shape[2],warped.shape[3],warped.shape[4])
                    gen_temp = gen_temp.reshape(-1,gen_temp.shape[2],gen_temp.shape[3],gen_temp.shape[4])
                    loss3 = l1loss(warped,gen_temp)
                    print("Epoch:",epoch,",Iter:",batch_idx,",inter-frame loss:",w_inter_frame *loss3.item())
                    
                    # BSxSeq C H W
                    gen1 = gen1.reshape(-1,gen1.shape[2],gen1.shape[3],gen1.shape[4])
                    gt = gt.reshape(-1,gt.shape[2],gt.shape[3],gt.shape[4])
                    
                    if ((epoch%10== 0 and epoch != 0) or epoch == 2): # torch.Size([2, 5, 160, 160, 3])
                        for i in range(gt.size()[0]):
                            save_image(gen1[i].data,os.path.join(OUTPUT_DIR,"gaze_out1_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data,posX[i//5][i%5].data,posY[i//5][i%5].data)))
                            save_image(gt[i].data,os.path.join(OUTPUT_DIR,"gaze_test1_gt0_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data,posX[i//5][i%5].data,posY[i//5][i%5].data)))
                    if ((epoch%100 == 0) and epoch != 0 and batch_idx==len(train_data_loader)-1):
                        save_checkpoints(os.path.join(OUTPUT_DIR, 'gaze-ckpt-epoch-%04d.pth' % (epoch)),epoch,lf_model,optimizer)


            if batch_model != "Single":
                if mode=="Perf":
                    end.record()
                    torch.cuda.synchronize()
                    print("forward:",start.elapsed_time(end))

                    start.record()
                optimizer.zero_grad()
BobYeah's avatar
BobYeah committed
541
542

                
BobYeah's avatar
BobYeah committed
543
544
545
546
547
548
549
550
551
552
                # BSxSeq C H W
                gen1 = gen1.reshape(-1,gen1.shape[2],gen1.shape[3],gen1.shape[4])
                # gen2 = gen2.reshape(-1,gen2.shape[2],gen2.shape[3],gen2.shape[4])
                # BSxSeq C H W
                gt = gt.reshape(-1,gt.shape[2],gt.shape[3],gt.shape[4])
                # gt2 = gt2.reshape(-1,gt2.shape[2],gt2.shape[3],gt2.shape[4])

                # BSx(Seq-1) C H W
                warped = warped.reshape(-1,warped.shape[2],warped.shape[3],warped.shape[4])
                gen_temp = gen_temp.reshape(-1,gen_temp.shape[2],gen_temp.shape[3],gen_temp.shape[4])
BobYeah's avatar
BobYeah committed
553
                
BobYeah's avatar
BobYeah committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
                loss1_value = loss1(gen1,gt)
                loss2_value = loss2(warped,gen_temp)
                if model_type == "RNN": 
                    loss = (w_frame * loss1_value)+ (w_inter_frame * loss2_value)
                else:
                    loss = (w_frame * loss1_value)

                if mode=="Perf":
                    end.record()
                    torch.cuda.synchronize()
                    print("compute loss:",start.elapsed_time(end))

                    start.record()
                loss.backward()
                if mode=="Perf":
                    end.record()
                    torch.cuda.synchronize()
                    print("backward:",start.elapsed_time(end))

                    start.record()
                optimizer.step()
                if mode=="Perf":
                    end.record()
                    torch.cuda.synchronize()
                    print("update:",start.elapsed_time(end))

                print("Epoch:",epoch,",Iter:",batch_idx,",loss:",loss.item(),",frame loss:",loss1_value.item(),",inter-frame loss:",loss2_value.item())
                
                # exit(0)
                ########################### Save #####################
                if ((epoch%10== 0 and epoch != 0) or epoch == 2): # torch.Size([2, 5, 160, 160, 3])
                    for i in range(gt.size()[0]):
                        # df 2,5 
                        save_image(gen1[i].data,os.path.join(OUTPUT_DIR,"gaze_out1_o_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data,posX[i//5][i%5].data,posY[i//5][i%5].data)))
                        # save_image(gen2[i].data,os.path.join(OUTPUT_DIR,"gaze_out2_o_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data)))
                        save_image(gt[i].data,os.path.join(OUTPUT_DIR,"gaze_test1_gt0_%.5f_%.5f_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data,posX[i//5][i%5].data,posY[i//5][i%5].data)))
                        # save_image(gt2[i].data,os.path.join(OUTPUT_DIR,"gaze_test1_gt1_%.5f_%.5f_%.5f.png"%(df[i//5][i%5].data,gazeX[i//5][i%5].data,gazeY[i//5][i%5].data)))
                if ((epoch%100 == 0) and epoch != 0 and batch_idx==len(train_data_loader)-1):
                    save_checkpoints(os.path.join(OUTPUT_DIR, 'gaze-ckpt-epoch-%04d.pth' % (epoch)),epoch,lf_model,optimizer)