-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain_fuser.py
227 lines (175 loc) · 8.62 KB
/
train_fuser.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
import trimesh
import yaml
import torch
import spconv
import os
import numpy as np
from time import time
from tqdm import tqdm
from os.path import join
from easydict import EasyDict
from torch.utils.data import DataLoader
from skimage.measure import marching_cubes
from torch.utils.tensorboard import SummaryWriter
from geometry.depthPointCloud import DepthPointCloud
from module import constructChunksFromVolume, FusionIntegrator
from network import FusionLoss, GradLoss, Parser, Fuser, SignLoss
from dataset import ChunkDataset
if __name__ == "__main__":
# Read configuration
configFile = open("./configs/train_fuser.yaml", 'r')
config = EasyDict(yaml.safe_load(configFile))
print("- Train Fuser: ", config.comment)
# Setup CUDA device
useGPU = True if torch.cuda.is_available() else False
device = torch.device("cuda" if useGPU else "cpu")
torch.cuda.set_device(0)
# Dataset
trainDir = join(config.dataRoot, "train")
valDir = join(config.dataRoot, "val")
print("- Loading Train data ...")
dataset_train = ChunkDataset(dataDir=trainDir, device=device)
trainLoader = DataLoader(dataset_train, batch_size=config.batchSize, shuffle=True, num_workers=0)
print("- Loading Train data ...")
dataset_val = ChunkDataset(dataDir=valDir, device=device)
print("- Loading Train size: ", len(dataset_train))
if config.tensorboard:
writer = SummaryWriter(comment= '_' + config.comment)
# Setup network
if config.withParser:
parser = Parser().to(device)
fuser = Fuser().to(device)
# Setup network
if config.withParser and config.parserModel is not None:
print("- Loading pretrained parser weights: {}".format(config.parserModel))
preTrainWeights = torch.load(config.parserModel)
parser.load_state_dict(preTrainWeights)
# Setup criterion
criterion = FusionLoss(
w_l1=config.w_l1,
w_mse=config.w_mse,
w_sign=config.w_sign,
w_grad=config.w_grad,
reduction="mean"
).to(device)
mse = torch.nn.MSELoss(reduction="mean").to(device)
l1 = torch.nn.L1Loss(reduction="mean").to(device)
sign = SignLoss(reduction="mean").to(device)
grad = GradLoss(reduction="mean").to(device)
# Setup Optimizer
optimizer_fuser = torch.optim.RMSprop(
fuser.parameters(),
lr=config.lr_fuser,
alpha=config.optimizer.alpha,
eps=config.optimizer.eps,
momentum=config.optimizer.momentum,
weight_decay=config.optimizer.weight_decay
)
if config.lr_parser > 0 and config.withParser:
optimizer_parser = torch.optim.RMSprop(
parser.parameters(),
lr=config.lr_parser,
alpha=config.optimizer.alpha,
eps=config.optimizer.eps,
momentum=config.optimizer.momentum,
weight_decay=config.optimizer.weight_decay
)
scheduler = torch.optim.lr_scheduler.StepLR(
optimizer=optimizer_fuser,
step_size=config.scheduler.step_size,
gamma=config.scheduler.gamma
)
bestMSE = np.inf
globalStep = 0
timeStamp = str(time())
# Training
print("\n- Training")
print("- ", config.comment)
trainBeginTime = time()
for epoch in range(config.n_epochs):
lossStats = []
for batchCount, chunkData in tqdm(enumerate(trainLoader), desc="- Training, Epochs [{}/{}]: ".format(epoch+1, config.n_epochs), total=len(trainLoader)):
input = chunkData["input"].to(device)
gtTSDF = chunkData["gt"].to(device)
inputTSDF = input[:, 0, :].reshape((-1, 1, config.chunkSize, config.chunkSize, config.chunkSize))
localTSDF = input[:, 1, :].reshape((-1, 1, config.chunkSize, config.chunkSize, config.chunkSize))
gtTSDF = gtTSDF.reshape((-1, 1, config.chunkSize, config.chunkSize, config.chunkSize))
inputMask = torch.abs(inputTSDF) < 1
localMask = torch.abs(localTSDF) < 1
predictTSDF = fuser(inputTSDF, localTSDF)
if config.withParser:
predictTSDF = parser(predictTSDF)
else:
predictTSDF = spconv.ToDense()(predictTSDF) * 2 - 1
lossMask = torch.logical_or(inputMask, localMask)
loss = criterion(lossMask, predictTSDF, gtTSDF)
loss.backward()
# optimize loss
optimizer_fuser.step()
optimizer_fuser.zero_grad()
if config.lr_parser > 0 and config.withParser:
optimizer_parser.step()
optimizer_parser.zero_grad()
scheduler.step()
lossStats.append(loss.item())
tqdm.write("- Batch Loss: {}".format(loss.item()))
if config.tensorboard:
writer.add_scalar("loss/train_loss", loss.item(), global_step=globalStep)
globalStep += 1
# Evaluate
if batchCount % config.evaluateInterval == 0:
with torch.no_grad():
chunkData = dataset_val.getRandomBatch(config.batchSize)
input = chunkData["input"].to(device)
gtTSDF = chunkData["gt"].to(device)
inputTSDF = input[:, 0, :].reshape((-1, 1, config.chunkSize, config.chunkSize, config.chunkSize))
localTSDF = input[:, 1, :].reshape((-1, 1, config.chunkSize, config.chunkSize, config.chunkSize))
gtTSDF = gtTSDF.reshape((-1, 1, config.chunkSize, config.chunkSize, config.chunkSize))
inputMask = torch.abs(inputTSDF) < 1
localMask = torch.abs(localTSDF) < 1
predictTSDF = fuser(inputTSDF, localTSDF)
if config.withParser:
predictTSDF = parser(predictTSDF)
else:
predictTSDF = spconv.ToDense()(predictTSDF) * 2 - 1
inputMask = torch.abs(inputTSDF) < 1
localMask = torch.abs(localTSDF) < 1
lossMask = torch.logical_or(inputMask, localMask)
mseLoss = mse(predictTSDF[lossMask], gtTSDF[lossMask])
l1Loss = l1(predictTSDF[lossMask], gtTSDF[lossMask])
signLoss = sign(predictTSDF[lossMask], gtTSDF[lossMask])
gradLoss = grad(lossMask, predictTSDF, gtTSDF)
tqdm.write("\n- Val MSE: {}".format(mseLoss.item()))
# End of integrating model
if config.tensorboard:
writer.add_scalar("loss/val_mse", mseLoss.item(), global_step=globalStep)
writer.add_scalar("loss/val_l1", l1Loss.item(), global_step=globalStep)
writer.add_scalar("loss/val_grad", gradLoss.item(), global_step=globalStep)
writer.add_scalar("loss/val_sign", signLoss.item(), global_step=globalStep)
# Save best model
if mseLoss.item() < bestMSE:
bestMSE = mseLoss.item()
tqdm.write("- Saving best model.")
if not os.path.isdir(join("./checkpoints/", config.comment, timeStamp, "fuser")):
os.makedirs(join("./checkpoints/", config.comment, timeStamp, "fuser"))
if not os.path.isdir(join("./checkpoints/", config.comment, timeStamp, "parser")):
os.makedirs(join("./checkpoints/", config.comment, timeStamp, "parser"))
torch.save(fuser.state_dict(), join("./checkpoints/", config.comment, timeStamp, "fuser", "best_model.pth"))
if config.withParser:
torch.save(parser.state_dict(), join("./checkpoints/", config.comment, timeStamp, "parser", "best_model.pth"))
# End of each epochs
print("- End of Epoch.")
print("- Loss: {:.5f}".format(np.mean(lossStats)))
processingTime = time() - trainBeginTime
h = int(np.floor(processingTime / 3600))
m = int(np.floor((processingTime - h * 3600) / 60))
s = int(processingTime % 60)
print("- Total Processing Time: {:02d}:{:02d}:{:02d}".format(h, m, s))
print(" ")
# Checkpoint
if epoch % config.checkpoint == 0:
print("- Saving checkpoint.")
torch.save(fuser.state_dict(), join("./checkpoints", config.comment, timeStamp, "fuser", "epochs_{}.pth".format(epoch)))
if config.withParser:
torch.save(parser.state_dict(), join("./checkpoints", config.comment, timeStamp, "parser", "epochs_{}.pth".format(epoch)))
# End of epoch, single iteration of the model dataset