-
Notifications
You must be signed in to change notification settings - Fork 3
/
MoCoGAN ODE deep UCF101.py
156 lines (135 loc) · 5.9 KB
/
MoCoGAN ODE deep UCF101.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
import torch
import torch.nn as nn
import numpy as np
from skvideo import io
from ucf101.UCF101DatasetTGAN import UCF101, UCF101Images
from models.mocogan import VideoDiscriminator, PatchImageDiscriminator
from models.mocogan_ode import VideoGenerator, ODEFuncDeep
from evaluation_metrics import calculate_inception_score
from tqdm import tqdm
epochs = 100000
batch_size = 32
path = 'ucf101/mocogan_ode_deep'
start_epoch = 0
conf = "C:/Video Datasets/ucf101_64px/train.json"
dset = "C:/Video Datasets/ucf101_64px/train.h5"
def genSamples(g, n=8, e=1):
g.eval()
with torch.no_grad():
s = g.sample_videos(n**2)[0].cpu().detach().numpy()
g.train()
out = np.zeros((3, 16, 64*n, 64*n))
for j in range(n):
for k in range(n):
out[:, :, 64*j:64*(j+1), 64*k:64*(k+1)] = s[j*n + k, :, :, :, :]
out = out.transpose((1, 2, 3, 0))
out = (out + 1) / 2 * 255
io.vwrite(
f'video_samples/{path}/gensamples_id{e}.gif',
out
)
def train():
# data
videoDataset = UCF101(dset, conf)
imgDataset = UCF101Images(dset, conf)
videoLoader = torch.utils.data.DataLoader(videoDataset, batch_size=batch_size,
shuffle=True,
drop_last=True)
imgLoader = torch.utils.data.DataLoader(imgDataset, batch_size=batch_size,
shuffle=True,
drop_last=True)
def dataGen(loader):
while True:
for d in loader:
yield d
vidGen = dataGen(videoLoader)
imgGen = dataGen(imgLoader)
# gen model
disVid = VideoDiscriminator(3).cuda()
disImg = PatchImageDiscriminator(3).cuda()
gen = VideoGenerator(3, 50, 0, 16, 16, ode_fn=ODEFuncDeep, dim_hidden=16).cuda()
# init optimizers and loss
disVidOpt = torch.optim.Adam(disVid.parameters(), lr=2e-4, betas=(0.5, 0.999), weight_decay=1e-5)
disImgOpt = torch.optim.Adam(disImg.parameters(), lr=2e-4, betas=(0.5, 0.999), weight_decay=1e-5)
genOpt = torch.optim.Adam(gen.parameters(), lr=2e-4, betas=(0.5, 0.999), weight_decay=1e-5)
loss = nn.BCEWithLogitsLoss()
# resume training
state_dicts = torch.load(f'checkpoints/{path}/state_normal94000.ckpt')
start_epoch = state_dicts['epoch'] + 1
gen.load_state_dict(state_dicts['model_state_dict'][0])
disVid.load_state_dict(state_dicts['model_state_dict'][1])
disImg.load_state_dict(state_dicts['model_state_dict'][2])
genOpt.load_state_dict(state_dicts['optimizer_state_dict'][0])
disVidOpt.load_state_dict(state_dicts['optimizer_state_dict'][1])
disImgOpt.load_state_dict(state_dicts['optimizer_state_dict'][2])
# train
# isScores = []
isScores = list(np.load('epoch_is/mocogan_ode_deep_inception.npy'))
for epoch in tqdm(range(start_epoch, epochs)):
# image discriminator
disImgOpt.zero_grad()
real = next(imgGen).cuda()
pr, _ = disImg(real)
with torch.no_grad():
fake, _ = gen.sample_images(batch_size)
pf, _ = disImg(fake)
pr_labels = torch.ones_like(pr)
pf_labels = torch.zeros_like(pf)
dis_img_loss = loss(pr, pr_labels) + loss(pf, pf_labels)
dis_img_loss.backward()
disImgOpt.step()
# video discriminator
disVidOpt.zero_grad()
real = next(vidGen).cuda().transpose(1, 2)
pr, _ = disVid(real)
with torch.no_grad():
fake, _ = gen.sample_videos(batch_size)
pf, _ = disVid(fake)
pr_labels = torch.ones_like(pr)
pf_labels = torch.zeros_like(pf)
dis_vid_loss = loss(pr, pr_labels) + loss(pf, pf_labels)
dis_vid_loss.backward()
disVidOpt.step()
# generator
genOpt.zero_grad()
fakeVid, _ = gen.sample_videos(batch_size)
fakeImg, _ = gen.sample_images(batch_size)
pf_vid, _ = disVid(fakeVid)
pf_img, _ = disImg(fakeImg)
pf_vid_labels = torch.ones_like(pf_vid)
pf_img_labels = torch.ones_like(pf_img)
gen_loss = loss(pf_vid, pf_vid_labels) + loss(pf_img, pf_img_labels)
gen_loss.backward()
genOpt.step()
# print('Epoch', epoch, 'DisImg', dis_img_loss.item(), 'DisVid', dis_vid_loss.item(), 'Gen', gen_loss.item())
if epoch % 100 == 0:
genSamples(gen, e=epoch)
if epoch % 1000 == 0:
gen.cpu()
isScores.append(calculate_inception_score(gen, test=False,
moco=True))
print(isScores[-1])
np.save('epoch_is/mocogan_ode_deep_inception.npy', isScores)
gen.cuda()
torch.save({'epoch': epoch,
'model_state_dict': [gen.state_dict(),
disVid.state_dict(),
disImg.state_dict()],
'optimizer_state_dict': [genOpt.state_dict(),
disVidOpt.state_dict(),
disImgOpt.state_dict()]},
f'checkpoints/{path}/state_normal{epoch}.ckpt')
torch.save({'epoch': epoch,
'model_state_dict': [gen.state_dict(),
disVid.state_dict(),
disImg.state_dict()],
'optimizer_state_dict': [genOpt.state_dict(),
disVidOpt.state_dict(),
disImgOpt.state_dict()]},
f'checkpoints/{path}/state_normal{epoch}.ckpt')
isScores.append(calculate_inception_score(gen, test=False,
moco=True))
np.save('epoch_is/mocogan_ode_deep_inception.npy', isScores)
print(isScores[-1])
if __name__ == '__main__':
train()