biplab2008 commited on
Commit
832a5e2
·
verified ·
1 Parent(s): 29e2a42

Upload model_for_huggingface.py

Browse files
Files changed (1) hide show
  1. model_for_huggingface.py +263 -0
model_for_huggingface.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import NamedTuple, List, Callable, List, Tuple, Optional
2
+ import torch
3
+ from torch import nn
4
+ import torch.nn.functional as F
5
+
6
+ class LinData(NamedTuple):
7
+ in_dim : int # input dimension
8
+ hidden_layers : List[int] # hidden layers including the output layer
9
+ activations : List[Optional[Callable[[torch.Tensor],torch.Tensor]]] # list of activations
10
+ bns : List[bool] # list of bools
11
+ dropouts : List[Optional[float]] # list of dropouts probas
12
+
13
+ class CNNData(NamedTuple):
14
+ in_dim : int # input dimension
15
+ n_f : List[int] # num filters
16
+ kernel_size : List[Tuple] # kernel size [(5,5,5), (3,3,3),(3,3,3)]
17
+ activations : List[Optional[Callable[[torch.Tensor],torch.Tensor]]] # activation list
18
+ bns : List[bool] # batch normialization [True, True, False]
19
+ dropouts : List[Optional[float]] # # list of dropouts probas [.5,0,0]
20
+ #dropouts_ps : list # [0.5,.7, 0]
21
+ paddings : List[Optional[Tuple]] #[(0,0,0),(0,0,0), (0,0,0)]
22
+ strides : List[Optional[Tuple]] #[(1,1,1),(1,1,1),(1,1,1)]
23
+
24
+
25
+ class NetData(NamedTuple):
26
+ cnn3d : CNNData
27
+ lin : LinData
28
+
29
+
30
+
31
+
32
+
33
+ class CNN3D_Mike(nn.Module):
34
+ def __init__(self, t_dim=30, img_x=256 , img_y=342, drop_p=0, fc_hidden1=256, fc_hidden2=256):
35
+ super(CNN3D_Mike, self).__init__() # set video dimension
36
+ self.t_dim = t_dim
37
+ self.img_x = img_x
38
+ self.img_y = img_y
39
+ # fully connected layer hidden nodes
40
+ self.fc_hidden1, self.fc_hidden2 = fc_hidden1, fc_hidden2
41
+ self.drop_p = drop_p
42
+ #self.num_classes = num_classes
43
+ self.ch1, self.ch2 = 32, 48
44
+ self.k1, self.k2 = (5, 5, 5), (3, 3, 3) # 3d kernel size
45
+ self.s1, self.s2 = (2, 2, 2), (2, 2, 2) # 3d strides
46
+ self.pd1, self.pd2 = (0, 0, 0), (0, 0, 0) # 3d padding # compute conv1 & conv2 output shape
47
+ self.conv1_outshape = conv3D_output_size((self.t_dim, self.img_x, self.img_y), self.pd1, self.k1, self.s1)
48
+ self.conv2_outshape = conv3D_output_size(self.conv1_outshape, self.pd2, self.k2, self.s2)
49
+ self.conv1 = nn.Conv3d(in_channels=1, out_channels=self.ch1, kernel_size=self.k1, stride=self.s1,
50
+ padding=self.pd1)
51
+ self.bn1 = nn.BatchNorm3d(self.ch1)
52
+ self.conv2 = nn.Conv3d(in_channels=self.ch1, out_channels=self.ch2, kernel_size=self.k2, stride=self.s2,
53
+ padding=self.pd2)
54
+ self.bn2 = nn.BatchNorm3d(self.ch2)
55
+ self.relu = nn.ReLU(inplace=True)
56
+ self.drop = nn.Dropout3d(self.drop_p)
57
+ self.pool = nn.MaxPool3d(2)
58
+ self.fc1 = nn.Linear(self.ch2*self.conv2_outshape[0]*self.conv2_outshape[1]*self.conv2_outshape[2],
59
+ self.fc_hidden1) # fully connected hidden layer
60
+ self.fc2 = nn.Linear(self.fc_hidden1, self.fc_hidden2)
61
+ self.fc3 = nn.Linear(self.fc_hidden2,1) # fully connected layer, output = multi-classes
62
+
63
+
64
+ def forward(self, x_3d):
65
+ # Conv 1
66
+ x = self.conv1(x_3d)
67
+
68
+ x = self.bn1(x)
69
+ x = self.relu(x)
70
+ x = self.drop(x)
71
+ # Conv 2
72
+ x = self.conv2(x)
73
+ x = self.bn2(x)
74
+ x = self.relu(x)
75
+ x = self.drop(x)
76
+ # FC 1 and 2
77
+ x = x.view(x.size(0), -1)
78
+ x = F.relu(self.fc1(x))
79
+ x = F.relu(self.fc2(x))
80
+
81
+ #x = F.relu(self.fc3(x))
82
+ #x = F.relu(self.fc3(x))
83
+ x = F.dropout(x, p=self.drop_p, training=self.training)
84
+ #x = self.fc3(x)
85
+ #x = F.softmax(self.fc2(x))
86
+
87
+ x = self.fc3(x)
88
+
89
+
90
+
91
+ return x
92
+
93
+
94
+
95
+ class CNNLayers(nn.Module):
96
+
97
+ def __init__(self, args):
98
+
99
+ super(CNNLayers, self).__init__()
100
+
101
+ self.in_dim = args.in_dim# 1/3
102
+ self.n_f = args.n_f#[32,64]
103
+ self.kernel_size = args.kernel_size # [(5,5,5), (3,3,3)]
104
+ self.activations = args.activations#['relu', 'relu']
105
+ self.bns = args.bns #[True, True],
106
+ self.dropouts = args.dropouts #[True, True]
107
+ #self.dropouts_ps = args.dropouts_ps#[0.5,.7]
108
+ self.paddings = args.paddings #[(0,0,0),(0,0,0)]
109
+ self.strides = args.strides # strides [(1,1,1),(1,1,1),(1,1,1)])
110
+ #self.poolings = args.poolings
111
+
112
+ assert len(self.n_f) == len(self.activations) == len(self.bns) == len(self.dropouts), 'dimensions mismatch : check dimensions!'
113
+
114
+ # generate layers seq of seq
115
+ self._get_layers()
116
+
117
+ def _get_layers(self):
118
+
119
+ layers =nn.ModuleList()
120
+ in_channels = self.in_dim
121
+
122
+ for idx, chans in enumerate(self.n_f):
123
+ sub_layers = nn.ModuleList()
124
+
125
+ sub_layers.append(nn.Conv3d(in_channels = in_channels,
126
+ out_channels = chans, #self.n_f[idx],
127
+ kernel_size = self.kernel_size[idx],
128
+ stride = self.strides[idx],
129
+ padding = self.paddings[idx]
130
+ ))
131
+
132
+
133
+
134
+ if self.bns[idx] : sub_layers.append(nn.BatchNorm3d(num_features = self.n_f[idx]))
135
+
136
+ #if self.dropouts[idx] : sub_layers.append(nn.Dropout3d(p = self.dropouts_ps[idx]))
137
+
138
+ if self.dropouts[idx] : sub_layers.append(nn.Dropout3d(p = self.dropouts[idx]))
139
+
140
+ #if self.activations[idx] : sub_layers.append(self.__class__.get_activation(self.activations[idx]))
141
+
142
+ if self.activations[idx] : sub_layers.append(self.activations[idx])
143
+
144
+ sub_layers = nn.Sequential(*sub_layers)
145
+
146
+ layers.append(sub_layers)
147
+
148
+ in_channels = self.n_f[idx]
149
+
150
+ self.layers = nn.Sequential(*layers)
151
+
152
+
153
+ @staticmethod
154
+ def get_activation(activation):
155
+ if activation == 'relu':
156
+ activation=nn.ReLU()
157
+ elif activation == 'leakyrelu':
158
+ activation=nn.LeakyReLU(negative_slope=0.1)
159
+ elif activation == 'selu':
160
+ activation=nn.SELU()
161
+
162
+ return activation
163
+
164
+
165
+
166
+ def forward(self, x):
167
+
168
+ x = self.layers(x)
169
+
170
+ return x
171
+
172
+
173
+
174
+ class CNN3D(nn.Module):
175
+
176
+ def __init__(self, args):
177
+ super(CNN3D,self).__init__()
178
+ # check datatype
179
+ if not isinstance(args, NetData):
180
+ raise TypeError("input must be a ParserClass")
181
+
182
+ self.cnn3d = CNNLayers(args.cnn3d)
183
+
184
+ self.lin = LinLayers(args.lin)
185
+
186
+ self.in_dim = args.lin.in_dim
187
+
188
+
189
+ def forward(self, x):
190
+
191
+ # cnn 3d
192
+ x = self.cnn3d(x)
193
+
194
+ x = x.view(-1, self.in_dim)
195
+
196
+ # feedforward
197
+ x = self.lin(x)
198
+
199
+ return x
200
+
201
+
202
+
203
+
204
+ class LinLayers(nn.Module):
205
+
206
+ def __init__(self, args):
207
+ super(LinLayers,self).__init__()
208
+
209
+ in_dim= args.in_dim #16,
210
+ hidden_layers= args.hidden_layers #[512,256,128,2],
211
+ activations=args.activations#[nn.LeakyReLU(0.2),nn.LeakyReLU(0.2),nn.LeakyReLU(0.2)],
212
+ batchnorms=args.bns#[True,True,True],
213
+ dropouts = args.dropouts#[None, 0.2, 0.2]
214
+
215
+
216
+ assert len(hidden_layers) == len(activations) == len(batchnorms) == len(dropouts), 'dimensions mismatch!'
217
+
218
+
219
+ layers=nn.ModuleList()
220
+
221
+ if hidden_layers:
222
+ old_dim=in_dim
223
+ for idx,layer in enumerate(hidden_layers):
224
+ sub_layers = nn.ModuleList()
225
+ sub_layers.append(nn.Linear(old_dim,layer))
226
+ if batchnorms[idx] : sub_layers.append(nn.BatchNorm1d(num_features=layer))
227
+ if activations[idx] : sub_layers.append(activations[idx])
228
+ if dropouts[idx] : sub_layers.append(nn.Dropout(p=dropouts[idx]))
229
+ old_dim = layer
230
+
231
+ sub_layers = nn.Sequential(*sub_layers)
232
+
233
+ layers.append(sub_layers)
234
+
235
+
236
+
237
+ else:# for single layer
238
+ layers.append(nn.Linear(in_dim,out_dim))
239
+ if batchnorms : layers.append(nn.BatchNorm1d(num_features=out_dim))
240
+ if activations : layers.append(activations)
241
+ if dropouts : layers.append(nn.Dropout(p=dropouts))
242
+
243
+ self.layers = nn.Sequential(*layers)
244
+
245
+
246
+
247
+ def forward(self,x):
248
+
249
+ x = self.layers(x)
250
+
251
+ return x
252
+
253
+ '''
254
+ def _check_dimensions(self):
255
+ if isinstance(self.hidden_layers,list) :
256
+ assert len(self.hidden_layers)==len(self.activations)
257
+ assert len(self.hidden_layers)==len(self.batchnorms)
258
+ assert len(self.hidden_layers)==len(self.dropouts)
259
+ '''
260
+
261
+
262
+
263
+