-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlstm_homography_predictor_module.py
731 lines (604 loc) · 24 KB
/
lstm_homography_predictor_module.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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
541
542
543
544
545
546
547
548
549
550
551
552
553
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
import importlib
import os
from typing import Any, List, Optional, Tuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
from kornia.geometry import warp_perspective
from pytorch_lightning.utilities.types import STEP_OUTPUT
import lightning_modules
from utils.processing import (
TaylorHomographyPrediction,
differentiate_duv,
four_point_homography_to_matrix,
frame_pairs,
image_edges,
integrate_duv,
)
from utils.viz import (
create_blend_from_four_point_homography,
uv_trajectory_figure,
yt_alpha_blend,
)
class DuvLSTMModule(pl.LightningModule):
def __init__(
self,
lstm_hidden_size: int = 512,
lr: float = 1e-4,
betas: List[float] = [0.9, 0.999],
frame_stride: int = 1,
) -> None:
super().__init__()
self.save_hyperparameters("lr", "betas")
self._homography_regression = None
# load model
self._lstm = torch.nn.LSTM(
input_size=8, hidden_size=lstm_hidden_size, num_layers=1
)
# fully connected for future duv prediction
self._fc = torch.nn.Linear(in_features=lstm_hidden_size, out_features=8) # duv
self._model = torch.nn.ModuleDict(
{"lstm": self._lstm, "fc": self._fc} # forward duv
)
self._distance_loss = nn.PairwiseDistance()
self.lr = lr
self._betas = betas
self._val_logged = False
self._frame_stride = frame_stride
def inject_homography_regression(
self, homography_regression: dict, homography_regression_prefix: str
):
# load trained homography regression model
self._homography_regression = getattr(
lightning_modules, homography_regression["lightning_module"]
).load_from_checkpoint(
checkpoint_path=os.path.join(
homography_regression_prefix,
homography_regression["path"],
homography_regression["checkpoint"],
),
**homography_regression["model"]
)
self._homography_regression = self._homography_regression.eval()
self._homography_regression.freeze()
def on_train_epoch_start(self) -> None:
self._homography_regression = self._homography_regression.eval()
self._homography_regression.freeze()
def configure_optimizers(self):
optimizer = torch.optim.Adam(
self._model.parameters(), lr=self.lr, betas=self._betas
)
return optimizer
def forward(self, duvs) -> Any:
duvs = duvs.permute(1, 0, 2, 3) # BxTx4x2 -> TxBx4x2
duvs = duvs.view(duvs.shape[:2] + (-1,)) # TxBx4x2 -> TxBx8
duvs_pred, (hn, cn) = self._lstm(
duvs
) # duvs_pred gives access to all hidden states in the sequence
duvs_pred = self._fc(duvs_pred)
duvs_pred = duvs_pred.view(
duvs_pred.shape[:2]
+ (
4,
2,
)
) # TxBx8 -> TxBx4x2
duvs_pred = duvs_pred.permute(1, 0, 2, 3) # TxBx4x2 -> BxTx4x2
return duvs_pred
def training_step(self, batch, batch_idx) -> STEP_OUTPUT:
if self._homography_regression is None:
raise ValueError("Homography regression model required in training step.")
videos, transformed_videos, frame_idcs, vid_idcs = batch
videos, transformed_videos = (
videos.float() / 255.0,
transformed_videos.float() / 255.0,
)
frames_i, frames_ips = frame_pairs(videos, self._frame_stride) # re-sort images
frames_i = frames_i.reshape(
(-1,) + frames_i.shape[-3:]
) # reshape BxNxCxHxW -> B*NxCxHxW
frames_ips = frames_ips.reshape(
(-1,) + frames_ips.shape[-3:]
) # reshape BxNxCxHxW -> B*NxCxHxW
with torch.no_grad():
duvs_reg = self._homography_regression(frames_i, frames_ips)
duvs_reg = duvs_reg.view(videos.shape[0], -1, 4, 2) # BxTx4x2
# forward
duvs_pred = self(duvs_reg[:, :-1])
# compute distance loss
distance_loss = self._distance_loss(
duvs_pred.reshape(-1, 2),
duvs_reg[:, 1:].reshape(-1, 2), # note that the first value is skipped
).mean()
self.log("train/distance", distance_loss)
return distance_loss
def validation_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
if self._homography_regression is None:
raise ValueError("Homography regression model required in training step.")
# by default without grad (torch.set_grad_enabled(False))
videos, transformed_videos, frame_idcs, vid_idcs = batch
videos, transformed_videos = (
videos.float() / 255.0,
transformed_videos.float() / 255.0,
)
frames_i, frames_ips = frame_pairs(videos, self._frame_stride) # re-sort images
frames_i = frames_i.reshape(
(-1,) + frames_i.shape[-3:]
) # reshape BxNxCxHxW -> B*NxCxHxW
frames_ips = frames_ips.reshape(
(-1,) + frames_ips.shape[-3:]
) # reshape BxNxCxHxW -> B*NxCxHxW
duvs_reg = self._homography_regression(frames_i, frames_ips)
duvs_reg = duvs_reg.view(videos.shape[0], -1, 4, 2) # BxTx4x2
# forward
duvs_pred = self(duvs_reg[:, :-1])
# compute distance loss
distance_loss = self._distance_loss(
duvs_pred.reshape(-1, 2),
duvs_reg[:, 1:].reshape(-1, 2), # note that the first value is skipped
).mean()
# logging
if not self._val_logged:
self._val_logged = True
frames_i = frames_i.view(
videos.shape[0], -1, 3, videos.shape[-2], videos.shape[-1]
) # reshape B*NxCxHxW -> BxNxCxHxW
frames_ips = frames_ips.view(
videos.shape[0], -1, 3, videos.shape[-2], videos.shape[-1]
) # reshape B*NxCxHxW -> BxNxCxHxW
# visualize sequence N in zeroth batch
blends = create_blend_from_four_point_homography(
frames_i[0], frames_ips[0], duvs_reg[0]
)
self.logger.experiment.add_images("val/blend", blends, self.global_step)
uv = image_edges(frames_i[0, 0].unsqueeze(0))
uv_reg = integrate_duv(
uv, duvs_reg[0, 1:]
) # batch 0, note that first value is skipped
uv_pred = integrate_duv(uv, duvs_pred[0]) # batch 0
uv_traj_fig = uv_trajectory_figure(
uv_reg.cpu().numpy(), uv_pred.detach().cpu().numpy()
)
self.logger.experiment.add_figure(
"val/uv_traj_fig", uv_traj_fig, self.global_step
)
self.log("val/distance", distance_loss)
def on_validation_epoch_end(self) -> None:
self._val_logged = False
return super().on_validation_epoch_end()
def test_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
pass
def _create_blend_from_homography_regression(
self, frames_i: torch.Tensor, frames_ips: torch.Tensor, duvs: torch.Tensor
):
r"""Helper function that creates blend figure, given four point homgraphy representation.
Args:
frames_i (torch.Tensor): Frames i of shape NxCxHxW
frames_ips (torch.Tensor): Frames i+step of shape NxCxHxW
duvs (torch.Tensor): Edge delta from frames i+step to frames i of shape Nx4x2
Return:
blends (torch.Tensor): Blends of warp(frames_i) and frames_ips
"""
uvs = image_edges(frames_i)
Hs = four_point_homography_to_matrix(uvs, duvs)
try: # handle inversion error
wrps = warp_perspective(frames_i, torch.inverse(Hs), frames_i.shape[-2:])
blends = yt_alpha_blend(frames_ips, wrps)
except:
return frames_i
return blends
class LSTMModule(pl.LightningModule):
def __init__(
self,
lstm_hidden_size: int = 512,
lr: float = 1e-4,
betas: List[float] = [0.9, 0.999],
frame_stride: int = 1,
) -> None:
super().__init__()
self.save_hyperparameters("lr", "betas")
# load model
self._lstm = torch.nn.LSTM(
input_size=8,
hidden_size=lstm_hidden_size,
num_layers=1,
)
# fully connected for future duv prediction
self._fc = torch.nn.Linear(in_features=lstm_hidden_size, out_features=8) # duv
self._model = torch.nn.ModuleDict(
{"lstm": self._lstm, "fc": self._fc} # forward duv
)
self._distance_loss = nn.PairwiseDistance()
self.lr = lr
self._betas = betas
self._val_logged = False
self._frame_stride = frame_stride
def configure_optimizers(self):
optimizer = torch.optim.Adam(
self._model.parameters(), lr=self.lr, betas=self._betas
)
return optimizer
def forward(self, duvs_i) -> Any:
duvs_i = duvs_i.permute(1, 0, 2, 3) # BxTx4x2 -> TxBx4x2
dduvs_i = differentiate_duv(duvs_i, False)
dduvs_i = dduvs_i.view(dduvs_i.shape[:2] + (-1,)) # (T-1)xBx4x2 -> (T-1)xBx8
dduvs_ip1, (hn, cn) = self._lstm(
dduvs_i
) # dduvs_p1 gives access to all hidden states in the sequence
dduvs_ip1 = self._fc(dduvs_ip1)
dduvs_ip1 = dduvs_ip1.view(
dduvs_ip1.shape[:2]
+ (
4,
2,
)
) # (T-1)xBx8 -> (T-1)xBx4x2
dduvs_ip1 = dduvs_ip1.permute(1, 0, 2, 3) # (T-1)xBx4x2 -> Bx(T-1)x4x2
duvs_i = duvs_i.permute(1, 0, 2, 3) # TxBx4x2 -> BxTx4x2
duvs_ip1 = duvs_i[:, 1:]
duvs_ip2 = duvs_ip1 + dduvs_ip1
return duvs_ip2
def training_step(self, batch, batch_idx) -> STEP_OUTPUT:
duvs_reg, frame_idcs, vid_idcs = batch
duvs_reg = duvs_reg.float()
# forward
duvs_ip2 = self(duvs_reg) # Bx(T-1)x4x2
# compute distance loss
distance_loss = self._distance_loss(
duvs_ip2[:, :-1].reshape(
-1, 2
), # we don't have ground truth for the last value in the sequence
duvs_reg[:, 2:].reshape(
-1, 2
), # note that the first two values are skipped
)
self.log("train/distance", distance_loss.mean())
return {
"loss": distance_loss.mean(),
"per_sequence_loss": distance_loss.detach()
.view(duvs_ip2.shape[0], -1)
.mean(axis=-1)
.cpu()
.numpy(),
}
def validation_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
img_seq, duvs_reg, frame_idcs, vid_idcs = batch
img_seq = img_seq.float() / 255.0
duvs_reg = duvs_reg.float()
# forward
duvs_ip2 = self(duvs_reg) # Bx(T-1)x4x2
# compute distance loss
distance_loss = self._distance_loss(
duvs_ip2[:, :-1].reshape(
-1, 2
), # we don't have ground truth for the last value in the sequence
duvs_reg[:, 2:].reshape(
-1, 2
), # note that the first two values are skipped
)
# # logging
if not self._val_logged:
self._val_logged = True
frames_i, frames_ips = frame_pairs(
img_seq, self._frame_stride
) # re-sort images
# visualize sequence N in zeroth batch
blends = create_blend_from_four_point_homography(
frames_i[0], frames_ips[0], duvs_reg[0, :-1]
)
self.logger.experiment.add_images("val/blend", blends, self.global_step)
uv = image_edges(frames_i[0, 0].unsqueeze(0))
uv_reg = integrate_duv(
uv, duvs_reg[0, 1:]
) # batch 0, note that first value is skipped
uv_pred = integrate_duv(uv, duvs_ip2[0]) # batch 0
uv_traj_fig = uv_trajectory_figure(
uv_reg.cpu().numpy(), uv_pred.detach().cpu().numpy()
)
self.logger.experiment.add_figure(
"val/uv_traj_fig", uv_traj_fig, self.global_step
)
self.log("val/distance", distance_loss.mean())
def on_validation_epoch_end(self) -> None:
self._val_logged = False
return super().on_validation_epoch_end()
def test_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
pass
class FeatureLSTMIncrementalModule(pl.LightningModule):
def __init__(
self,
encoder: dict,
lstm: dict,
head: List[dict],
optimizer: dict,
loss: dict,
frame_stride: int = 1,
) -> None:
super().__init__()
self._encoder = getattr(
importlib.import_module(encoder["module"]), encoder["name"]
)(**encoder["kwargs"])
self._lstm = getattr(importlib.import_module(lstm["module"]), lstm["name"])(
**lstm["kwargs"]
)
modules = []
for module in head:
modules.append(
getattr(importlib.import_module(module["module"]), module["name"])(
**module["kwargs"]
)
)
self._head = torch.nn.Sequential(*modules)
self._optimizer = getattr(
importlib.import_module(optimizer["module"]), optimizer["name"]
)(params=self.parameters(), **optimizer["kwargs"])
self._loss = getattr(importlib.import_module(loss["module"]), loss["name"])(
**loss["kwargs"]
)
self._sign = 1.
if isinstance(self._loss, torch.nn.CosineSimilarity):
self._sign = -1.
self._val_logged = False
self._frame_stride = frame_stride
self._taylor = TaylorHomographyPrediction(
order=1
) # comparing against simple linear model
def inject_homography_regression(
self, homography_regression: dict, homography_regression_prefix: str
):
raise RuntimeError("Currently not supported.")
def forward(
self,
imgs_ip1: torch.Tensor,
duvs_i: torch.Tensor,
dduvs_im1: torch.Tensor,
hx: Tuple[torch.Tensor, torch.Tensor] = None,
) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
# for indices, see https://drive.google.com/file/d/1T1HV01G0bzM_xAavhefhGgsOHGRQmCGw/view?usp=share_link
B, T, C, H, W = imgs_ip1.shape
# forward videos into latent space
imgs_ip1 = imgs_ip1.reshape(-1, C, H, W) # BxTxCxHxW -> B*TxCxHxW
f_ip1 = self._encoder(imgs_ip1)
f_ip1 = f_ip1.view(B, T, -1) # B*TxF -> BxTxF, where F = features
f_ip1 = f_ip1.permute(1, 0, 2) # BxTxF -> TxBxF
# prepare dduv
dduvs_im1 = dduvs_im1.view(B, T, -1) # BxTx4x2 -> BxTx8
dduvs_im1 = dduvs_im1.permute(1, 0, 2) # BxTx8 -> TxBx8
# lstm and head
f_ip1 = torch.concat([f_ip1, dduvs_im1], axis=-1)
dduvs_i, hx = self._lstm(f_ip1, hx)
dduvs_i = self._head(dduvs_i)
dduvs_i = dduvs_i.view(T, B, 4, 2) # TxBx8 -> TxBx4x2
dduvs_i = dduvs_i.permute(1, 0, 2, 3) # TxBx4x2 -> BxTx4x2
duvs_ip1 = duvs_i + dduvs_i
return duvs_ip1, hx
def configure_optimizers(self) -> Any:
return self._optimizer
def training_step(self, batch, batch_idx) -> STEP_OUTPUT:
(
tf_imgs,
duvs_reg,
frame_idcs,
vid_idcs,
) = batch # transformed images and four point homography
tf_imgs = tf_imgs.float() / 255.0
duvs_reg = duvs_reg.float()
# forward model
dduvs_reg = differentiate_duv(duvs_reg, True) # Bx(T-1)x4x2
duvs_ip1, _ = self(tf_imgs[:, 2:], duvs_reg[:, 1:-1], dduvs_reg[:, :-1])
# compute loss
loss = self._sign*self._loss(
duvs_ip1.reshape(-1, 2),
duvs_reg[:, 2:].reshape(
-1, 2
), # note that the first two values are skipped
)
self.log("train/loss", loss.mean())
return {
"loss": loss.mean(),
"per_sequence_loss": loss.detach()
.view(duvs_ip1.shape[0], -1)
.mean(axis=-1)
.cpu()
.numpy(),
}
def validation_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
(
tf_imgs,
duvs_reg,
frame_idcs,
vid_idcs,
) = batch # transformed images and four point homography
tf_imgs = tf_imgs.float() / 255.0
duvs_reg = duvs_reg.float()
# forward model
dduvs_reg = differentiate_duv(duvs_reg, True) # Bx(T-1)x4x2
duvs_ip1, _ = self(tf_imgs[:, 2:], duvs_reg[:, 1:-1], dduvs_reg[:, :-1])
# compute loss
loss = self._sign*self._loss(
duvs_ip1.reshape(-1, 2),
duvs_reg[:, 2:].reshape(
-1, 2
), # note that the first two values are skipped
)
self.log("val/loss", loss.mean())
if not self._val_logged:
self._val_logged = True
frames_i, frames_ips = frame_pairs(
tf_imgs, self._frame_stride
) # re-sort images
# visualize sequence N in zeroth batch
blends = create_blend_from_four_point_homography(
frames_i[0], frames_ips[0], duvs_reg[0, :-1]
)
self.logger.experiment.add_images("val/blend", blends, self.global_step)
uv = image_edges(frames_i[0, 0].unsqueeze(0))
uv_reg = integrate_duv(
uv, duvs_reg[0, 1:]
) # batch 0, note that first value is skipped
uv_pred = integrate_duv(uv, duvs_ip1[0]) # batch 0
uv_traj_fig = uv_trajectory_figure(
uv_reg.cpu().numpy(), uv_pred.detach().cpu().numpy()
)
self.logger.experiment.add_figure(
"val/uv_traj_fig", uv_traj_fig, self.global_step
)
# classical estimation
duvs_ip1_taylor = self._taylor(duvs_reg.cpu())[:, 1:]
# compute loss
loss_taylor = self._sign*self._loss(
duvs_ip1_taylor.reshape(
-1, 2
), # we don't have ground truth for the last value in the sequence
duvs_reg[:, 2:]
.cpu()
.reshape(-1, 2), # note that the first two values are skipped
)
self.log("val/loss_taylor", loss_taylor.mean())
self.log("val/taylor_loss_minus_loss", loss_taylor.mean() - loss.mean())
def on_validation_epoch_end(self) -> None:
self._val_logged = False
return super().on_validation_epoch_end()
def test_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
pass
class FeatureLSTMModule(pl.LightningModule):
def __init__(
self,
encoder: dict,
lstm: dict,
head: List[dict],
optimizer: dict,
loss: dict,
frame_stride: int = 1,
) -> None:
super().__init__()
self._encoder = getattr(
importlib.import_module(encoder["module"]), encoder["name"]
)(**encoder["kwargs"])
self._lstm = getattr(importlib.import_module(lstm["module"]), lstm["name"])(
**lstm["kwargs"]
)
modules = []
for module in head:
modules.append(
getattr(importlib.import_module(module["module"]), module["name"])(
**module["kwargs"]
)
)
self._head = torch.nn.Sequential(*modules)
self._optimizer = getattr(
importlib.import_module(optimizer["module"]), optimizer["name"]
)(params=self.parameters(), **optimizer["kwargs"])
self._loss = getattr(importlib.import_module(loss["module"]), loss["name"])(
**loss["kwargs"]
)
self._sign = 1.
if isinstance(self._loss, torch.nn.CosineSimilarity):
self._sign = -1.
self._val_logged = False
self._frame_stride = frame_stride
self._taylor = TaylorHomographyPrediction(
order=1
) # comparing against simple linear model
def inject_homography_regression(
self, homography_regression: dict, homography_regression_prefix: str
):
raise RuntimeError("Currently not supported.")
def forward(
self,
imgs: torch.Tensor,
hx: Tuple[torch.Tensor, torch.Tensor] = None,
) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
B, T, C, H, W = imgs.shape
# forward videos into latent space
imgs = imgs.reshape(-1, C, H, W) # BxTxCxHxW -> B*TxCxHxW
f = self._encoder(imgs)
f = f.view(B, T, -1) # B*TxF -> BxTxF, where F = features
f = f.permute(1, 0, 2) # BxTxF -> TxBxF
# lstm and head
duvs, hx = self._lstm(f, hx)
duvs = self._head(duvs)
duvs = duvs.view(T, B, 4, 2) # TxBx8 -> TxBx4x2
duvs = duvs.permute(1, 0, 2, 3) # TxBx4x2 -> BxTx4x2
return duvs, hx
def configure_optimizers(self) -> Any:
return self._optimizer
def training_step(self, batch, batch_idx) -> STEP_OUTPUT:
(
tf_imgs,
duvs_reg,
frame_idcs,
vid_idcs,
) = batch # transformed images and four point homography
tf_imgs = tf_imgs.float() / 255.0
duvs_reg = duvs_reg.float()
# forward model
duvs, _ = self(tf_imgs)
# compute loss
loss = self._sign*self._loss(
duvs.reshape(-1, 2),
duvs_reg.reshape(-1, 2),
)
self.log("train/loss", loss.mean())
return {
"loss": loss.mean(),
"per_sequence_loss": loss.detach()
.view(duvs.shape[0], -1)
.mean(axis=-1)
.cpu()
.numpy(),
}
def validation_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
(
tf_imgs,
duvs_reg,
frame_idcs,
vid_idcs,
) = batch # transformed images and four point homography
tf_imgs = tf_imgs.float() / 255.0
duvs_reg = duvs_reg.float()
# forward model
duvs, _ = self(tf_imgs)
# compute loss
loss = self._sign*self._loss(
duvs.reshape(-1, 2),
duvs_reg.reshape(-1, 2),
)
self.log("val/loss", loss.mean(), sync_dist=True)
# if not self._val_logged:
# self._val_logged = True
# frames_i, frames_ips = frame_pairs(
# tf_imgs, self._frame_stride
# ) # re-sort images
# # visualize sequence N in zeroth batch
# blends = create_blend_from_four_point_homography(
# frames_i[0], frames_ips[0], duvs_reg[0, :-1]
# )
# self.logger.experiment.add_images("val/blend", blends, self.global_step)
# uv = image_edges(frames_i[0, 0].unsqueeze(0))
# uv_reg = integrate_duv(uv, duvs_reg[0]) # batch 0
# uv_pred = integrate_duv(uv, duvs[0]) # batch 0
# uv_traj_fig = uv_trajectory_figure(
# uv_reg.cpu().numpy(), uv_pred.detach().cpu().numpy()
# )
# self.logger.experiment.add_figure(
# "val/uv_traj_fig", uv_traj_fig, self.global_step
# )
# classical estimation
duvs_taylor = self._taylor(duvs_reg.cpu())
# compute loss
loss_taylor = self._sign*self._loss(
duvs_taylor.reshape(
-1, 2
), # we don't have ground truth for the last value in the sequence
duvs_reg[:, self._taylor._order :]
.cpu()
.reshape(-1, 2), # note that the first two values are skipped
)
self.log("val/loss_taylor", loss_taylor.mean(), sync_dist=True)
self.log("val/taylor_loss_minus_loss", loss_taylor.mean() - loss.mean(), sync_dist=True)
def on_validation_epoch_end(self) -> None:
self._val_logged = False
return super().on_validation_epoch_end()
def test_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]:
pass