-
Notifications
You must be signed in to change notification settings - Fork 0
/
clifford.py
1167 lines (940 loc) · 46.7 KB
/
clifford.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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#================================================================================================================================
#== 'CliffPhys: Camera-based Respiratory Measurement using Clifford Neural Networks' (Paper ID #11393) ==
#================================================================================================================================
"""
Code containing functions and classes for the definition of the CliffPhys family of prediction models.
CLIFFORD:
This script contains utility functions and classes for the definition of the CLI.
It includes implementations of the Clifford product for different algebra signatures (Clifford kernels),
the implementation of the Linear and 2D, 3D convolutional Clifford layers.
It also provides the Negative Pearson loss implementation and the Processor() class to use any CliffPhys model in prediction mode.
It provides the implementation of each model in the CliffPhys family, 4 models working using depth information, 4 depth-lacking models.
MODELS: training version choices:
'CliffPhys02_d' 'CliffPhys02' 'PT-scamps_XYZ_FT-cohface_XYZ'
'CliffPhys03_d' 'CliffPhys03'
'CliffPhys30_d' 'CliffPhys30'
'CliffPhys20_d' 'CliffPhys20'
"""
import os
import numpy as np
import torch
import torch.nn as nn
import os
import numpy as np
import math
import torch.nn.functional as F
from torch.nn.modules.utils import _pair, _triple
from typing import Callable, Optional, Tuple, Union
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class Neg_Pearson(nn.Module):
"""
Custom PyTorch module to compute the negative Pearson correlation coefficient loss.
Attributes:
None
"""
def __init__(self):
super(Neg_Pearson, self).__init__()
return
def forward(self, preds, labels):
cos = nn.CosineSimilarity(dim=0, eps=1e-6)
pearson = cos(preds - preds.mean(dim=0, keepdim=True), labels - labels.mean(dim=0, keepdim=True))
return torch.mean(1 - pearson)
def _w_assert(w: Union[tuple, list, torch.Tensor, nn.Parameter, nn.ParameterList]) -> torch.Tensor:
"""Convert Clifford weights to tensor .
Args:
w (Union[tuple, list, torch.Tensor, nn.Parameter, nn.ParameterList]): Clifford weights.
Raises:
ValueError: Unknown weight type.
Returns:
torch.Tensor: Clifford weights as torch.Tensor.
"""
if type(w) in (tuple, list):
w = torch.stack(w)
return w
elif isinstance(w, torch.Tensor):
return w
elif isinstance(w, nn.Parameter):
return w
elif isinstance(w, nn.ParameterList):
return w
else:
raise ValueError("Unknown weight type.")
class CliffordSignature:
def __init__(self, g: Union[tuple, list, torch.Tensor]):
super().__init__()
self.g = self._g_tensor(g)
self.dim = self.g.numel()
if self.dim == 1:
self.n_blades = 2
elif self.dim == 2:
self.n_blades = 4
elif self.dim == 3:
self.n_blades = 8
else:
raise NotImplementedError("Wrong Clifford signature.")
def _g_tensor(self, g: Union[tuple, list, torch.Tensor]) -> torch.Tensor:
"""Convert Clifford signature to tensor.
Args:
g (Union[tuple, list, torch.Tensor]): Clifford signature.
Raises:
ValueError: Unknown metric.
Returns:
torch.Tensor: Clifford signature as torch.Tensor.
"""
if type(g) in (tuple, list):
g = torch.as_tensor(g, dtype=torch.float32)
elif isinstance(g, torch.Tensor):
pass
else:
raise ValueError("Unknown signature.")
if not torch.any(abs(g) == 1.0):
raise ValueError("Clifford signature should have at least one element as 1.")
return g
def get_2d_clifford_kernel(
w: Union[tuple, list, torch.Tensor, nn.Parameter, nn.ParameterList], g: torch.Tensor
) -> Tuple[int, torch.Tensor]:
"""Clifford kernel for 2d Clifford algebras, g = [-1, -1] corresponds to a quaternion kernel.
Args:
w (Union[tuple, list, torch.Tensor, nn.Parameter, nn.ParameterList]): Weight input of shape `(4, d~input~, d~output~, ...)`.
g (torch.Tensor): Signature of Clifford algebra.
Raises:
ValueError: Wrong encoding/decoding options provided.
Returns:
(Tuple[int, torch.Tensor]): Number of output blades, weight output of shape `(d~output~ * 4, d~input~ * 4, ...)`.
"""
assert isinstance(g, torch.Tensor)
assert g.numel() == 2
w = _w_assert(w)
assert len(w) == 4
k0 = torch.cat([w[0], g[0] * w[1], g[1] * w[2], -g[0] * g[1] * w[3]], dim=1)
k1 = torch.cat([w[1], w[0], -g[1] * w[3], g[1] * w[2]], dim=1)
k2 = torch.cat([w[2], g[0] * w[3], w[0], -g[0] * w[1]], dim=1)
k3 = torch.cat([w[3], w[2], -w[1], w[0]], dim=1)
k = torch.cat([k0, k1, k2, k3], dim=0)
return 4, k
def get_3d_clifford_kernel(
w: Union[tuple, list, torch.Tensor, nn.Parameter, nn.ParameterList], g: torch.Tensor
) -> Tuple[int, torch.Tensor]:
"""Clifford kernel for 3d Clifford algebras, g = [-1, -1, -1] corresponds to an octonion kernel.
Args:
w (Union[tuple, list, torch.Tensor, nn.Parameter, nn.ParameterList]): Weight input of shape `(8, d~input~, d~output~, ...)`.
g (torch.Tensor): Signature of Clifford algebra.
Raises:
ValueError: Wrong encoding/decoding options provided.
Returns:
(Tuple[int, torch.Tensor]): Number of output blades, weight output of dimension `(d~output~ * 8, d~input~ * 8, ...)`.
"""
assert isinstance(g, torch.Tensor)
assert g.numel() == 3
w = _w_assert(w)
assert len(w) == 8
k0 = torch.cat([w[0], w[1] * g[0], w[2] * g[1], w[3] * g[2], -w[4] * g[0] * g[1], -w[5] * g[0] * g[2], -w[6] * g[1] * g[2], -w[7] * g[0] * g[1] * g[2],], dim=1,)
k1 = torch.cat([w[1], w[0], -w[4] * g[1], -w[5] * g[2], w[2] * g[1], w[3] * g[2], -w[7] * g[1] * g[2], -w[6] * g[2] * g[1]], dim=1,)
k2 = torch.cat([w[2], w[4] * g[0], w[0], -w[6] * g[2], -w[1] * g[0], w[7] * g[0] * g[2], w[3] * g[2], w[5] * g[2] * g[0]], dim=1,)
k3 = torch.cat([w[3], w[5] * g[0], w[6] * g[1], w[0], -w[7] * g[0] * g[1], -w[1] * g[0], -w[2] * g[1], -w[4] * g[0] * g[1]], dim=1,)
k4 = torch.cat([w[4], w[2], -w[1], g[2] * w[7], w[0], -w[6] * g[2], w[5] * g[2], w[3] * g[2]], dim=1)
k5 = torch.cat([w[5], w[3], -w[7] * g[1], -w[1], w[6] * g[1], w[0], -w[4] * g[1], -w[2] * g[1]], dim=1)
k6 = torch.cat([w[6], w[7] * g[0], w[3], -w[2], -w[5] * g[0], w[4] * g[0], w[0], w[1] * g[0]], dim=1)
k7 = torch.cat([w[7], w[6], -w[5], w[4], w[3], -w[2], w[1], w[0]], dim=1)
k = torch.cat([k0, k1, k2, k3, k4, k5, k6, k7], dim=0)
return 8, k
def clifford_convnd(conv_fn: Callable, x: torch.Tensor, output_blades: int, weight: torch.Tensor, bias: Optional[torch.Tensor] = None, **kwargs,
) -> torch.Tensor:
"""Apply a Clifford convolution to a tensor.
Args:
conv_fn (Callable): The convolution function to use.
x (torch.Tensor): Input tensor.
output_blades (int): The output blades of the Clifford algebra.
Different from the default n_blades when using encoding and decoding layers.
weight (torch.Tensor): Weight tensor.
bias (torch.Tensor, optional): Bias tensor. Defaults to None.
Returns:
torch.Tensor: Convolved output tensor.
"""
# Reshape x such that the convolution function can be applied.
#print('x shape: '+str(x.shape))
B, *_ = x.shape
B_dim, C_dim, *D_dims, I_dim = range(len(x.shape))
x = x.permute(B_dim, -1, C_dim, *D_dims)
x = x.reshape(B, -1, *x.shape[3:])
# Apply convolution function
output = conv_fn(x, weight, bias=bias, **kwargs)
#print('\n weights shape: '+str(weight.shape))
# Reshape back.
output = output.view(B, output_blades, -1, *output.shape[2:])
B_dim, I_dim, C_dim, *D_dims = range(len(output.shape))
output = output.permute(B_dim, C_dim, *D_dims, I_dim)
return output
class _CliffordConvNd(nn.Module):
"""Base class for all Clifford convolution modules."""
def __init__(self, g: Union[tuple, list, torch.Tensor], in_channels: int, out_channels: int, kernel_size: int, stride: int,
padding: int, dilation: int, groups: int, bias: bool, padding_mode: str, rotation: bool = False, ) -> None:
super().__init__()
sig = CliffordSignature(g)
# register as buffer as we want the tensor to be moved to the same device as the module
self.register_buffer("g", sig.g)
self.dim = sig.dim
self.n_blades = sig.n_blades
if rotation:
assert (
self.dim == 2
), "2d rotational Clifford layers are only available for g = [-1, -1]. Make sure you have the right signature."
if self.dim == 2:
self._get_kernel = get_2d_clifford_kernel
elif self.dim == 3:
self._get_kernel = get_3d_clifford_kernel
else:
raise NotImplementedError(
f"Clifford convolution not implemented for {self.dim} dimensions. Wrong Clifford signature."
)
if padding_mode != "zeros":
raise NotImplementedError(f"Padding mode {padding_mode} not implemented.")
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.padding_mode = padding_mode
self.rotation = rotation
self.weight = nn.ParameterList(
[nn.Parameter(torch.empty(out_channels, in_channels // groups, *kernel_size)) for _ in range(self.n_blades)]
)
if bias:
self.bias = nn.Parameter(torch.empty(self.n_blades, out_channels))
else:
self.register_parameter("bias", None)
if rotation:
self.scale_param = nn.Parameter(torch.Tensor(self.weight[0].shape))
self.zero_kernel = nn.Parameter(torch.zeros(self.weight[0].shape), requires_grad=False)
self.weight.append(self.scale_param)
self.weight.append(self.zero_kernel)
self.reset_parameters()
def reset_parameters(self):
"""Initialization of the Clifford convolution weight and bias tensors.
The number of blades is taken into account when calculated the bounds of Kaiming uniform.
"""
for blade, w in enumerate(self.weight):
# Weight initialization for Clifford weights.
if blade < self.n_blades:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(
torch.Tensor(
self.out_channels, int(self.in_channels * self.n_blades / self.groups), *self.kernel_size
)
)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(w, -bound, bound)
# Extra weights for 2d Clifford rotation layer.
elif blade == self.n_blades:
assert self.rotation is True
# Default channel_in / channel_out initialization for scaling params.
nn.init.kaiming_uniform_(w, a=math.sqrt(5))
elif blade == self.n_blades + 1:
# Nothing to be done for zero kernel.
pass
else:
raise ValueError(
f"Wrong number of Clifford weights. Expected {self.n_blades} weight tensors, and 2 extra tensors for rotational kernels."
)
if self.bias is not None:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(
torch.Tensor(self.out_channels, int(self.in_channels * self.n_blades / self.groups), *self.kernel_size)
)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, x: torch.Tensor, conv_fn: callable) -> torch.Tensor:
if self.bias is not None:
b = self.bias.view(-1)
else:
b = None
output_blades, w = self._get_kernel(self.weight, self.g)
return clifford_convnd(conv_fn, x, output_blades, w, b, stride=self.stride, padding=self.padding, dilation=self.dilation, groups=self.groups,)
def extra_repr(self):
s = "{in_channels}, {out_channels}, kernel_size={kernel_size}" ", stride={stride}"
if self.padding != (0,) * len(self.padding):
s += ", padding={padding}"
if self.dilation != (1,) * len(self.dilation):
s += ", dilation={dilation}"
if self.groups != 1:
s += ", groups={groups}"
if self.bias is None:
s += ", bias=False"
return s.format(**self.__dict__)
class CliffordConv2d(_CliffordConvNd):
"""2d Clifford convolution (dim(g)=2).
Args:
g (Union[tuple, list, torch.Tensor]): Clifford signature.
in_channels (int): Number of channels in the input tensor.
out_channels (int): Number of channels produced by the convolution.
kernel_size (Union[int, Tuple[int, int]]): Size of the convolving kernel.
stride (Union[int, Tuple[int, int]]): Stride of the convolution.
padding (Union[int, Tuple[int, int]]): padding added to both sides of the input.
dilation (Union[int, Tuple[int, int]]): Spacing between kernel elements.
groups (int): Number of blocked connections from input channels to output channels.
bias (bool): If True, adds a learnable bias to the output.
padding_mode (str): Padding to use.
rotation (bool): If True, enables the rotation kernel for Clifford convolution.
"""
def __init__(self, g: Union[tuple, list, torch.Tensor], in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1,
padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, padding_mode: str = "zeros", rotation: bool = False,):
kernel_size_ = _pair(kernel_size)
stride_ = _pair(stride)
padding_ = padding if isinstance(padding, str) else _pair(padding)
dilation_ = _pair(dilation)
super().__init__(g, in_channels, out_channels, kernel_size_, stride_, padding_, dilation_, groups, bias, padding_mode, rotation,)
if not self.dim == 2 and not self.dim == 3:
raise NotImplementedError("Wrong Clifford signature for CliffordConv2d.")
def forward(self, x: torch.Tensor) -> torch.Tensor:
*_, I = x.shape
if not (I == self.n_blades):
raise ValueError(f"Input has {I} blades, but Clifford layer expects {self.n_blades}.")
return super().forward(x, F.conv2d)
class CliffordConv3d(_CliffordConvNd):
"""3d Clifford convolution.
Args:
g (Union[tuple, list, torch.Tensor]): Clifford signature.
in_channels (int): Number of channels in the input tensor.
out_channels (int): Number of channels produced by the convolution.
kernel_size (Union[int, Tuple[int, int, int]]): Size of the convolving kernel.
stride (Union[int, Tuple[int, int, int]]): Stride of the convolution.
padding (Union[int, Tuple[int, int, int]]): padding added to all sides of the input.
dilation (Union[int, Tuple[int, int, int]]): Spacing between kernel elements.
groups (int): Number of blocked connections from input channels to output channels.
bias (bool): If True, adds a learnable bias to the output.
padding_mode (str): Padding to use.
"""
def __init__(self, g: Union[tuple, list, torch.Tensor], in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1,
padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, padding_mode: str = "zeros",):
kernel_size_ = _triple(kernel_size)
stride_ = _triple(stride)
padding_ = padding if isinstance(padding, str) else _triple(padding)
dilation_ = _triple(dilation)
super().__init__(g, in_channels, out_channels, kernel_size_, stride_, padding_, dilation_, groups, bias, padding_mode,)
if not self.dim == 2 and not self.dim == 3:
raise NotImplementedError("Wrong Clifford signature for CliffordConv3d.")
def forward(self, x: torch.Tensor) -> torch.Tensor:
*_, I = x.shape
if not (I == self.n_blades):
raise ValueError(f"Input has {I} blades, but Clifford layer expects {self.n_blades}.")
return super().forward(x, F.conv3d)
class CliffordLinear(nn.Module):
"""Clifford linear layer.
Args:
g (Union[List, Tuple]): Clifford signature tensor.
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
bias (bool, optional): If True, adds a learnable bias to the output. Defaults to True.
"""
def __init__(self, g, in_channels: int, out_channels: int, bias: bool = True,) -> None:
super().__init__()
sig = CliffordSignature(g)
self.register_buffer("g", sig.g)
self.dim = sig.dim
self.n_blades = sig.n_blades
if self.dim == 2:
self._get_kernel = get_2d_clifford_kernel
elif self.dim == 3:
self._get_kernel = get_3d_clifford_kernel
else:
raise NotImplementedError(
f"Clifford linear layers are not implemented for {self.dim} dimensions. Wrong Clifford signature."
)
self.in_channels = in_channels
self.out_channels = out_channels
self.weight = nn.Parameter(torch.empty(self.n_blades, out_channels, in_channels))
if bias:
self.bias = nn.Parameter(torch.empty(self.n_blades, out_channels))
else:
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self):
# Initialization of the Clifford linear weight and bias tensors.
# The number of blades is taken into account when calculated the bounds of Kaiming uniform.
nn.init.kaiming_uniform_(
self.weight.view(self.out_channels, self.in_channels * self.n_blades),
a=math.sqrt(5),
)
if self.bias is not None:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(
self.weight.view(self.out_channels, self.in_channels * self.n_blades)
)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Reshape x such that the Clifford kernel can be applied.
B, _, I = x.shape
if not (I == self.n_blades):
raise ValueError(f"Input has {I} blades, but Clifford layer expects {self.n_blades}.")
B_dim, C_dim, I_dim = range(len(x.shape))
x = x.permute(B_dim, -1, C_dim)
x = x.reshape(B, -1)
# Get Clifford kernel, apply it.
_, weight = self._get_kernel(self.weight, self.g)
output = F.linear(x, weight, self.bias.view(-1))
# Reshape back.
output = output.view(B, I, -1)
B_dim, I_dim, C_dim = range(len(output.shape))
output = output.permute(B_dim, C_dim, I_dim)
return output
class CliffPhys20(nn.Module):
"""CliffordPhys20 model.
Args:
model_params (dict): Dictionary containing model parameters.
dropout_rate1 (float, optional): Dropout rate for the first dropout layer. Defaults to 0.25.
dropout_rate2 (float, optional): Dropout rate for the second dropout layer. Defaults to 0.5.
pool_size (Tuple, optional): Size of the pooling window. Defaults to (2, 2).
device (str, optional): Device to run the model on. Defaults to 'cpu'.
"""
def __init__(self, model_params, dropout_rate1=0.25, dropout_rate2=0.5, pool_size=(2, 2), device='cpu'):
super(CliffPhys20, self).__init__()
self.img_size = model_params['img_size']
self.num_frames = model_params['num_frames']
self.in_channels = 1
self.hidden_channels = 1
self.out_channels = self.img_size * self.img_size
self.kernel_size_1 = (15, 3, 3) # (frames, height, width) A:(15, 3, 3) B:(101, 3, 3)
self.dropout_rate1 = dropout_rate1
self.dropout_rate2 = dropout_rate2
self.pool_size = pool_size
self.g = [1, 1]
self.stride = (1, 1, 1) # (frames, height, width)
self.padding_1 = (7, 1, 1) # (frames, height, width) A:(7, 1, 1) B:(50, 1, 1)
self.num_groups = 1
self.device = device
# Motion branch
self.motion_conv1 = CliffordConv3d(self.g, self.in_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
self.motion_conv2 = CliffordConv3d(self.g, self.hidden_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
# Dropout layers
self.dropout_1 = nn.Dropout(self.dropout_rate1)
self.final_dense_1 = CliffordLinear(self.g, self.out_channels, 128, bias=True)
self.dropout_2 = nn.Dropout(self.dropout_rate2)
self.final_dense_2 = CliffordLinear(self.g, 128, 1, bias=True)
self.dropout_3 = nn.Dropout(self.dropout_rate2)
self.final_dense_3 = nn.Linear(4, 1, bias=True)
def forward(self, inputs):
"""Forward pass of the model.
Args:
inputs (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
S, F, C, H, W = inputs.size()
m = inputs.reshape(S, F, H, W, C)
scalar_pure_coeff = torch.zeros(S, F, H, W, 1)
e_coeff = torch.zeros(S, F, H, W, 1)
m = torch.cat((scalar_pure_coeff.to(self.device), m, e_coeff), dim=-1)
Q = m.size(-1)
m = m.reshape(S, 1, F, H, W, Q)
d1 = self.motion_conv1(m)
d2 = self.motion_conv2(d1)
d2 = d2.reshape(S*F, Q, H, W)
d2 = self.dropout_1(d2)
d2 = d2.view(S*F, H*W, Q)
d3 = self.final_dense_1(d2)
d3 = self.dropout_2(d3)
d4 = self.final_dense_2(d3)
d4 = self.dropout_3(d4)
out = self.final_dense_3(d4)
out = out.view(S,F)
return out
class CliffPhys30(nn.Module):
"""CliffordPhys30 model.
Args:
model_params (dict): Dictionary containing model parameters.
dropout_rate1 (float, optional): Dropout rate for the first dropout layer. Defaults to 0.25.
dropout_rate2 (float, optional): Dropout rate for the second dropout layer. Defaults to 0.5.
pool_size (Tuple, optional): Size of the pooling window. Defaults to (2, 2).
device (str, optional): Device to run the model on. Defaults to 'cpu'.
"""
def __init__(self, model_params, dropout_rate1=0.25, dropout_rate2=0.5, pool_size=(2, 2), device='cpu'):
super(CliffPhys30, self).__init__()
self.img_size = model_params['img_size']
self.num_frames = model_params['num_frames']
self.in_channels = 1
self.hidden_channels = 1
self.out_channels = self.img_size * self.img_size
self.kernel_size_1 = (15, 3, 3) # (frames, height, width) A:(15, 3, 3) B:(101, 3, 3)
self.dropout_rate1 = dropout_rate1
self.dropout_rate2 = dropout_rate2
self.pool_size = pool_size
self.g = [1, 1, 1]
self.stride = (1, 1, 1) # (frames, height, width)
self.padding_1 = (7, 1, 1) # (frames, height, width) A:(7, 1, 1) B:(50, 1, 1)
self.num_groups = 1
self.device = device
# Motion branch
self.motion_conv1 = CliffordConv3d(self.g, self.in_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
self.motion_conv2 = CliffordConv3d(self.g, self.hidden_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
# Dropout layers
self.dropout_1 = nn.Dropout(self.dropout_rate1)
self.final_dense_1 = CliffordLinear(self.g, self.out_channels, 128, bias=True)
self.dropout_2 = nn.Dropout(self.dropout_rate2)
self.final_dense_2 = CliffordLinear(self.g, 128, 1, bias=True)
self.dropout_3 = nn.Dropout(self.dropout_rate2)
self.final_dense_3 = nn.Linear(8, 1, bias=True)
def forward(self, inputs, params=None):
"""Forward pass of the model.
Args:
inputs (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
S, F, C, H, W = inputs.size()
m = inputs.reshape(S, F, H, W, C)
scalar_pure_coeff = torch.zeros(S, F, H, W, 1)
e_coeff = torch.zeros(S, F, H, W, 5)
m = torch.cat((scalar_pure_coeff.to(self.device), m, e_coeff), dim=-1)
Q = m.size(-1)
m = m.reshape(S, 1, F, H, W, Q)
d1 = self.motion_conv1(m)
d2 = self.motion_conv2(d1)
d2 = d2.reshape(S*F, Q, H, W)
d2 = self.dropout_1(d2)
d2 = d2.view(S*F, H*W, Q)
d3 = self.final_dense_1(d2)
d3 = self.dropout_2(d3)
d4 = self.final_dense_2(d3)
d4 = self.dropout_3(d4)
out = self.final_dense_3(d4)
out = out.view(S,F)
return out
class CliffPhys02(nn.Module):
"""CliffordPhys02 model.
Args:
model_params (dict): Dictionary containing model parameters.
dropout_rate1 (float, optional): Dropout rate for the first dropout layer. Defaults to 0.25.
dropout_rate2 (float, optional): Dropout rate for the second dropout layer. Defaults to 0.5.
pool_size (Tuple, optional): Size of the pooling window. Defaults to (2, 2).
device (str, optional): Device to run the model on. Defaults to 'cpu'.
"""
def __init__(self, model_params, dropout_rate1=0.25, dropout_rate2=0.5, pool_size=(2, 2), device='cpu'):
super(CliffPhys02, self).__init__()
self.img_size = model_params['img_size']
self.num_frames = model_params['num_frames']
self.in_channels = 1
self.hidden_channels = 1
self.out_channels = self.img_size * self.img_size
self.kernel_size_1 = (15, 3, 3) # (frames, height, width) A:(15, 3, 3) B:(101, 3, 3)
self.dropout_rate1 = dropout_rate1
self.dropout_rate2 = dropout_rate2
self.pool_size = pool_size
self.g = [-1, -1]
self.stride = (1, 1, 1) # (frames, height, width)
self.padding_1 = (7, 1, 1) # (frames, height, width) A:(7, 1, 1) B:(50, 1, 1)
self.num_groups = 1
self.device = device
# Motion branch
self.motion_conv1 = CliffordConv3d(self.g, self.in_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
self.motion_conv2 = CliffordConv3d(self.g, self.hidden_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
# Dropout layers
self.dropout_1 = nn.Dropout(self.dropout_rate1)
self.final_dense_1 = CliffordLinear(self.g, self.out_channels, 128, bias=True)
self.dropout_2 = nn.Dropout(self.dropout_rate2)
self.final_dense_2 = CliffordLinear(self.g, 128, 1, bias=True)
self.dropout_3 = nn.Dropout(self.dropout_rate2)
self.final_dense_3 = nn.Linear(4, 1, bias=True)
def forward(self, inputs):
"""Forward pass of the model.
Args:
inputs (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
S, F, C, H, W = inputs.size()
m = inputs.reshape(S, F, H, W, C)
scalar_pure_coeff = torch.zeros(S, F, H, W, 1)
e_coeff = torch.zeros(S, F, H, W, 1)
m = torch.cat((scalar_pure_coeff.to(self.device), m, e_coeff), dim=-1)
Q = m.size(-1)
m = m.reshape(S, 1, F, H, W, Q)
d1 = self.motion_conv1(m)
d2 = self.motion_conv2(d1)
d2 = d2.reshape(S*F, Q, H, W)
d2 = self.dropout_1(d2)
d2 = d2.view(S*F, H*W, Q)
d3 = self.final_dense_1(d2)
d3 = self.dropout_2(d3)
d4 = self.final_dense_2(d3)
d4 = self.dropout_3(d4)
out = self.final_dense_3(d4)
out = out.view(S,F)
return out
class CliffPhys03(nn.Module):
"""CliffordPhys03 model.
Args:
model_params (dict): Dictionary containing model parameters.
dropout_rate1 (float, optional): Dropout rate for the first dropout layer. Defaults to 0.25.
dropout_rate2 (float, optional): Dropout rate for the second dropout layer. Defaults to 0.5.
pool_size (Tuple, optional): Size of the pooling window. Defaults to (2, 2).
device (str, optional): Device to run the model on. Defaults to 'cpu'.
"""
def __init__(self, model_params, dropout_rate1=0.25, dropout_rate2=0.5, pool_size=(2, 2), device='cpu'):
super(CliffPhys03, self).__init__()
self.img_size = model_params['img_size']
self.num_frames = model_params['num_frames']
self.in_channels = 1
self.hidden_channels = 1
self.out_channels = self.img_size * self.img_size
self.kernel_size_1 = (15, 3, 3) # (frames, height, width) A:(15, 3, 3) B:(101, 3, 3)
self.dropout_rate1 = dropout_rate1
self.dropout_rate2 = dropout_rate2
self.pool_size = pool_size
self.g = [-1, -1, -1]
self.stride = (1, 1, 1) # (frames, height, width)
self.padding_1 = (7, 1, 1) # (frames, height, width) A:(7, 1, 1) B:(50, 1, 1)
self.num_groups = 1
self.device = device
# Motion branch
self.motion_conv1 = CliffordConv3d(self.g, self.in_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
self.motion_conv2 = CliffordConv3d(self.g, self.hidden_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
# Dropout layers
self.dropout_1 = nn.Dropout(self.dropout_rate1)
self.final_dense_1 = CliffordLinear(self.g, self.out_channels, 128, bias=True)
self.dropout_2 = nn.Dropout(self.dropout_rate2)
self.final_dense_2 = CliffordLinear(self.g, 128, 1, bias=True)
self.dropout_3 = nn.Dropout(self.dropout_rate2)
self.final_dense_3 = nn.Linear(8, 1, bias=True)
def forward(self, inputs):
"""Forward pass of the model.
Args:
inputs (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
S, F, C, H, W = inputs.size()
m = inputs.reshape(S, F, H, W, C)
scalar_pure_coeff = torch.zeros(S, F, H, W, 1)
e_coeff = torch.zeros(S, F, H, W, 5)
m = torch.cat((scalar_pure_coeff.to(self.device), m, e_coeff), dim=-1)
Q = m.size(-1)
m = m.reshape(S, 1, F, H, W, Q)
d1 = self.motion_conv1(m)
d2 = self.motion_conv2(d1)
d2 = d2.reshape(S*F, Q, H, W)
d2 = self.dropout_1(d2)
d2 = d2.view(S*F, H*W, Q)
d3 = self.final_dense_1(d2)
d3 = self.dropout_2(d3)
d4 = self.final_dense_2(d3)
d4 = self.dropout_3(d4)
out = self.final_dense_3(d4)
out = out.view(S,F)
return out
class CliffPhys30_d(nn.Module):
"""CliffordPhys30_d model, processing also depth information.
Args:
model_params (dict): Dictionary containing model parameters.
dropout_rate1 (float, optional): Dropout rate for the first dropout layer. Defaults to 0.25.
dropout_rate2 (float, optional): Dropout rate for the second dropout layer. Defaults to 0.5.
pool_size (Tuple, optional): Size of the pooling window. Defaults to (2, 2).
device (str, optional): Device to run the model on. Defaults to 'cpu'.
"""
def __init__(self, model_params, dropout_rate1=0.25, dropout_rate2=0.5, pool_size=(2, 2), device='cpu'):
super(CliffPhys30_d, self).__init__()
self.img_size = model_params['img_size']
self.num_frames = model_params['num_frames']
self.in_channels = 1
self.hidden_channels = 1
self.out_channels = self.img_size * self.img_size
self.kernel_size_1 = (15, 3, 3) # (frames, height, width) A:(15, 3, 3) B:(101, 3, 3)
self.dropout_rate1 = dropout_rate1
self.dropout_rate2 = dropout_rate2
self.pool_size = pool_size
self.g = [1, 1, 1]
self.stride = (1, 1, 1) # (frames, height, width)
self.padding_1 = (7, 1, 1) # (frames, height, width) A:(7, 1, 1) B:(50, 1, 1)
self.num_groups = 1
self.device = device
# Motion branch
self.motion_conv1 = CliffordConv3d(self.g, self.in_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
self.motion_conv2 = CliffordConv3d(self.g, self.hidden_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
# Dropout layers
self.dropout_1 = nn.Dropout(self.dropout_rate1)
self.final_dense_1 = CliffordLinear(self.g, self.out_channels, 128, bias=True)
self.dropout_2 = nn.Dropout(self.dropout_rate2)
self.final_dense_2 = CliffordLinear(self.g, 128, 1, bias=True)
self.dropout_3 = nn.Dropout(self.dropout_rate2)
self.final_dense_3 = nn.Linear(8, 1, bias=True)
def forward(self, inputs):
"""Forward pass of the model.
Args:
inputs (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
S, F, C, H, W = inputs.size()
m = inputs.reshape(S, F, H, W, C)
e_coeff = torch.zeros(S, F, H, W, 5)
m = torch.cat((m, e_coeff), dim=-1)
Q = m.size(-1)
m = m.reshape(S, 1, F, H, W, Q)
d1 = self.motion_conv1(m)
d2 = self.motion_conv2(d1)
d2 = d2.reshape(S*F, Q, H, W)
d2 = self.dropout_1(d2)
d2 = d2.view(S*F, H*W, Q)
d3 = self.final_dense_1(d2)
d3 = self.dropout_2(d3)
d4 = self.final_dense_2(d3)
d4 = self.dropout_3(d4)
out = self.final_dense_3(d4)
out = out.view(S,F)
return out
class CliffPhys20_d(nn.Module):
"""CliffordPhys20_d model, processing also depth information.
Args:
model_params (dict): Dictionary containing model parameters.
dropout_rate1 (float, optional): Dropout rate for the first dropout layer. Defaults to 0.25.
dropout_rate2 (float, optional): Dropout rate for the second dropout layer. Defaults to 0.5.
pool_size (Tuple, optional): Size of the pooling window. Defaults to (2, 2).
device (str, optional): Device to run the model on. Defaults to 'cpu'.
"""
def __init__(self, model_params, dropout_rate1=0.25, dropout_rate2=0.5, pool_size=(2, 2), device='cpu'):
super(CliffPhys20_d, self).__init__()
self.img_size = model_params['img_size']
self.num_frames = model_params['num_frames']
self.in_channels = 1
self.hidden_channels = 1
self.out_channels = self.img_size * self.img_size
self.kernel_size_1 = (15, 3, 3) # (frames, height, width) A:(15, 3, 3) B:(101, 3, 3)
self.dropout_rate1 = dropout_rate1
self.dropout_rate2 = dropout_rate2
self.pool_size = pool_size
self.g = [1, 1]
self.stride = (1, 1, 1) # (frames, height, width)
self.padding_1 = (7, 1, 1) # (frames, height, width) A:(7, 1, 1) B:(50, 1, 1)
self.num_groups = 1
self.device = device
# Motion branch
self.motion_conv1 = CliffordConv3d(self.g, self.in_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
self.motion_conv2 = CliffordConv3d(self.g, self.hidden_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
# Dropout layers
self.dropout_1 = nn.Dropout(self.dropout_rate1)
self.final_dense_1 = CliffordLinear(self.g, self.out_channels, 128, bias=True)
self.dropout_2 = nn.Dropout(self.dropout_rate2)
self.final_dense_2 = CliffordLinear(self.g, 128, 1, bias=True)
self.dropout_3 = nn.Dropout(self.dropout_rate2)
self.final_dense_3 = nn.Linear(4, 1, bias=True)
def forward(self, inputs):
"""Forward pass of the model.
Args:
inputs (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
S, F, C, H, W = inputs.size()
m = inputs.reshape(S, F, H, W, C)
e_coeff = torch.zeros(S, F, H, W, 1)
m = torch.cat((m, e_coeff), dim=-1)
Q = m.size(-1)
m = m.reshape(S, 1, F, H, W, Q)
d1 = self.motion_conv1(m)
d2 = self.motion_conv2(d1)
d2 = d2.reshape(S*F, Q, H, W)
d2 = self.dropout_1(d2)
d2 = d2.view(S*F, H*W, Q)
d3 = self.final_dense_1(d2)
d3 = self.dropout_2(d3)
d4 = self.final_dense_2(d3)
d4 = self.dropout_3(d4)
out = self.final_dense_3(d4)
out = out.view(S,F)
return out
class CliffPhys02_d(nn.Module):
"""CliffordPhys02_d model, processing also depth information.
Args:
model_params (dict): Dictionary containing model parameters.
dropout_rate1 (float, optional): Dropout rate for the first dropout layer. Defaults to 0.25.
dropout_rate2 (float, optional): Dropout rate for the second dropout layer. Defaults to 0.5.
pool_size (Tuple, optional): Size of the pooling window. Defaults to (2, 2).
device (str, optional): Device to run the model on. Defaults to 'cpu'.
"""
def __init__(self, model_params, dropout_rate1=0.25, dropout_rate2=0.5, pool_size=(2, 2), device='cpu'):
super(CliffPhys02_d, self).__init__()
self.img_size = model_params['img_size']
self.num_frames = model_params['num_frames']
self.in_channels = 1
self.hidden_channels = 1
self.out_channels = self.img_size * self.img_size
self.kernel_size_1 = (15, 3, 3) # (frames, height, width) A:(15, 3, 3) B:(101, 3, 3)
self.dropout_rate1 = dropout_rate1
self.dropout_rate2 = dropout_rate2
self.pool_size = pool_size
self.g = [-1, -1]
self.stride = (1, 1, 1) # (frames, height, width)
self.padding_1 = (7, 1, 1) # (frames, height, width) A:(7, 1, 1) B:(50, 1, 1)
self.num_groups = 1
self.device = device
# Motion branch
self.motion_conv1 = CliffordConv3d(self.g, self.in_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
self.motion_conv2 = CliffordConv3d(self.g, self.hidden_channels, self.hidden_channels, kernel_size=self.kernel_size_1, stride=self.stride,
padding=self.padding_1, bias=True)
# Dropout layers
self.dropout_1 = nn.Dropout(self.dropout_rate1)
self.final_dense_1 = CliffordLinear(self.g, self.out_channels, 128, bias=True)
self.dropout_2 = nn.Dropout(self.dropout_rate2)
self.final_dense_2 = CliffordLinear(self.g, 128, 1, bias=True)
self.dropout_3 = nn.Dropout(self.dropout_rate2)
self.final_dense_3 = nn.Linear(4, 1, bias=True)
def forward(self, inputs):
"""Forward pass of the model.
Args:
inputs (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
S, F, C, H, W = inputs.size()
m = inputs.reshape(S, F, H, W, C)
k_pure_coeff = torch.zeros(S, F, H, W, 1)
m = torch.cat((m, k_pure_coeff.to(self.device)), dim=-1)
Q = m.size(-1)
m = m.reshape(S, 1, F, H, W, Q)
d1 = self.motion_conv1(m)
d2 = self.motion_conv2(d1)
d2 = d2.reshape(S*F, Q, H, W)