-
Notifications
You must be signed in to change notification settings - Fork 104
/
model.py
1578 lines (1342 loc) · 56.8 KB
/
model.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
"""
T.E.D.D. 1104 (Reference to the robot that drives a bus is Call of Duty: Black Ops II tranzit mode
https://nazizombiesplus.fandom.com/wiki/T.E.D.D.)
is the neural network that learns how to drive in video-games.
It has been developed with Grand Theft Auto V (GTAV) in mind.
However, it can learn how to drive in any video-game and if the game controls are modified accordingly.
T.E.D.D. 1104 is a supervised learning model, it learns from the examples recorded when human players play the game.
Additionally, 'TEDD1104 for image reordering' predicts the correct order of images in a shuffled sequence.
It is intended as a pretraining task before training in the self-driving objetive.
Developed by Iker García-Ferrero:
Website: https://ikergarcia1996.github.io/Iker-Garcia-Ferrero/
Github: https://github.com/ikergarcia1996
Some of the code for input handling and image recording was developed with the help of Aiden Yerga:
Github: https://github.com/aidenyg
Project GitHub repository:
https://github.com/ikergarcia1996/Self-Driving-Car-in-Video-Games
"""
from typing import List
import torch
import torch.nn as nn
import torchvision
import torchvision.models as models
import pytorch_lightning as pl
import torchmetrics
from optimizers.optimizer import get_adafactor, get_adamw
from optimizers.scheduler import (
get_reducelronplateau,
get_linear_schedule_with_warmup,
get_polynomial_decay_schedule_with_warmup,
get_cosine_schedule_with_warmup,
)
from packaging import version # Requires setuptools
class WeightedMseLoss(nn.Module):
"""
Weighted mse loss columnwise
"""
def __init__(
self,
weights: List[float] = None,
reduction: str = "mean",
):
"""
INIT
:param List[float] weights: List of weights for each joystick
:param str reduction: "mean" or "sum"
"""
assert reduction in ["sum", "mean"], (
f"Reduction method: {reduction} not implemented. "
f"Available reduction methods: [sum,mean]"
)
super(WeightedMseLoss, self).__init__()
self.reduction = reduction
if not weights:
weights = [1.0, 1.0]
weights = torch.tensor(weights)
weights.requires_grad = False
self.register_buffer("weights", weights)
def forward(
self,
predicted: torch.tensor,
target: torch.tensor,
) -> torch.tensor:
"""
Forward pass
:param torch.tensor predicted: Predicted values [batch_size, 2]
:param torch.tensor target: Target values [batch_size, 2]
:return: Loss [1] if reduction is "mean" else [2]
"""
if self.reduction == "mean":
loss_per_joystick: torch.tensor = torch.mean(
(predicted - target) ** 2, dim=0
)
return torch.mean(self.weights * loss_per_joystick)
else:
loss_per_joystick: torch.tensor = torch.sum(
(predicted - target) ** 2, dim=0
)
return self.weights * loss_per_joystick
class CrossEntropyLoss(torch.nn.Module):
"""
Weighted CrossEntropyLoss
"""
def __init__(
self,
weights: List[float] = None,
reduction: str = "mean",
label_smoothing: float = 0.0,
):
"""
INIT
:param List[float] weights: List of weights for each key combination [9]
:param str reduction: "mean" or "sum"
:param float label_smoothing: A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss
"""
assert reduction in ["sum", "mean"], (
f"Reduction method: {reduction} not implemented. "
f"Available reduction methods: [sum,mean]"
)
super(CrossEntropyLoss, self).__init__()
self.reduction = reduction
if weights:
weights = torch.tensor(weights)
weights.requires_grad = False
self.register_buffer("weights", weights)
self.CrossEntropyLoss = torch.nn.CrossEntropyLoss(
reduction=reduction,
weight=weights,
label_smoothing=label_smoothing,
)
def forward(
self,
predicted: torch.tensor,
target: torch.tensor,
) -> torch.tensor:
"""
Forward pass
:param torch.tensor predicted: Predicted values [batch_size, 9]
:param torch.tensor target: Target values [batch_size]
:return: Loss [1] if reduction is "mean" else [9]
"""
return self.CrossEntropyLoss(predicted, target)
class CrossEntropyLossImageReorder(torch.nn.Module):
"""
Weighted CrossEntropyLoss for Image Reordering
"""
def __init__(
self,
label_smoothing: float = 0.0,
):
"""
INIT
:param float label_smoothing: A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss
"""
super(CrossEntropyLossImageReorder, self).__init__()
self.CrossEntropyLoss = torch.nn.CrossEntropyLoss(
label_smoothing=label_smoothing
)
def forward(
self,
predicted: torch.tensor,
target: torch.tensor,
) -> torch.tensor:
"""
Forward pass
:param torch.tensor predicted: Predicted values [batch_size, 5]
:param torch.tensor target: Target values [batch_size]
:return: Loss [1]
"""
return self.CrossEntropyLoss(predicted.view(-1, 5), target.view(-1).long())
class ImageReorderingAccuracy(torchmetrics.Metric):
"""
Image Reordering Accuracy Metric
"""
def __init__(self, dist_sync_on_step=False):
"""
INIT
:param bool dist_sync_on_step: If True, the metric will be synchronized on step
"""
super().__init__(dist_sync_on_step=dist_sync_on_step)
self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum")
self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
def update(self, preds: torch.Tensor, target: torch.Tensor):
"""
Update the metric with the given predictions and targets
:param torch.Tensor preds: Predictions [batch_size, 5]
:param torch.Tensor target: Target values [batch_size]
"""
assert (
preds.size() == target.size()
), f"Pred sise: {preds.size()} != Target size: {target.size()}"
self.correct += torch.sum(torch.all(preds == target, dim=-1))
self.total += target.size(0)
def compute(self):
return self.correct.float() / self.total
def get_cnn(cnn_model_name: str, pretrained: bool) -> (torchvision.models, int):
"""
Get a CNN model from torchvision.models (https://pytorch.org/vision/stable/models.html)
:param str cnn_model_name: Name of the CNN model from torchvision.models
:param bool pretrained: If True, the model will be loaded with pretrained weights
:return: CNN model, last layer output size
"""
# Get the CNN model
cnn_call_method = getattr(models, cnn_model_name)
cnn_model = cnn_call_method(pretrained=pretrained)
# Remove classification layer
_ = cnn_model._modules.popitem()
cnn_model = nn.Sequential(*list(cnn_model.children()))
# Test output_size of last layer of the CNN (Not the most efficient way, but it works)
features = cnn_model(torch.zeros((1, 3, 270, 480), dtype=torch.float32))
output_size: int = features.reshape(features.size(0), -1).size(1)
return cnn_model, output_size
class EncoderCNN(nn.Module):
"""
Encoder CNN, extracts features from the input images
For efficiency the input is a single sequence of [sequence_size*batch_size] images,
the output of the CNN will be packed as sequences of sequence_size vectors.
"""
def __init__(
self,
embedded_size: int,
dropout_cnn_out: float,
cnn_model_name: str,
pretrained_cnn: bool,
sequence_size: int = 5,
):
"""
INIT
:param int embedded_size: Size of the output embedding
:param float dropout_cnn_out: Dropout rate for the output of the CNN
:param str cnn_model_name: Name of the CNN model from torchvision.models
:param bool pretrained_cnn: If True, the model will be loaded with pretrained weights
:param int sequence_size: Size of the sequence of images
"""
super(EncoderCNN, self).__init__()
self.embedded_size = embedded_size
self.cnn_model_name = cnn_model_name
self.dropout_cnn_out = dropout_cnn_out
self.pretrained_cnn = pretrained_cnn
self.cnn, self.cnn_output_size = get_cnn(
cnn_model_name=cnn_model_name, pretrained=pretrained_cnn
)
self.dp = nn.Dropout(p=dropout_cnn_out)
self.dense = nn.Linear(self.cnn_output_size, self.cnn_output_size)
self.layer_norm = nn.LayerNorm(self.cnn_output_size, eps=1e-05)
self.decoder = nn.Linear(self.cnn_output_size, self.embedded_size)
self.bias = nn.Parameter(torch.zeros(self.embedded_size))
self.decoder.bias = self.bias
self.gelu = nn.GELU()
self.sequence_size = sequence_size
def forward(self, images: torch.tensor) -> torch.tensor:
"""
Forward pass
:param torch.tensor images: Input images [batch_size * sequence_size, 3, 270, 480]
:return: Output embedding [batch_size, sequence_size, embedded_size]
"""
features = self.cnn(images)
features = features.reshape(features.size(0), -1)
"""
Reshapes the features from the CNN into a time distributed format
"""
features = features.view(
int(features.size(0) / self.sequence_size),
self.sequence_size,
features.size(1),
)
features = self.dp(features)
features = self.dense(features)
features = self.gelu(features)
features = self.layer_norm(features)
features = self.decoder(features)
return features
def _tie_weights(self):
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
self.bias = self.decoder.bias
class EncoderRNN(nn.Module):
"""
Extracts features from the input sequence using an RNN
"""
def __init__(
self,
embedded_size: int,
hidden_size: int,
num_layers: int,
bidirectional_lstm: bool,
dropout_lstm: float,
):
"""
INIT
:param int embedded_size: Size of the input feature vectors
:param int hidden_size: LSTM hidden size
:param int num_layers: number of layers in the LSTM
:param bool bidirectional_lstm: forward or bidirectional LSTM
:param float dropout_lstm: dropout probability for the LSTM
"""
super(EncoderRNN, self).__init__()
self.embedded_size = embedded_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.bidirectional_lstm = bidirectional_lstm
self.dropout_lstm = dropout_lstm
self.lstm: nn.LSTM = nn.LSTM(
embedded_size,
hidden_size,
num_layers,
dropout=dropout_lstm,
bidirectional=bidirectional_lstm,
batch_first=True,
)
self.bidirectional_lstm = bidirectional_lstm
def forward(self, features: torch.tensor) -> torch.tensor:
"""
Forward pass
:param torch.tensor features: Input features [batch_size, sequence_size, embedded_size]
:return: Output features [batch_size, hidden_size*2 if bidirectional else hidden_size]
"""
output, (h_n, c_n) = self.lstm(features)
if self.bidirectional_lstm:
x = torch.cat((h_n[-2], h_n[-1]), 1)
else:
x = h_n[-1]
return x
class PositionalEmbedding(nn.Module):
"""
Add positional encodings to the transformer input features
"""
def __init__(
self,
sequence_length: int,
d_model: int,
dropout: float = 0.1,
):
"""
INIT
:param int sequence_length: Length of the input sequence
:param int d_model: Size of the input feature vectors
:param float dropout: dropout probability for the embeddings
"""
super(PositionalEmbedding, self).__init__()
self.d_model = d_model
self.sequence_length = sequence_length
self.dropout = dropout
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(self.sequence_length, d_model).float()
pe.requires_grad = True
pe = pe.unsqueeze(0)
self.pe = torch.nn.Parameter(pe)
torch.nn.init.normal_(self.pe, std=0.02)
self.LayerNorm = nn.LayerNorm(self.d_model, eps=1e-05)
self.dp = torch.nn.Dropout(p=dropout)
def forward(self, x: torch.tensor) -> torch.tensor:
"""
Forward pass
:param torch.tensor x: Input features [batch_size, sequence_size, embedded_size]
:return: Output features [batch_size, sequence_size, embedded_size]
"""
pe = self.pe[:, : x.size(1)]
x = pe + x
x = self.LayerNorm(x)
x = self.dp(x)
return x
class EncoderTransformer(nn.Module):
"""
Extracts features from the input sequence using a Transformer
"""
def __init__(
self,
d_model: int = 512,
nhead: int = 8,
num_layers: int = 1,
dropout: float = 0.1,
sequence_length: int = 5,
):
"""
INIT
:param int d_model: Size of the input feature vectors
:param int nhead: Number of heads in the multi-head attention
:param int num_layers: number of transformer layers in the encoder
:param float dropout: dropout probability of transformer layers in the encoder
:param int sequence_length: Length of the input sequence
"""
super(EncoderTransformer, self).__init__()
self.d_model = d_model
self.nhead = nhead
self.num_layers = num_layers
self.dropout = dropout
self.sequence_length = sequence_length
cls_token = torch.zeros(1, 1, self.d_model).float()
cls_token.require_grad = True
self.clsToken = torch.nn.Parameter(cls_token)
torch.nn.init.normal_(cls_token, std=0.02)
self.pe = PositionalEmbedding(
sequence_length=self.sequence_length + 1, d_model=self.d_model
)
encoder_layer = torch.nn.TransformerEncoderLayer(
d_model=self.d_model,
nhead=self.nhead,
dim_feedforward=self.d_model * 4,
dropout=dropout,
activation="gelu",
batch_first=True,
)
self.transformer_encoder = torch.nn.TransformerEncoder(
encoder_layer, num_layers=self.num_layers
)
for parameter in self.transformer_encoder.parameters():
parameter.requires_grad = True
def forward(
self, features: torch.tensor, attention_mask: torch.tensor = None
) -> torch.tensor:
"""
Forward pass
:param torch.tensor features: Input features [batch_size, sequence_length, embedded_size]
:param torch.tensor attention_mask: Mask for the input features
[batch_size*heads, sequence_length, sequence_length]
1 for masked positions and 0 for unmasked positions
:return: Output features [batch_size, d_model]
"""
features = torch.cat(
(self.clsToken.repeat(features.size(0), 1, 1), features), dim=1
)
features = self.pe(features)
features = self.transformer_encoder(features, attention_mask)
return features
class OutputLayer(nn.Module):
"""
Output layer of the model
Based on RobertaClassificationHead:
https://github.com/huggingface/transformers/blob/master/src/transformers/models/roberta/modeling_roberta.py
"""
def __init__(
self,
d_model: int,
num_classes: int,
dropout_encoder_features: float = 0.2,
from_transformer: bool = True,
):
"""
INIT
:param int d_model: Size of the encoder output vector
:param int num_classes: Size of output vector
:param float dropout_encoder_features: Dropout probability of the encoder output
:param bool from_transformer: If true, get the CLS token from the transformer output
"""
super(OutputLayer, self).__init__()
self.d_model = d_model
self.num_classes = num_classes
self.dropout_encoder_features = dropout_encoder_features
self.dense = nn.Linear(self.d_model, self.d_model)
self.dp = nn.Dropout(p=dropout_encoder_features)
self.out_proj = nn.Linear(self.d_model, self.num_classes)
self.tanh = nn.Tanh()
self.from_transformer = from_transformer
def forward(self, x):
"""
Forward pass
:param torch.tensor x: Input features [batch_size, d_model] if RNN else [batch_size, sequence_length+1, d_model]
:return: Output features [num_classes]
"""
if self.from_transformer:
x = x[:, 0, :] # Get [CLS] token
x = self.dp(x)
x = self.dense(x)
x = torch.tanh(x)
x = self.dp(x)
x = self.out_proj(x)
return x
class OutputImageOrderingLayer(nn.Module):
"""
Output layer of the image reordering model
Based on RobertaLMHead:
https://github.com/huggingface/transformers/blob/master/src/transformers/models/roberta/modeling_roberta.py
"""
def __init__(self, d_model: int, num_classes: int):
"""
INIT
:param int d_model: Size of the encoder output vector
:param int num_classes: Size of output vector
"""
super(OutputImageOrderingLayer, self).__init__()
self.d_model = d_model
self.num_classes = num_classes
self.dense = nn.Linear(self.d_model, self.d_model)
self.layer_norm = nn.LayerNorm(self.d_model, eps=1e-05)
self.decoder = nn.Linear(self.d_model, self.num_classes)
self.bias = nn.Parameter(torch.zeros(num_classes))
self.decoder.bias = self.bias
self.gelu = nn.GELU()
def forward(self, x):
"""
Forward pass
:param torch.tensor x: Input features [batch_size, sequence_length+1, d_model]
:return: Output features [num_classes]
"""
x = self.dense(x)[:, 1:, :] # Remove CLS
x = self.gelu(x)
x = self.layer_norm(x)
x = self.decoder(x)
return x
class Controller2Keyboard(nn.Module):
"""
Map controller output to keyboard keys probabilities
"""
def __init__(self):
"""
INIT
"""
super(Controller2Keyboard, self).__init__()
keys2vector_matrix = torch.tensor(
[
[0.0, 0.0],
[-1.0, 0.0],
[1.0, 0.0],
[0.0, 1.0],
[0.0, -1.0],
[-1.0, 1.0],
[-1.0, -1.0],
[1.0, 1.0],
[1.0, -1.0],
],
requires_grad=False,
)
self.register_buffer("keys2vector_matrix", keys2vector_matrix)
def forward(self, x: torch.tensor):
"""
Forward pass
:param torch.tensor x: Controller input [2]
:return: Keyboard keys probabilities [9]
"""
return 1.0 / torch.cdist(x, self.keys2vector_matrix)
class Keyboard2Controller(nn.Module):
"""
Map keyboard keys probabilities to controller output
"""
def __init__(self):
"""
INIT
"""
super(Keyboard2Controller, self).__init__()
keys2vector_matrix = torch.tensor(
[
[0.0, 0.0],
[-1.0, 0.0],
[1.0, 0.0],
[0.0, 1.0],
[0.0, -1.0],
[-1.0, 1.0],
[-1.0, -1.0],
[1.0, 1.0],
[1.0, -1.0],
],
requires_grad=False,
)
self.register_buffer("keys2vector_matrix", keys2vector_matrix)
def forward(self, x: torch.tensor):
"""
Forward pass
:param torch.tensor x: Keyboard keys probabilities [9]
:return: Controller input [2]
"""
controller_inputs = self.keys2vector_matrix.repeat(len(x), 1, 1)
return (
torch.sum(controller_inputs * x.view(len(x), 9, 1), dim=1)
/ torch.sum(x, dim=-1)[:, None]
)
class TEDD1104LSTM(nn.Module):
"""
T.E.D.D 1104 model with LSTM encoder. The model consists of:
- A CNN that extract features from the images
- A RNN (LSTM) that extracts a representation of the image sequence
- A linear output layer that predicts the controller input.
"""
def __init__(
self,
cnn_model_name: str,
pretrained_cnn: bool,
embedded_size: int,
hidden_size: int,
num_layers_lstm: int,
bidirectional_lstm: bool,
dropout_cnn_out: float,
dropout_lstm: float,
dropout_encoder_features: float,
control_mode: str = "keyboard",
sequence_size: int = 5,
):
"""
INIT
:param int embedded_size: Size of the output embedding
:param float dropout_cnn_out: Dropout rate for the output of the CNN
:param str cnn_model_name: Name of the CNN model from torchvision.models
:param bool pretrained_cnn: If True, the model will be loaded with pretrained weights
:param int embedded_size: Size of the input feature vectors
:param int hidden_size: LSTM hidden size
:param int num_layers_lstm: number of layers in the LSTM
:param bool bidirectional_lstm: forward or bidirectional LSTM
:param float dropout_lstm: dropout probability for the LSTM
:param float dropout_encoder_features: Dropout probability of the encoder output
:param int sequence_size: Length of the input sequence
:param control_mode: Model output format: keyboard (Classification task: 9 classes) or controller (Regression task: 2 variables)
"""
super(TEDD1104LSTM, self).__init__()
# Remember hyperparameters.
self.cnn_model_name: str = cnn_model_name
self.pretrained_cnn: bool = pretrained_cnn
self.sequence_size: int = sequence_size
self.embedded_size: int = embedded_size
self.hidden_size: int = hidden_size
self.num_layers_lstm: int = num_layers_lstm
self.bidirectional_lstm: bool = bidirectional_lstm
self.dropout_cnn_out: float = dropout_cnn_out
self.dropout_lstm: float = dropout_lstm
self.dropout_encoder_features = dropout_encoder_features
self.control_mode = control_mode
self.EncoderCNN: EncoderCNN = EncoderCNN(
embedded_size=embedded_size,
dropout_cnn_out=dropout_cnn_out,
cnn_model_name=cnn_model_name,
pretrained_cnn=pretrained_cnn,
)
self.EncoderRNN: EncoderRNN = EncoderRNN(
embedded_size=embedded_size,
hidden_size=hidden_size,
num_layers=num_layers_lstm,
bidirectional_lstm=bidirectional_lstm,
dropout_lstm=dropout_lstm,
)
self.OutputLayer: OutputLayer = OutputLayer(
d_model=embedded_size if not self.bidirectional_lstm else embedded_size * 2,
num_classes=9 if self.control_mode == "keyboard" else 2,
dropout_encoder_features=self.dropout_encoder_features,
from_transformer=False,
)
def forward(
self, x: torch.tensor, attention_mask: torch.tensor = None
) -> torch.tensor:
"""
Forward pass
:param torch.tensor x: Input tensor of shape [batch_size * sequence_size, 3, 270, 480]
:param torch.tensor attention_mask: For compatibility with the Transformer model, this is not used
:return: Output tensor of shape [9] if control_mode == "keyboard" or [2] if control_mode == "controller"
"""
x = self.EncoderCNN(x)
x = self.EncoderRNN(x)
return self.OutputLayer(x)
class TEDD1104Transformer(nn.Module):
"""
T.E.D.D 1104 model with transformer encoder. The model consists of:
- A CNN that extract features from the images
- A transformer that extracts a representation of the image sequence
- A linear output layer that predicts the controller input.
"""
def __init__(
self,
cnn_model_name: str,
pretrained_cnn: bool,
embedded_size: int,
nhead: int,
num_layers_transformer: int,
dropout_cnn_out: float,
positional_embeddings_dropout: float,
dropout_transformer: float,
dropout_encoder_features: float,
control_mode: str = "keyboard",
sequence_size: int = 5,
):
"""
INIT
:param int embedded_size: Size of the output embedding
:param float dropout_cnn_out: Dropout rate for the output of the CNN
:param str cnn_model_name: Name of the CNN model from torchvision.models
:param bool pretrained_cnn: If True, the model will be loaded with pretrained weights
:param int embedded_size: Size of the input feature vectors
:param int nhead: Number of heads in the multi-head attention
:param int num_layers_transformer: number of transformer layers in the encoder
:param float positional_embeddings_dropout: Dropout rate for the positional embeddings
:param float dropout_transformer: dropout probability of transformer layers in the encoder
:param int sequence_size: Length of the input sequence
:param float dropout_encoder_features: Dropout probability of the encoder output
:param control_mode: Model output format: keyboard (Classification task: 9 classes) or controller (Regression task: 2 variables)
"""
super(TEDD1104Transformer, self).__init__()
# Remember hyperparameters.
self.cnn_model_name: str = cnn_model_name
self.pretrained_cnn: bool = pretrained_cnn
self.sequence_size: int = sequence_size
self.embedded_size: int = embedded_size
self.nhead: int = nhead
self.num_layers_transformer: int = num_layers_transformer
self.dropout_cnn_out: float = dropout_cnn_out
self.positional_embeddings_dropout: float = positional_embeddings_dropout
self.dropout_transformer: float = dropout_transformer
self.control_mode = control_mode
self.dropout_encoder_features = dropout_encoder_features
self.EncoderCNN: EncoderCNN = EncoderCNN(
embedded_size=embedded_size,
dropout_cnn_out=dropout_cnn_out,
cnn_model_name=cnn_model_name,
pretrained_cnn=pretrained_cnn,
sequence_size=self.sequence_size,
)
self.PositionalEncoding = PositionalEmbedding(
d_model=embedded_size,
dropout=self.positional_embeddings_dropout,
sequence_length=self.sequence_size,
)
self.EncoderTransformer: EncoderTransformer = EncoderTransformer(
d_model=embedded_size,
nhead=nhead,
num_layers=num_layers_transformer,
dropout=self.dropout_transformer,
)
self.OutputLayer: OutputLayer = OutputLayer(
d_model=embedded_size,
num_classes=9 if self.control_mode == "keyboard" else 2,
dropout_encoder_features=dropout_encoder_features,
from_transformer=True,
)
def forward(
self, x: torch.tensor, attention_mask: torch.tensor = None
) -> torch.tensor:
"""
Forward pass
:param torch.tensor x: Input tensor of shape [batch_size * sequence_size, 3, 270, 480]
:param torch.tensor attention_mask: Mask for the input features
[batch_size*heads, sequence_length, sequence_length]
1 for masked positions and 0 for unmasked positions
:return: Output tensor of shape [9] if control_mode == "keyboard" or [2] if control_mode == "controller"
"""
x = self.EncoderCNN(x)
x = self.PositionalEncoding(x)
x = self.EncoderTransformer(x, attention_mask=attention_mask)
return self.OutputLayer(x)
class TEDD1104TransformerForImageReordering(nn.Module):
"""
T.E.D.D 1104 for image reordering model consists of:
- A CNN that extract features from the images
- A transformer that extracts a representation of the image sequence
- A linear output layer that predicts the correct order of the input sequence
"""
def __init__(
self,
cnn_model_name: str,
pretrained_cnn: bool,
embedded_size: int,
nhead: int,
num_layers_transformer: int,
dropout_cnn_out: float,
positional_embeddings_dropout: float,
dropout_transformer: float,
dropout_encoder_features: float,
sequence_size: int = 5,
):
"""
INIT
:param int embedded_size: Size of the output embedding
:param float dropout_cnn_out: Dropout rate for the output of the CNN
:param str cnn_model_name: Name of the CNN model from torchvision.models
:param bool pretrained_cnn: If True, the model will be loaded with pretrained weights
:param int embedded_size: Size of the input feature vectors
:param int nhead: Number of heads in the multi-head attention
:param int num_layers_transformer: number of transformer layers in the encoder
:param float positional_embeddings_dropout: Dropout rate for the positional embeddings
:param float dropout_transformer: dropout probability of transformer layers in the encoder
:param int sequence_size: Length of the input sequence
:param float dropout_encoder_features: Dropout probability of the encoder output
:param sequence_size: Length of the input sequence
"""
super(TEDD1104TransformerForImageReordering, self).__init__()
# Remember hyperparameters.
self.cnn_model_name: str = cnn_model_name
self.pretrained_cnn: bool = pretrained_cnn
self.sequence_size: int = sequence_size
self.embedded_size: int = embedded_size
self.nhead: int = nhead
self.num_layers_transformer: int = num_layers_transformer
self.dropout_cnn_out: float = dropout_cnn_out
self.positional_embeddings_dropout: float = positional_embeddings_dropout
self.dropout_transformer: float = dropout_transformer
self.dropout_encoder_features = dropout_encoder_features
self.EncoderCNN: EncoderCNN = EncoderCNN(
embedded_size=embedded_size,
dropout_cnn_out=dropout_cnn_out,
cnn_model_name=cnn_model_name,
pretrained_cnn=pretrained_cnn,
sequence_size=self.sequence_size,
)
self.PositionalEncoding = PositionalEmbedding(
d_model=embedded_size,
dropout=self.positional_embeddings_dropout,
sequence_length=self.sequence_size,
)
self.EncoderTransformer: EncoderTransformer = EncoderTransformer(
d_model=embedded_size,
nhead=nhead,
num_layers=num_layers_transformer,
dropout=self.dropout_transformer,
)
self.OutputLayer: OutputImageOrderingLayer = OutputImageOrderingLayer(
d_model=embedded_size,
num_classes=self.sequence_size,
)
def forward(
self, x: torch.tensor, attention_mask: torch.tensor = None
) -> torch.tensor:
"""
Forward pass
:param torch.tensor x: Input tensor of shape [batch_size * sequence_size, 3, 270, 480]
:param torch.tensor attention_mask: Mask for the input features
[batch_size*heads, sequence_length, sequence_length]
1 for masked positions and 0 for unmasked positions
:return: Output tensor of shape [9] if control_mode == "keyboard" or [2] if control_mode == "controller"
"""
x = self.EncoderCNN(x)
x = self.PositionalEncoding(x)
x = self.EncoderTransformer(x, attention_mask=attention_mask)
return self.OutputLayer(x)
class Tedd1104ModelPL(pl.LightningModule):
"""
Pytorch Lightning module for the Tedd1104Model
"""
def __init__(
self,
cnn_model_name: str,
pretrained_cnn: bool,
embedded_size: int,
nhead: int,
num_layers_encoder: int,
lstm_hidden_size: int,
dropout_cnn_out: float,
positional_embeddings_dropout: float,
dropout_encoder: float,
dropout_encoder_features: float = 0.8,
control_mode: str = "keyboard",
sequence_size: int = 5,
encoder_type: str = "transformer",
bidirectional_lstm=True,
weights: List[float] = None,
label_smoothing: float = 0.0,
accelerator: str = None,
optimizer_name: str = "adamw",
scheduler_name: str = "linear",
learning_rate: float = 1e-5,
weight_decay: float = 1e-3,
num_warmup_steps: int = 0,
num_training_steps: int = 0,
):
"""
INIT
:param int embedded_size: Size of the output embedding
:param float dropout_cnn_out: Dropout rate for the output of the CNN
:param str cnn_model_name: Name of the CNN model from torchvision.models
:param bool pretrained_cnn: If True, the model will be loaded with pretrained weights
:param int embedded_size: Size of the input feature vectors
:param int nhead: Number of heads in the multi-head attention
:param int num_layers_encoder: number of transformer layers in the encoder
:param float positional_embeddings_dropout: Dropout rate for the positional embeddings