-
Notifications
You must be signed in to change notification settings - Fork 1
/
basset.py
1230 lines (988 loc) · 49.9 KB
/
basset.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
import argparse
import sys
import math
from collections import OrderedDict
import torch
import torch.nn as nn
import lightning.pytorch as ptl
from ..common import utils
from .custom_layers import Conv1dNorm, LinearNorm, GroupedLinear, RepeatLayer, BranchedLinear
from .loss_functions import add_criterion_specific_args
from ..model import loss_functions
def get_padding(kernel_size):
"""
Calculate padding values for convolutional layers.
Args:
kernel_size (int): Size of the convolutional kernel.
Returns:
list: Padding values for left and right sides of the kernel.
"""
left = (kernel_size - 1) // 2
right= kernel_size - 1 - left
return [ max(0,x) for x in [left,right] ]
##################
# Models #
##################
class Basset(ptl.LightningModule):
"""
Basset model architecture.
Args:
conv1_channels (int): Number of output channels in the first convolutional layer.
conv1_kernel_size (int): Kernel size of the first convolutional layer.
conv2_channels (int): Number of output channels in the second convolutional layer.
conv2_kernel_size (int): Kernel size of the second convolutional layer.
conv3_channels (int): Number of output channels in the third convolutional layer.
conv3_kernel_size (int): Kernel size of the third convolutional layer.
linear1_channels (int): Number of output channels in the first linear layer.
linear2_channels (int): Number of output channels in the second linear layer.
n_outputs (int): Number of output classes.
activation (str): Activation function name.
dropout_p (float): Dropout probability.
use_batch_norm (bool): Whether to use batch normalization.
use_weight_norm (bool): Whether to use weight normalization.
loss_criterion (str): Loss criterion name.
Methods:
add_model_specific_args(parent_parser): Add model-specific arguments to the argument parser.
add_conditional_args(parser, known_args): Add conditional arguments based on known arguments.
process_args(grouped_args): Process grouped arguments and return model-specific arguments.
encode(x): Encode input through the Basset model's encoding layers.
decode(x): Decode encoded tensor through the Basset model's decoding layers.
classify(x): Classify decoded tensor using the Basset model's classification layer.
forward(x): Forward pass through the Basset model.
"""
#####################
# CLI staticmethods #
#####################
@staticmethod
def add_model_specific_args(parent_parser):
"""
Add model-specific arguments to the argument parser.
Args:
parent_parser (argparse.ArgumentParser): Parent argument parser.
Returns:
argparse.ArgumentParser: Argument parser with added model-specific arguments.
"""
parser = argparse.ArgumentParser(parents=[parent_parser], add_help=False)
group = parser.add_argument_group('Model Module args')
group.add_argument('--conv1_channels', type=int, default=300)
group.add_argument('--conv1_kernel_size', type=int, default=19)
group.add_argument('--conv2_channels', type=int, default=200)
group.add_argument('--conv2_kernel_size', type=int, default=11)
group.add_argument('--conv3_channels', type=int, default=200)
group.add_argument('--conv3_kernel_size', type=int, default=7)
group.add_argument('--linear1_channels', type=int, default=1000)
group.add_argument('--linear2_channels', type=int, default=1000)
group.add_argument('--n_outputs', type=int, default=280)
group.add_argument('--dropout_p', type=float, default=0.3)
group.add_argument('--use_batch_norm', type=utils.str2bool, default=True)
group.add_argument('--use_weight_norm',type=utils.str2bool, default=False)
group.add_argument('--loss_criterion',type=str, default='CrossEntropyLoss')
return parser
@staticmethod
def add_conditional_args(parser, known_args):
"""
Add conditional arguments based on known arguments.
Args:
parser (argparse.ArgumentParser): Argument parser.
known_args (Namespace): Namespace of known arguments.
Returns:
argparse.ArgumentParser: Argument parser with added conditional arguments.
"""
parser = add_criterion_specific_args(parser, known_args.loss_criterion)
return parser
@staticmethod
def process_args(grouped_args):
"""
Perform any required processessing of command line args required
before passing to the class constructor.
Args:
grouped_args (Namespace): Namespace of known arguments with
`'Model Module args'` key and conditionally added
`'Criterion args'` key.
Returns:
Namespace: A modified namespace that can be passed to the
associated class constructor.
"""
model_args = grouped_args['Model Module args']
model_args.loss_args = vars(grouped_args['Criterion args'])
return model_args
######################
# Model construction #
######################
def __init__(self, conv1_channels=300, conv1_kernel_size=19,
conv2_channels=200, conv2_kernel_size=11,
conv3_channels=200, conv3_kernel_size=7,
linear1_channels=1000, linear2_channels=1000,
n_outputs=280, activation='ReLU',
dropout_p=0.3, use_batch_norm=True, use_weight_norm=False,
loss_criterion='CrossEntropyLoss', loss_args={}):
"""
Initialize Basset model.
Args:
conv1_channels (int): Number of output channels in the first convolutional layer.
conv1_kernel_size (int): Kernel size of the first convolutional layer.
conv2_channels (int): Number of output channels in the second convolutional layer.
conv2_kernel_size (int): Kernel size of the second convolutional layer.
conv3_channels (int): Number of output channels in the third convolutional layer.
conv3_kernel_size (int): Kernel size of the third convolutional layer.
linear1_channels (int): Number of output channels in the first linear layer.
linear2_channels (int): Number of output channels in the second linear layer.
n_outputs (int): Number of output classes.
activation (str): Activation function name.
dropout_p (float): Dropout probability.
use_batch_norm (bool): Whether to use batch normalization.
use_weight_norm (bool): Whether to use weight normalization.
loss_criterion (str): Loss criterion name.
loss_args (dict): Dict of kwargs to construct loss with.
"""
super().__init__()
self.conv1_channels = conv1_channels
self.conv1_kernel_size = conv1_kernel_size
self.conv1_pad = get_padding(conv1_kernel_size)
self.conv2_channels = conv2_channels
self.conv2_kernel_size = conv2_kernel_size
self.conv2_pad = get_padding(conv2_kernel_size)
self.conv3_channels = conv3_channels
self.conv3_kernel_size = conv3_kernel_size
self.conv3_pad = get_padding(conv3_kernel_size)
self.linear1_channels = linear1_channels
self.linear2_channels = linear2_channels
self.n_outputs = n_outputs
self.activation = activation
self.dropout_p = dropout_p
self.use_batch_norm = use_batch_norm
self.use_weight_norm = use_weight_norm
self.loss_criterion = loss_criterion
self.loss_args = loss_args
self.pad1 = nn.ConstantPad1d(self.conv1_pad, 0.)
self.conv1 = Conv1dNorm(4,
self.conv1_channels, self.conv1_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad2 = nn.ConstantPad1d(self.conv2_pad, 0.)
self.conv2 = Conv1dNorm(self.conv1_channels,
self.conv2_channels, self.conv2_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad3 = nn.ConstantPad1d(self.conv3_pad, 0.)
self.conv3 = Conv1dNorm(self.conv2_channels,
self.conv3_channels, self.conv3_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad4 = nn.ConstantPad1d((1,1), 0.)
self.maxpool_3 = nn.MaxPool1d(3, padding=0)
self.maxpool_4 = nn.MaxPool1d(4, padding=0)
self.linear1 = LinearNorm(self.conv3_channels*13, self.linear1_channels,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.linear2 = LinearNorm(self.linear1_channels, self.linear2_channels,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.output = nn.Linear(self.linear2_channels, self.n_outputs)
self.nonlin = getattr(nn, self.activation)()
self.dropout = nn.Dropout(p=self.dropout_p)
self.criterion = getattr(loss_functions,self.loss_criterion) \
(**self.loss_args)
######################
# Model computations #
######################
def encode(self, x):
"""
Encode input through the Basset model's encoding layers.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Encoded tensor.
"""
hook = self.nonlin( self.conv1( self.pad1( x ) ) )
hook = self.maxpool_3( hook )
hook = self.nonlin( self.conv2( self.pad2( hook ) ) )
hook = self.maxpool_4( hook )
hook = self.nonlin( self.conv3( self.pad3( hook ) ) )
hook = self.maxpool_4( self.pad4( hook ) )
hook = torch.flatten( hook, start_dim=1 )
return hook
def decode(self, x):
"""
Decode encoded tensor through the Basset model's decoding layers.
Args:
x (torch.Tensor): Encoded tensor.
Returns:
torch.Tensor: Decoded tensor.
"""
hook = self.dropout( self.nonlin( self.linear1( x ) ) )
hook = self.dropout( self.nonlin( self.linear2( hook ) ) )
return hook
def classify(self, x):
"""
Classify decoded tensor using the Basset model's classification layer.
Args:
x (torch.Tensor): Decoded tensor.
Returns:
torch.Tensor: Classification output tensor.
"""
output = self.output( x )
return output
def forward(self, x):
"""
Forward pass through the Basset model.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
encoded = self.encode(x)
decoded = self.decode(encoded)
output = self.classify(decoded)
return output
class BassetVL(ptl.LightningModule):
"""
BassetVL (Variant of Basset with Variable Linear Layers) model architecture.
Args:
conv1_channels (int): Number of output channels in the first convolutional layer.
conv1_kernel_size (int): Kernel size of the first convolutional layer.
conv2_channels (int): Number of output channels in the second convolutional layer.
conv2_kernel_size (int): Kernel size of the second convolutional layer.
conv3_channels (int): Number of output channels in the third convolutional layer.
conv3_kernel_size (int): Kernel size of the third convolutional layer.
n_linear_layers (int): Number of linear layers.
linear_channels (int): Number of output channels in linear layers.
n_outputs (int): Number of output classes.
activation (str): Activation function name.
dropout_p (float): Dropout probability.
use_batch_norm (bool): Whether to use batch normalization.
use_weight_norm (bool): Whether to use weight normalization.
loss_criterion (str): Loss criterion name.
Methods:
add_model_specific_args(parent_parser): Add model-specific arguments to the argument parser.
add_conditional_args(parser, known_args): Add conditional arguments based on known arguments.
process_args(grouped_args): Process grouped arguments to extract model-specific arguments.
encode(x): Encode input through the BassetVL model's encoding layers.
decode(x): Decode encoded tensor through the BassetVL model's decoding layers.
classify(x): Classify decoded tensor using the BassetVL model's classification layer.
forward(x): Forward pass through the BassetVL model.
"""
#####################
# CLI staticmethods #
#####################
@staticmethod
def add_model_specific_args(parent_parser):
"""
Add model-specific arguments to the argument parser.
Args:
parent_parser (argparse.ArgumentParser): Parent argument parser.
Returns:
argparse.ArgumentParser: Argument parser with added model-specific arguments.
"""
parser = argparse.ArgumentParser(parents=[parent_parser], add_help=False)
group = parser.add_argument_group('Model Module args')
group.add_argument('--input_len', type=int, default=600)
group.add_argument('--conv1_channels', type=int, default=300)
group.add_argument('--conv1_kernel_size', type=int, default=19)
group.add_argument('--conv2_channels', type=int, default=200)
group.add_argument('--conv2_kernel_size', type=int, default=11)
group.add_argument('--conv3_channels', type=int, default=200)
group.add_argument('--conv3_kernel_size', type=int, default=7)
group.add_argument('--n_linear_layers', type=int, default=2)
group.add_argument('--linear_channels', type=int, default=1000)
group.add_argument('--linear_activation',type=str, default='ReLU')
group.add_argument('--linear_dropout_p', type=float, default=0.3)
group.add_argument('--n_outputs', type=int, default=280)
group.add_argument('--use_batch_norm', type=utils.str2bool, default=True)
group.add_argument('--use_weight_norm',type=utils.str2bool, default=False)
group.add_argument('--loss_criterion',type=str, default='CrossEntropyLoss')
return parser
@staticmethod
def add_conditional_args(parser, known_args):
"""
Add conditional arguments based on known arguments.
Args:
parser (argparse.ArgumentParser): Argument parser.
known_args (Namespace): Namespace of known arguments.
Returns:
argparse.ArgumentParser: Argument parser with added conditional arguments.
"""
parser = add_criterion_specific_args(parser, known_args.loss_criterion)
return parser
@staticmethod
def process_args(grouped_args):
"""
Perform any required processessing of command line args required
before passing to the class constructor.
Args:
grouped_args (Namespace): Namespace of known arguments with
`'Model Module args'` key and conditionally added
`'Criterion args'` key.
Returns:
Namespace: A modified namespace that can be passed to the
associated class constructor.
"""
model_args = grouped_args['Model Module args']
model_args.loss_args = vars(grouped_args['Criterion args'])
return model_args
######################
# Model construction #
######################
def __init__(self, input_len=600,
conv1_channels=300, conv1_kernel_size=19,
conv2_channels=200, conv2_kernel_size=11,
conv3_channels=200, conv3_kernel_size=7,
n_linear_layers=2, linear_channels=1000,
linear_activation='ReLU', linear_dropout_p=0.3,
n_outputs=280,
use_batch_norm=True, use_weight_norm=False,
loss_criterion='MSELoss', loss_args={}):
"""
Initialize BassetVL model.
Args:
conv1_channels (int): Number of output channels in the first convolutional layer.
conv1_kernel_size (int): Kernel size of the first convolutional layer.
conv2_channels (int): Number of output channels in the second convolutional layer.
conv2_kernel_size (int): Kernel size of the second convolutional layer.
conv3_channels (int): Number of output channels in the third convolutional layer.
conv3_kernel_size (int): Kernel size of the third convolutional layer.
n_linear_layers (int): Number of linear layers.
linear_channels (int): Number of output channels in linear layers.
n_outputs (int): Number of output classes.
linear_activation (str): Activation function name.
linear_dropout_p (float): Dropout probability.
use_batch_norm (bool): Whether to use batch normalization.
use_weight_norm (bool): Whether to use weight normalization.
loss_criterion (str): Loss criterion name.
"""
super().__init__()
self.input_len = input_len
self.conv1_channels = conv1_channels
self.conv1_kernel_size = conv1_kernel_size
self.conv1_pad = get_padding(conv1_kernel_size)
self.conv2_channels = conv2_channels
self.conv2_kernel_size = conv2_kernel_size
self.conv2_pad = get_padding(conv2_kernel_size)
self.conv3_channels = conv3_channels
self.conv3_kernel_size = conv3_kernel_size
self.conv3_pad = get_padding(conv3_kernel_size)
self.n_linear_layers = n_linear_layers
self.linear_channels = linear_channels
self.n_outputs = n_outputs
self.linear_activation = linear_activation
self.linear_dropout_p = linear_dropout_p
self.use_batch_norm = use_batch_norm
self.use_weight_norm = use_weight_norm
self.loss_criterion = loss_criterion
self.loss_args = loss_args
self.pad1 = nn.ConstantPad1d(self.conv1_pad, 0.)
self.conv1 = Conv1dNorm(4,
self.conv1_channels, self.conv1_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad2 = nn.ConstantPad1d(self.conv2_pad, 0.)
self.conv2 = Conv1dNorm(self.conv1_channels,
self.conv2_channels, self.conv2_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad3 = nn.ConstantPad1d(self.conv3_pad, 0.)
self.conv3 = Conv1dNorm(self.conv2_channels,
self.conv3_channels, self.conv3_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad4 = nn.ConstantPad1d((1,1), 0.)
self.maxpool_3 = nn.MaxPool1d(3, padding=0)
self.maxpool_4 = nn.MaxPool1d(4, padding=0)
next_in_channels = self.conv3_channels * self.get_flatten_factor(self.input_len)
for i in range(self.n_linear_layers):
setattr(self, f'linear{i+1}',
LinearNorm(next_in_channels, self.linear_channels,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
)
next_in_channels = self.linear_channels
self.output = nn.Linear(next_in_channels, self.n_outputs)
self.nonlin = getattr(nn, self.linear_activation)()
self.dropout = nn.Dropout(p=self.linear_dropout_p)
self.criterion = getattr(loss_functions,self.loss_criterion) \
(**self.loss_args)
def get_flatten_factor(self, input_len):
hook = input_len
assert hook % 3 == 0
hook = hook // 3
assert hook % 4 == 0
hook = hook // 4
assert (hook + 2) % 4 == 0
return (hook + 2) // 4
######################
# Model computations #
######################
def encode(self, x):
"""
Encode input through the BassetVL model's encoding layers.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Encoded tensor.
"""
hook = self.nonlin( self.conv1( self.pad1( x ) ) )
hook = self.maxpool_3( hook )
hook = self.nonlin( self.conv2( self.pad2( hook ) ) )
hook = self.maxpool_4( hook )
hook = self.nonlin( self.conv3( self.pad3( hook ) ) )
hook = self.maxpool_4( self.pad4( hook ) )
hook = torch.flatten( hook, start_dim=1 )
return hook
def decode(self, x):
"""
Decode encoded tensor through the BassetVL model's decoding layers.
Args:
x (torch.Tensor): Encoded tensor.
Returns:
torch.Tensor: Decoded tensor.
"""
hook = x
for i in range(self.n_linear_layers):
hook = self.dropout(
self.nonlin(
getattr(self,f'linear{i+1}')(hook)
)
)
return hook
def classify(self, x):
"""
Classify decoded tensor using the BassetVL model's classification layer.
Args:
x (torch.Tensor): Decoded tensor.
Returns:
torch.Tensor: Classification output tensor.
"""
output = self.output( x )
return output
def forward(self, x):
"""
Forward pass through the BassetVL model.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
encoded = self.encode(x)
decoded = self.decode(encoded)
output = self.classify(decoded)
return output
class BassetEntropyVL(ptl.LightningModule):
"""
Deprecated, redundant to updated BassetVL.
A custom LightningModule implementing the Basset model with entropy-based loss and variation loss.
Args:
conv1_channels (int): Number of channels in the first convolutional layer.
conv1_kernel_size (int): Kernel size of the first convolutional layer.
conv2_channels (int): Number of channels in the second convolutional layer.
conv2_kernel_size (int): Kernel size of the second convolutional layer.
conv3_channels (int): Number of channels in the third convolutional layer.
conv3_kernel_size (int): Kernel size of the third convolutional layer.
n_linear_layers (int): Number of linear layers in the model.
linear_channels (int): Number of channels in the linear layers.
n_outputs (int): Number of output units.
activation (str): Activation function to use.
dropout_p (float): Dropout probability applied to hidden layers.
use_batch_norm (bool): Whether to use batch normalization.
use_weight_norm (bool): Whether to use weight normalization.
criterion_reduction (str): Reduction method for the combined loss.
mse_scale (float): Scale factor for the MSE loss.
kl_scale (float): Scale factor for the KL loss.
Methods:
add_model_specific_args(parent_parser): Add model-specific arguments to the provided argparse ArgumentParser.
add_conditional_args(parser, known_args): Add conditional model-specific arguments based on known arguments.
process_args(grouped_args): Process grouped arguments and extract model-specific arguments.
forward(x): Perform forward pass through the BassetEntropyVL model.
encode(x): Encode input data through the convolutional layers.
decode(x): Decode encoded data through the linear layers.
classify(x): Generate model predictions from decoded data.
Example:
model = BassetEntropyVL(conv1_channels=300, conv1_kernel_size=19,
conv2_channels=200, conv2_kernel_size=11,
conv3_channels=200, conv3_kernel_size=7,
n_linear_layers=2, linear_channels=1000,
n_outputs=280, activation='ReLU',
dropout_p=0.3, use_batch_norm=True, use_weight_norm=False,
criterion_reduction='mean', mse_scale=1.0, kl_scale=1.0)
output = model(input_tensor)
"""
#####################
# CLI staticmethods #
#####################
@staticmethod
def add_model_specific_args(parent_parser):
"""
Add model-specific arguments to the argument parser.
Args:
parent_parser (argparse.ArgumentParser): Parent argument parser.
Returns:
argparse.ArgumentParser: Argument parser with added model-specific arguments.
"""
parser = argparse.ArgumentParser(parents=[parent_parser], add_help=False)
group = parser.add_argument_group('Model Module args')
group.add_argument('--conv1_channels', type=int, default=300)
group.add_argument('--conv1_kernel_size', type=int, default=19)
group.add_argument('--conv2_channels', type=int, default=200)
group.add_argument('--conv2_kernel_size', type=int, default=11)
group.add_argument('--conv3_channels', type=int, default=200)
group.add_argument('--conv3_kernel_size', type=int, default=7)
group.add_argument('--n_linear_layers', type=int, default=2)
group.add_argument('--linear_channels', type=int, default=1000)
group.add_argument('--n_outputs', type=int, default=280)
group.add_argument('--dropout_p', type=float, default=0.3)
group.add_argument('--use_batch_norm', type=utils.str2bool, default=True)
group.add_argument('--use_weight_norm',type=utils.str2bool, default=False)
group.add_argument('--criterion_reduction', type=str, default='mean')
group.add_argument('--mse_scale', type=float, default=1.0)
group.add_argument('--kl_scale', type=float, default=1.0)
return parser
@staticmethod
def add_conditional_args(parser, known_args):
"""
Add conditional model-specific arguments based on known arguments.
Args:
parser (argparse.ArgumentParser): Argument parser to which conditional arguments will be added.
known_args (Namespace): Namespace containing known arguments.
Returns:
argparse.ArgumentParser: Argument parser with added conditional arguments.
"""
return parser
@staticmethod
def process_args(grouped_args):
"""
Process grouped arguments and extract model-specific arguments.
Args:
grouped_args (dict): Dictionary of grouped arguments.
Returns:
dict: Model-specific arguments extracted from grouped_args.
"""
model_args = grouped_args['Model Module args']
return model_args
######################
# Model construction #
######################
def __init__(self, conv1_channels=300, conv1_kernel_size=19,
conv2_channels=200, conv2_kernel_size=11,
conv3_channels=200, conv3_kernel_size=7,
n_linear_layers=2, linear_channels=1000,
n_outputs=280, activation='ReLU',
dropout_p=0.3, use_batch_norm=True, use_weight_norm=False,
criterion_reduction='mean', mse_scale=1.0, kl_scale=1.0):
"""
Initialize the BassetEntropyVL module.
Args:
conv1_channels (int): Number of channels in the first convolutional layer.
conv1_kernel_size (int): Kernel size of the first convolutional layer.
conv2_channels (int): Number of channels in the second convolutional layer.
conv2_kernel_size (int): Kernel size of the second convolutional layer.
conv3_channels (int): Number of channels in the third convolutional layer.
conv3_kernel_size (int): Kernel size of the third convolutional layer.
n_linear_layers (int): Number of linear layers in the model.
linear_channels (int): Number of channels in the linear layers.
n_outputs (int): Number of output units.
activation (str): Activation function to use.
dropout_p (float): Dropout probability applied to hidden layers.
use_batch_norm (bool): Whether to use batch normalization.
use_weight_norm (bool): Whether to use weight normalization.
criterion_reduction (str): Reduction method for the combined loss.
mse_scale (float): Scale factor for the MSE loss.
kl_scale (float): Scale factor for the KL loss.
Returns:
None
"""
super().__init__()
self.conv1_channels = conv1_channels
self.conv1_kernel_size = conv1_kernel_size
self.conv1_pad = get_padding(conv1_kernel_size)
self.conv2_channels = conv2_channels
self.conv2_kernel_size = conv2_kernel_size
self.conv2_pad = get_padding(conv2_kernel_size)
self.conv3_channels = conv3_channels
self.conv3_kernel_size = conv3_kernel_size
self.conv3_pad = get_padding(conv3_kernel_size)
self.n_linear_layers = n_linear_layers
self.linear_channels = linear_channels
self.n_outputs = n_outputs
self.activation = activation
self.dropout_p = dropout_p
self.use_batch_norm = use_batch_norm
self.use_weight_norm = use_weight_norm
self.criterion_reduction=criterion_reduction
self.mse_scale = mse_scale
self.kl_scale = kl_scale
self.pad1 = nn.ConstantPad1d(self.conv1_pad, 0.)
self.conv1 = Conv1dNorm(4,
self.conv1_channels, self.conv1_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad2 = nn.ConstantPad1d(self.conv2_pad, 0.)
self.conv2 = Conv1dNorm(self.conv1_channels,
self.conv2_channels, self.conv2_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad3 = nn.ConstantPad1d(self.conv3_pad, 0.)
self.conv3 = Conv1dNorm(self.conv2_channels,
self.conv3_channels, self.conv3_kernel_size,
stride=1, padding=0, dilation=1, groups=1,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
self.pad4 = nn.ConstantPad1d((1,1), 0.)
self.maxpool_3 = nn.MaxPool1d(3, padding=0)
self.maxpool_4 = nn.MaxPool1d(4, padding=0)
next_in_channels = self.conv3_channels*13
for i in range(self.n_linear_layers):
setattr(self, f'linear{i+1}',
LinearNorm(next_in_channels, self.linear_channels,
bias=True,
batch_norm=self.use_batch_norm,
weight_norm=self.use_weight_norm)
)
next_in_channels = self.linear_channels
self.output = nn.Linear(next_in_channels, self.n_outputs)
self.nonlin = getattr(nn, self.activation)()
self.dropout = nn.Dropout(p=self.dropout_p)
self.criterion = MSEKLmixed(reduction=self.criterion_reduction,
mse_scale=self.mse_scale,
kl_scale =self.kl_scale)
######################
# Model computations #
######################
def encode(self, x):
"""
Encode input data through the convolutional layers.
Args:
x (Tensor): The input tensor.
Returns:
Tensor: Encoded tensor.
"""
hook = self.nonlin( self.conv1( self.pad1( x ) ) )
hook = self.maxpool_3( hook )
hook = self.nonlin( self.conv2( self.pad2( hook ) ) )
hook = self.maxpool_4( hook )
hook = self.nonlin( self.conv3( self.pad3( hook ) ) )
hook = self.maxpool_4( self.pad4( hook ) )
hook = torch.flatten( hook, start_dim=1 )
return hook
def decode(self, x):
"""
Decode encoded data through the linear layers.
Args:
x (Tensor): The encoded tensor.
Returns:
Tensor: Decoded tensor.
"""
hook = x
for i in range(self.n_linear_layers):
hook = self.dropout(
self.nonlin(
getattr(self,f'linear{i+1}')(hook)
)
)
return hook
def classify(self, x):
"""
Generate model predictions from decoded data.
Args:
x (Tensor): The decoded tensor.
Returns:
Tensor: Model predictions.
"""
output = self.output( x )
return output
def forward(self, x):
"""
Perform forward pass through the BassetEntropyVL model.
Args:
x (Tensor): The input tensor.
Returns:
Tensor: Model predictions.
"""
encoded = self.encode(x)
decoded = self.decode(encoded)
output = self.classify(decoded)
return output
class BassetBranched(ptl.LightningModule):
"""
A PyTorch Lightning module representing the BassetBranched model.
Args:
input_len (int): Fixed sequence length of inputs.
conv1_channels (int): Number of channels for the first convolutional layer.
conv1_kernel_size (int): Kernel size for the first convolutional layer.
conv2_channels (int): Number of channels for the second convolutional layer.
conv2_kernel_size (int): Kernel size for the second convolutional layer.
conv3_channels (int): Number of channels for the third convolutional layer.
conv3_kernel_size (int): Kernel size for the third convolutional layer.
n_linear_layers (int): Number of linear (fully connected) layers.
linear_channels (int): Number of channels in linear layers.
linear_activation (str): Activation function for linear layers (default: 'ReLU').
linear_dropout_p (float): Dropout probability for linear layers (default: 0.3).
n_branched_layers (int): Number of branched linear layers.
branched_channels (int): Number of output channels for branched layers.
branched_activation (str): Activation function for branched layers (default: 'ReLU6').
branched_dropout_p (float): Dropout probability for branched layers (default: 0.0).
n_outputs (int): Number of output units.
loss_criterion (str): Loss criterion class name (default: 'MSEKLmixed').
criterion_reduction (str): Reduction type for loss criterion (default: 'mean').
mse_scale (float): Scale factor for MSE loss component (default: 1.0).
kl_scale (float): Scale factor for KL divergence loss component (default: 1.0).
use_batch_norm (bool): Use batch normalization (default: True).
use_weight_norm (bool): Use weight normalization (default: False).
Methods:
add_model_specific_args(parent_parser): Add model-specific arguments to the provided argparse ArgumentParser.
add_conditional_args(parser, known_args): Add conditional model-specific arguments based on known arguments.
process_args(grouped_args): Process grouped arguments and extract model-specific arguments.
encode(x): Encode input data through the model's encoder layers.
decode(x): Decode encoded data through the model's linear and branched layers.
classify(x): Classify data using the output layer.
forward(x): Forward pass through the entire model.
"""
#####################
# CLI staticmethods #
#####################
@staticmethod
def add_model_specific_args(parent_parser):
"""
Add model-specific arguments to the provided argparse ArgumentParser.
Args:
parent_parser (argparse.ArgumentParser): The parent ArgumentParser.
Returns:
argparse.ArgumentParser: The ArgumentParser with added model-specific arguments.
"""
parser = argparse.ArgumentParser(parents=[parent_parser], add_help=False)
group = parser.add_argument_group('Model Module args')
group.add_argument('--input_len', type=int, default=600)
group.add_argument('--conv1_channels', type=int, default=300)
group.add_argument('--conv1_kernel_size', type=int, default=19)
group.add_argument('--conv2_channels', type=int, default=200)
group.add_argument('--conv2_kernel_size', type=int, default=11)
group.add_argument('--conv3_channels', type=int, default=200)
group.add_argument('--conv3_kernel_size', type=int, default=7)
group.add_argument('--n_linear_layers', type=int, default=2)
group.add_argument('--linear_channels', type=int, default=1000)
group.add_argument('--linear_activation',type=str, default='ReLU')
group.add_argument('--linear_dropout_p', type=float, default=0.3)
group.add_argument('--n_branched_layers', type=int, default=1)
group.add_argument('--branched_channels', type=int, default=1000)
group.add_argument('--branched_activation',type=str, default='ReLU')
group.add_argument('--branched_dropout_p', type=float, default=0.3)
group.add_argument('--n_outputs', type=int, default=280)
group.add_argument('--use_batch_norm', type=utils.str2bool, default=True)
group.add_argument('--use_weight_norm',type=utils.str2bool, default=False)
group.add_argument('--loss_criterion', type=str, default='L1KLmixed')
return parser
@staticmethod
def add_conditional_args(parser, known_args):
"""
Add conditional arguments based on known arguments.
Args:
parser (argparse.ArgumentParser): Argument parser.
known_args (Namespace): Namespace of known arguments.
Returns:
argparse.ArgumentParser: Argument parser with added conditional arguments.
"""
parser = add_criterion_specific_args(parser, known_args.loss_criterion)
return parser