-
Notifications
You must be signed in to change notification settings - Fork 8
/
rome_losses.py
1866 lines (1591 loc) · 82.7 KB
/
rome_losses.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 torch
from torch import nn
from torch.nn import functional as F
from typing import List
class AdversarialLoss(nn.Module):
def __init__(self, loss_type = 'hinge'):
super(AdversarialLoss, self).__init__()
# TODO: different adversarial loss types
self.loss_type = loss_type
def forward(self,
fake_scores: List[List[torch.Tensor]],
real_scores: List[List[torch.Tensor]] = None,
mode: str = 'gen') -> torch.Tensor:
"""
scores: a list of lists of scores (the second layer corresponds to a
separate input to each of these discriminators)
"""
loss = 0
if mode == 'dis':
for real_scores_net, fake_scores_net in zip(real_scores, fake_scores):
# *_scores_net corresponds to outputs of a separate discriminator
loss_real = 0
for real_scores_net_i in real_scores_net:
if self.loss_type == 'hinge':
loss_real += torch.relu(1.0 - real_scores_net_i).mean()
else:
raise # not implemented
loss_real /= len(real_scores_net)
loss_fake = 0
for fake_scores_net_i in fake_scores_net:
if self.loss_type == 'hinge':
loss_fake += torch.relu(1.0 + fake_scores_net_i).mean()
else:
raise # not implemented
loss_fake /= len(fake_scores_net)
loss_net = loss_real + loss_fake
loss += loss_net
elif mode == 'gen':
for fake_scores_net in fake_scores:
assert isinstance(fake_scores_net, list), 'Expect a list of fake scores per discriminator'
loss_net = 0
for fake_scores_net_i in fake_scores_net:
if self.loss_type == 'hinge':
# *_scores_net_i corresponds to outputs for separate inputs
loss_net -= fake_scores_net_i.mean()
else:
raise # not implemented
loss_net /= len(fake_scores_net) # normalize by the number of inputs
loss += loss_net
loss /= len(fake_scores) # normalize by the nubmer of discriminators
return loss
import torch
class PSNR(object):
def __call__(self, y_pred, y_true):
"""
args:
y_true : 4-d ndarray in [batch_size, channels, img_rows, img_cols]
y_pred : 4-d ndarray in [batch_size, channels, img_rows, img_cols]
threshold : [0.0, 1.0]
return PSNR, larger the better
"""
mse = ((y_pred - y_true) ** 2).mean()
return 10 * torch.log10(1 / mse)
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import grad
# try:
# from pytorch3d.loss.mesh_laplacian_smoothing import cot_laplacian
# except:
# from pytorch3d.loss.mesh_laplacian_smoothing import laplacian_cot as cot_laplacian
def make_grid(h, w, device, dtype):
grid_x = torch.linspace(-1, 1, w, device=device, dtype=dtype)
grid_y = torch.linspace(-1, 1, h, device=device, dtype=dtype)
v, u = torch.meshgrid(grid_y, grid_x)
grid = torch.stack([u, v], dim=2).view(1, h * w, 2)
return grid
class Transform(nn.Module):
def __init__(self, sigma_affine, sigma_tps, points_tps):
super(Transform, self).__init__()
self.sigma_affine = sigma_affine
self.sigma_tps = sigma_tps
self.points_tps = points_tps
def transform_img(self, img):
b, _, h, w = img.shape
device = img.device
dtype = img.dtype
if not hasattr(self, 'identity_grid'):
identity_grid = make_grid(h, w, device, dtype)
self.register_buffer('identity_grid', identity_grid, persistent=False)
if not hasattr(self, 'control_grid'):
control_grid = make_grid(self.points_tps, self.points_tps, device, dtype)
self.register_buffer('control_grid', control_grid, persistent=False)
# Sample transform
noise = torch.normal(
mean=0,
std=self.sigma_affine,
size=(b, 2, 3),
device=device,
dtype=dtype)
self.theta = (noise + torch.eye(2, 3, device=device, dtype=dtype)[None])[:, None] # b x 1 x 2 x 3
self.control_params = torch.normal(
mean=0,
std=self.sigma_tps,
size=(b, 1, self.points_tps ** 2),
device=device,
dtype=dtype)
grid = self.warp_pts(self.identity_grid).view(-1, h, w, 2)
return F.grid_sample(img, grid, padding_mode="reflection")
def warp_pts(self, pts):
b = self.theta.shape[0]
n = pts.shape[1]
pts_transformed = torch.matmul(self.theta[:, :, :, :2], pts[..., None]) + self.theta[:, :, :, 2:]
pts_transformed = pts_transformed[..., 0]
pdists = pts[:, :, None] - self.control_grid[:, None]
pdists = (pdists).abs().sum(dim=3)
result = pdists**2 * torch.log(pdists + 1e-5) * self.control_params
result = result.sum(dim=2).view(b, n, 1)
pts_transformed = pts_transformed + result
return pts_transformed
def jacobian(self, pts):
new_pts = self.warp_pts(pts)
grad_x = grad(new_pts[..., 0].sum(), pts, create_graph=True)
grad_y = grad(new_pts[..., 1].sum(), pts, create_graph=True)
jac = torch.cat([grad_x[0].unsqueeze(-2), grad_y[0].unsqueeze(-2)], dim=-2)
return jac
class EquivarianceLoss(nn.Module):
def __init__(self, sigma_affine, sigma_tps, points_tps):
super(EquivarianceLoss, self).__init__()
self.transform = Transform(sigma_affine, sigma_tps, points_tps)
def forward(self, img, kp, jac, kp_detector):
img_transformed = self.transform.transform_img(img)
kp_transformed, jac_transformed = kp_detector(img_transformed)
kp_recon = self.transform.warp_pts(kp_transformed)
loss_kp = (kp - kp_recon).abs().mean()
jac_recon = torch.matmul(self.transform.jacobian(kp_transformed), jac_transformed)
inv_jac = torch.linalg.inv(jac)
loss_jac = (torch.matmul(inv_jac, jac_recon) - torch.eye(2)[None, None].type(inv_jac.type())).abs().mean()
return loss_kp, loss_jac, img_transformed, kp_transformed, kp_recon
class LaplaceMeshLoss(nn.Module):
def __init__(self, type='uniform', use_vector_constant=False):
super(LaplaceMeshLoss, self).__init__()
self.method = type
self.precomputed_laplacian = None
self.use_vector_constant = use_vector_constant
def _compute_loss(self, L, verts_packed, inv_areas=None):
if self.method == "uniform":
loss = L.mm(verts_packed)
elif self.method == "cot":
norm_w = torch.sparse.sum(L, dim=1).to_dense().view(-1, 1)
idx = norm_w > 0
norm_w[idx] = 1.0 / norm_w[idx]
loss = L.mm(verts_packed) * norm_w - verts_packed
elif self.method == "cotcurv":
L_sum = torch.sparse.sum(L, dim=1).to_dense().view(-1, 1)
norm_w = 0.25 * inv_areas
loss = (L.mm(verts_packed) - L_sum * verts_packed) * norm_w
return loss.norm(dim=1)
def forward(self, meshes, coefs=None):
if meshes.isempty():
return torch.tensor(
[0.0], dtype=torch.float32, device=meshes.device, requires_grad=True
)
N = len(meshes)
verts_packed = meshes.verts_packed() # (sum(V_n), 3)
faces_packed = meshes.faces_packed() # (sum(F_n), 3)
num_verts_per_mesh = meshes.num_verts_per_mesh() # (N,)
verts_packed_idx = meshes.verts_packed_to_mesh_idx() # (sum(V_n),)
weights = num_verts_per_mesh.gather(0, verts_packed_idx) # (sum(V_n),)
weights = 1.0 / weights.float()
norm_w, inv_areas = None, None
with torch.no_grad():
if self.method == "uniform":
if self.precomputed_laplacian is None or self.precomputed_laplacian.shape[0] != verts_packed.shape[0]:
L = meshes.laplacian_packed()
self.precomputed_laplacian = L
else:
L = self.precomputed_laplacian
elif self.method in ["cot", "cotcurv"]:
L, inv_areas = cot_laplacian(verts_packed, faces_packed)
else:
raise ValueError("Method should be one of {uniform, cot, cotcurv}")
loss = self._compute_loss(L, verts_packed,
inv_areas=inv_areas)
loss = loss * weights
if coefs is not None:
loss = loss * coefs.view(-1)
return loss.sum() / N
import torch
from torch import nn
import torch.nn.functional as F
from typing import List
class FeatureMatchingLoss(nn.Module):
def __init__(self, loss_type = 'l1', ):
super(FeatureMatchingLoss, self).__init__()
self.loss_type = loss_type
def forward(self,
real_features: List[List[List[torch.Tensor]]],
fake_features: List[List[List[torch.Tensor]]]
) -> torch.Tensor:
"""
features: a list of features of different inputs (the third layer corresponds to
features of a separate input to each of these discriminators)
"""
loss = 0
for real_feats_net, fake_feats_net in zip(real_features, fake_features):
# *_feats_net corresponds to outputs of a separate discriminator
loss_net = 0
for real_feats_layer, fake_feats_layer in zip(real_feats_net, fake_feats_net):
assert len(real_feats_layer) == 1 or len(real_feats_layer) == len(fake_feats_layer), 'Wrong number of real inputs'
if len(real_feats_layer) == 1:
real_feats_layer = [real_feats_layer[0]] * len(fake_feats_layer)
for real_feats_layer_i, fake_feats_layer_i in zip(real_feats_layer, fake_feats_layer):
if self.loss_type == 'l1':
loss_net += F.l1_loss(fake_feats_layer_i, real_feats_layer_i)
elif self.loss_type == 'l2':
loss_net += F.mse_loss(fake_feats_layer_i, real_feats_layer_i)
loss_net /= len(fake_feats_layer) # normalize by the number of inputs
loss_net /= len(fake_feats_net) # normalize by the number of layers
loss += loss_net
loss /= len(real_features) # normalize by the number of networks
return loss
import torch
from torch import nn
import torch.nn.functional as F
from typing import List, Union
class KeypointsMatchingLoss(nn.Module):
def __init__(self):
super(KeypointsMatchingLoss, self).__init__()
self.register_buffer('weights', torch.ones(68), persistent=False)
self.weights[5:7] = 2.0
self.weights[10:12] = 2.0
self.weights[27:36] = 1.5
self.weights[30] = 3.0
self.weights[31] = 3.0
self.weights[35] = 3.0
self.weights[60:68] = 1.5
self.weights[48:60] = 1.5
self.weights[48] = 3
self.weights[54] = 3
def forward(self,
pred_keypoints: torch.Tensor,
keypoints: torch.Tensor) -> torch.Tensor:
diff = pred_keypoints - keypoints
loss = (diff.abs().mean(-1) * self.weights[None] / self.weights.sum()).sum(-1).mean()
return loss
import torch
from torch import nn
import lpips
class LPIPS(nn.Module):
def __init__(self):
super(LPIPS, self).__init__()
self.metric = lpips.LPIPS(net='alex')
for m in self.metric.modules():
names = [name for name, _ in m.named_parameters()]
for name in names:
if hasattr(m, name):
data = getattr(m, name).data
delattr(m, name)
m.register_buffer(name, data, persistent=False)
names = [name for name, _ in m.named_buffers()]
for name in names:
if hasattr(m, name):
data = getattr(m, name).data
delattr(m, name)
m.register_buffer(name, data, persistent=False)
@torch.no_grad()
def __call__(self, inputs, targets):
return self.metric(inputs, targets, normalize=True).mean()
def train(self, mode: bool = True):
return self
# from .adversarial import AdversarialLoss
# from .feature_matching import FeatureMatchingLoss
# from .keypoints_matching import KeypointsMatchingLoss
# from .eye_closure import EyeClosureLoss
# from .lip_closure import LipClosureLoss
# from .head_pose_matching import HeadPoseMatchingLoss
# from .perceptual import PerceptualLoss
# from .segmentation import SegmentationLoss, MultiScaleSilhouetteLoss
# from .chamfer_silhouette import ChamferSilhouetteLoss
# from .equivariance import EquivarianceLoss, LaplaceMeshLoss
# from .vgg2face import VGGFace2Loss
# from .gaze import GazeLoss
# from .psnr import PSNR
# from .lpips import LPIPS
from pytorch_msssim import SSIM, MS_SSIM
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved
import torch
import torch.nn.functional as F
import torchvision
from torch import nn
from typing import Union
# from src.utils import misc
def apply_imagenet_normalization(input):
r"""Normalize using ImageNet mean and std.
Args:
input (4D tensor NxCxHxW): The input images, assuming to be [0, 1].
Returns:
Normalized inputs using the ImageNet normalization.
"""
# normalize the input using the ImageNet mean and std
mean = input.new_tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
std = input.new_tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
output = (input - mean) / std
return output
class PerceptualLoss(nn.Module):
r"""Perceptual loss initialization.
Args:
network (str) : The name of the loss network: 'vgg16' | 'vgg19'.
layers (str or list of str) : The layers used to compute the loss.
weights (float or list of float : The loss weights of each layer.
criterion (str): The type of distance function: 'l1' | 'l2'.
resize (bool) : If ``True``, resize the inputsut images to 224x224.
resize_mode (str): Algorithm used for resizing.
instance_normalized (bool): If ``True``, applies instance normalization
to the feature maps before computing the distance.
num_scales (int): The loss will be evaluated at original size and
this many times downsampled sizes.
use_fp16 (bool) : If ``True``, use cast networks and inputs to FP16
"""
def __init__(
self,
network='vgg19',
layers=('relu_1_1', 'relu_2_1', 'relu_3_1', 'relu_4_1', 'relu_5_1'),
weights=(0.03125, 0.0625, 0.125, 0.25, 1.0),
criterion='l1',
resize=False,
resize_mode='bilinear',
instance_normalized=False,
replace_maxpool_with_avgpool=False,
num_scales=1,
use_fp16=False
) -> None:
super(PerceptualLoss, self).__init__()
if isinstance(layers, str):
layers = [layers]
if weights is None:
weights = [1.] * len(layers)
elif isinstance(layers, float) or isinstance(layers, int):
weights = [weights]
assert len(layers) == len(weights), \
'The number of layers (%s) must be equal to ' \
'the number of weights (%s).' % (len(layers), len(weights))
if network == 'vgg19':
self.model = _vgg19(layers)
elif network == 'vgg16':
self.model = _vgg16(layers)
elif network == 'alexnet':
self.model = _alexnet(layers)
elif network == 'inception_v3':
self.model = _inception_v3(layers)
elif network == 'resnet50':
self.model = _resnet50(layers)
elif network == 'robust_resnet50':
self.model = _robust_resnet50(layers)
elif network == 'vgg_face_dag':
self.model = _vgg_face_dag(layers)
else:
raise ValueError('Network %s is not recognized' % network)
if replace_maxpool_with_avgpool:
for k, v in self.model.network._modules.items():
if isinstance(v, nn.MaxPool2d):
self.model.network._modules[k] = nn.AvgPool2d(2)
self.num_scales = num_scales
self.layers = layers
self.weights = weights
if criterion == 'l1':
self.criterion = nn.L1Loss()
elif criterion == 'l2' or criterion == 'mse':
self.criterion = nn.MSEloss()
else:
raise ValueError('Criterion %s is not recognized' % criterion)
self.resize = resize
self.resize_mode = resize_mode
self.instance_normalized = instance_normalized
self.fp16 = use_fp16
if self.fp16:
self.model.half()
@torch.cuda.amp.autocast(True)
def forward(self,
inputs: Union[torch.Tensor, list],
target: torch.Tensor) -> Union[torch.Tensor, list]:
r"""Perceptual loss forward.
Args:
inputs (4D tensor or list of 4D tensors) : inputsut tensor.
target (4D tensor) : Ground truth tensor, same shape as the inputsut.
Returns:
(scalar tensor or list of tensors) : The perceptual loss.
"""
if isinstance(inputs, list):
# Concat alongside the batch axis
input_is_a_list = True
num_chunks = len(inputs)
inputs = torch.cat(inputs)
else:
input_is_a_list = False
# Perceptual loss should operate in eval mode by default.
self.model.eval()
inputs, target = \
apply_imagenet_normalization(inputs), \
apply_imagenet_normalization(target)
if self.resize:
inputs = F.interpolate(
inputs, mode=self.resize_mode, size=(224, 224),
align_corners=False)
target = F.interpolate(
target, mode=self.resize_mode, size=(224, 224),
align_corners=False)
# Evaluate perceptual loss at each scale.
loss = 0
for scale in range(self.num_scales):
if self.fp16:
input_features = self.model(inputs.half())
with torch.no_grad():
target_features = self.model(target.half())
else:
input_features = self.model(inputs)
with torch.no_grad():
target_features = self.model(target)
for layer, weight in zip(self.layers, self.weights):
# Example per-layer VGG19 loss values after applying
# [0.03125, 0.0625, 0.125, 0.25, 1.0] weighting.
# relu_1_1, 0.014698
# relu_2_1, 0.085817
# relu_3_1, 0.349977
# relu_4_1, 0.544188
# relu_5_1, 0.906261
input_feature = input_features[layer]
target_feature = target_features[layer].detach()
if self.instance_normalized:
input_feature = F.instance_norm(input_feature)
target_feature = F.instance_norm(target_feature)
if input_is_a_list:
target_feature = torch.cat([target_feature] * num_chunks)
loss += weight * self.criterion(input_feature,
target_feature)
# Downsample the inputsut and target.
if scale != self.num_scales - 1:
inputs = F.interpolate(
inputs, mode=self.resize_mode, scale_factor=0.5,
align_corners=False, recompute_scale_factor=True)
target = F.interpolate(
target, mode=self.resize_mode, scale_factor=0.5,
align_corners=False, recompute_scale_factor=True)
loss /= self.num_scales
return loss
def train(self, mode: bool = True):
return self
class _PerceptualNetwork(nn.Module):
r"""The network that extracts features to compute the perceptual loss.
Args:
network (nn.Sequential) : The network that extracts features.
layer_name_mapping (dict) : The dictionary that
maps a layer's index to its name.
layers (list of str): The list of layer names that we are using.
"""
def __init__(self, network, layer_name_mapping, layers):
super().__init__()
assert isinstance(network, nn.Sequential), \
'The network needs to be of type "nn.Sequential".'
self.network = network
self.layer_name_mapping = layer_name_mapping
self.layers = layers
for m in self.network.modules():
names = [name for name, _ in m.named_parameters()]
for name in names:
if hasattr(m, name):
data = getattr(m, name).data
delattr(m, name)
m.register_buffer(name, data, persistent=False)
def forward(self, x):
r"""Extract perceptual features."""
output = {}
for i, layer in enumerate(self.network):
x = layer(x)
layer_name = self.layer_name_mapping.get(i, None)
if layer_name in self.layers:
# If the current layer is used by the perceptual loss.
output[layer_name] = x
return output
def _vgg19(layers):
r"""Get vgg19 layers"""
network = torchvision.models.vgg19(pretrained=True).features
layer_name_mapping = {1: 'relu_1_1',
3: 'relu_1_2',
6: 'relu_2_1',
8: 'relu_2_2',
11: 'relu_3_1',
13: 'relu_3_2',
15: 'relu_3_3',
17: 'relu_3_4',
20: 'relu_4_1',
22: 'relu_4_2',
24: 'relu_4_3',
26: 'relu_4_4',
29: 'relu_5_1'}
return _PerceptualNetwork(network, layer_name_mapping, layers)
def _vgg16(layers):
r"""Get vgg16 layers"""
network = torchvision.models.vgg16(pretrained=True).features
layer_name_mapping = {1: 'relu_1_1',
3: 'relu_1_2',
6: 'relu_2_1',
8: 'relu_2_2',
11: 'relu_3_1',
13: 'relu_3_2',
15: 'relu_3_3',
18: 'relu_4_1',
20: 'relu_4_2',
22: 'relu_4_3',
25: 'relu_5_1'}
return _PerceptualNetwork(network, layer_name_mapping, layers)
def _alexnet(layers):
r"""Get alexnet layers"""
network = torchvision.models.alexnet(pretrained=True).features
layer_name_mapping = {0: 'conv_1',
1: 'relu_1',
3: 'conv_2',
4: 'relu_2',
6: 'conv_3',
7: 'relu_3',
8: 'conv_4',
9: 'relu_4',
10: 'conv_5',
11: 'relu_5'}
return _PerceptualNetwork(network, layer_name_mapping, layers)
def _inception_v3(layers):
r"""Get inception v3 layers"""
inception = torchvision.models.inception_v3(pretrained=True)
network = nn.Sequential(inception.Conv2d_1a_3x3,
inception.Conv2d_2a_3x3,
inception.Conv2d_2b_3x3,
nn.MaxPool2d(kernel_size=3, stride=2),
inception.Conv2d_3b_1x1,
inception.Conv2d_4a_3x3,
nn.MaxPool2d(kernel_size=3, stride=2),
inception.Mixed_5b,
inception.Mixed_5c,
inception.Mixed_5d,
inception.Mixed_6a,
inception.Mixed_6b,
inception.Mixed_6c,
inception.Mixed_6d,
inception.Mixed_6e,
inception.Mixed_7a,
inception.Mixed_7b,
inception.Mixed_7c,
nn.AdaptiveAvgPool2d(output_size=(1, 1)))
layer_name_mapping = {3: 'pool_1',
6: 'pool_2',
14: 'mixed_6e',
18: 'pool_3'}
return _PerceptualNetwork(network, layer_name_mapping, layers)
def _resnet50(layers):
r"""Get resnet50 layers"""
resnet50 = torchvision.models.resnet50(pretrained=True)
network = nn.Sequential(resnet50.conv1,
resnet50.bn1,
resnet50.relu,
resnet50.maxpool,
resnet50.layer1,
resnet50.layer2,
resnet50.layer3,
resnet50.layer4,
resnet50.avgpool)
layer_name_mapping = {4: 'layer_1',
5: 'layer_2',
6: 'layer_3',
7: 'layer_4'}
return _PerceptualNetwork(network, layer_name_mapping, layers)
def _robust_resnet50(layers):
r"""Get robust resnet50 layers"""
resnet50 = torchvision.models.resnet50(pretrained=False)
state_dict = torch.utils.model_zoo.load_url(
'http://andrewilyas.com/ImageNet.pt')
new_state_dict = {}
for k, v in state_dict['model'].items():
if k.startswith('module.model.'):
new_state_dict[k[13:]] = v
resnet50.load_state_dict(new_state_dict)
network = nn.Sequential(resnet50.conv1,
resnet50.bn1,
resnet50.relu,
resnet50.maxpool,
resnet50.layer1,
resnet50.layer2,
resnet50.layer3,
resnet50.layer4,
resnet50.avgpool)
layer_name_mapping = {4: 'layer_1',
5: 'layer_2',
6: 'layer_3',
7: 'layer_4'}
return _PerceptualNetwork(network, layer_name_mapping, layers)
def _vgg_face_dag(layers):
r"""Get vgg face layers"""
network = torchvision.models.vgg16(num_classes=2622).features
state_dict = torch.utils.model_zoo.load_url(
'http://www.robots.ox.ac.uk/~albanie/models/pytorch-mcn/'
'vgg_face_dag.pth')
layer_name_mapping = {
0: 'conv1_1',
2: 'conv1_2',
5: 'conv2_1',
7: 'conv2_2',
10: 'conv3_1',
12: 'conv3_2',
14: 'conv3_3',
17: 'conv4_1',
19: 'conv4_2',
21: 'conv4_3',
24: 'conv5_1',
26: 'conv5_2',
28: 'conv5_3'}
new_state_dict = {}
for k, v in layer_name_mapping.items():
new_state_dict[str(k) + '.weight'] =\
state_dict[v + '.weight']
new_state_dict[str(k) + '.bias'] = \
state_dict[v + '.bias']
return _PerceptualNetwork(network, layer_name_mapping, layers)
import torch.nn as nn
import numpy as np
import torch
import torch.nn.functional as F
import cv2
from torch.autograd import Variable
import math
import torch
import torch.nn as nn
class Resnet50_scratch_dag(nn.Module):
def __init__(self):
super(Resnet50_scratch_dag, self).__init__()
self.meta = {'mean': [131.0912, 103.8827, 91.4953],
'std': [1, 1, 1],
'imageSize': [224, 224, 3]}
self.conv1_7x7_s2 = nn.Conv2d(3, 64, kernel_size=[7, 7], stride=(2, 2), padding=(3, 3), bias=False)
self.conv1_7x7_s2_bn = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv1_relu_7x7_s2 = nn.ReLU()
self.pool1_3x3_s2 = nn.MaxPool2d(kernel_size=[3, 3], stride=[2, 2], padding=(0, 0), dilation=1, ceil_mode=True)
self.conv2_1_1x1_reduce = nn.Conv2d(64, 64, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv2_1_1x1_reduce_bn = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_1_1x1_reduce_relu = nn.ReLU()
self.conv2_1_3x3 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv2_1_3x3_bn = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_1_3x3_relu = nn.ReLU()
self.conv2_1_1x1_increase = nn.Conv2d(64, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv2_1_1x1_increase_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_1_1x1_proj = nn.Conv2d(64, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv2_1_1x1_proj_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_1_relu = nn.ReLU()
self.conv2_2_1x1_reduce = nn.Conv2d(256, 64, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv2_2_1x1_reduce_bn = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_2_1x1_reduce_relu = nn.ReLU()
self.conv2_2_3x3 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv2_2_3x3_bn = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_2_3x3_relu = nn.ReLU()
self.conv2_2_1x1_increase = nn.Conv2d(64, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv2_2_1x1_increase_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_2_relu = nn.ReLU()
self.conv2_3_1x1_reduce = nn.Conv2d(256, 64, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv2_3_1x1_reduce_bn = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_3_1x1_reduce_relu = nn.ReLU()
self.conv2_3_3x3 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv2_3_3x3_bn = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_3_3x3_relu = nn.ReLU()
self.conv2_3_1x1_increase = nn.Conv2d(64, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv2_3_1x1_increase_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv2_3_relu = nn.ReLU()
self.conv3_1_1x1_reduce = nn.Conv2d(256, 128, kernel_size=[1, 1], stride=(2, 2), bias=False)
self.conv3_1_1x1_reduce_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_1_1x1_reduce_relu = nn.ReLU()
self.conv3_1_3x3 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv3_1_3x3_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_1_3x3_relu = nn.ReLU()
self.conv3_1_1x1_increase = nn.Conv2d(128, 512, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv3_1_1x1_increase_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_1_1x1_proj = nn.Conv2d(256, 512, kernel_size=[1, 1], stride=(2, 2), bias=False)
self.conv3_1_1x1_proj_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_1_relu = nn.ReLU()
self.conv3_2_1x1_reduce = nn.Conv2d(512, 128, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv3_2_1x1_reduce_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_2_1x1_reduce_relu = nn.ReLU()
self.conv3_2_3x3 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv3_2_3x3_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_2_3x3_relu = nn.ReLU()
self.conv3_2_1x1_increase = nn.Conv2d(128, 512, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv3_2_1x1_increase_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_2_relu = nn.ReLU()
self.conv3_3_1x1_reduce = nn.Conv2d(512, 128, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv3_3_1x1_reduce_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_3_1x1_reduce_relu = nn.ReLU()
self.conv3_3_3x3 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv3_3_3x3_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_3_3x3_relu = nn.ReLU()
self.conv3_3_1x1_increase = nn.Conv2d(128, 512, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv3_3_1x1_increase_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_3_relu = nn.ReLU()
self.conv3_4_1x1_reduce = nn.Conv2d(512, 128, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv3_4_1x1_reduce_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_4_1x1_reduce_relu = nn.ReLU()
self.conv3_4_3x3 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv3_4_3x3_bn = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_4_3x3_relu = nn.ReLU()
self.conv3_4_1x1_increase = nn.Conv2d(128, 512, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv3_4_1x1_increase_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv3_4_relu = nn.ReLU()
self.conv4_1_1x1_reduce = nn.Conv2d(512, 256, kernel_size=[1, 1], stride=(2, 2), bias=False)
self.conv4_1_1x1_reduce_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_1_1x1_reduce_relu = nn.ReLU()
self.conv4_1_3x3 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv4_1_3x3_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_1_3x3_relu = nn.ReLU()
self.conv4_1_1x1_increase = nn.Conv2d(256, 1024, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_1_1x1_increase_bn = nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_1_1x1_proj = nn.Conv2d(512, 1024, kernel_size=[1, 1], stride=(2, 2), bias=False)
self.conv4_1_1x1_proj_bn = nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_1_relu = nn.ReLU()
self.conv4_2_1x1_reduce = nn.Conv2d(1024, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_2_1x1_reduce_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_2_1x1_reduce_relu = nn.ReLU()
self.conv4_2_3x3 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv4_2_3x3_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_2_3x3_relu = nn.ReLU()
self.conv4_2_1x1_increase = nn.Conv2d(256, 1024, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_2_1x1_increase_bn = nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_2_relu = nn.ReLU()
self.conv4_3_1x1_reduce = nn.Conv2d(1024, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_3_1x1_reduce_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_3_1x1_reduce_relu = nn.ReLU()
self.conv4_3_3x3 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv4_3_3x3_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_3_3x3_relu = nn.ReLU()
self.conv4_3_1x1_increase = nn.Conv2d(256, 1024, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_3_1x1_increase_bn = nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_3_relu = nn.ReLU()
self.conv4_4_1x1_reduce = nn.Conv2d(1024, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_4_1x1_reduce_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_4_1x1_reduce_relu = nn.ReLU()
self.conv4_4_3x3 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv4_4_3x3_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_4_3x3_relu = nn.ReLU()
self.conv4_4_1x1_increase = nn.Conv2d(256, 1024, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_4_1x1_increase_bn = nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_4_relu = nn.ReLU()
self.conv4_5_1x1_reduce = nn.Conv2d(1024, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_5_1x1_reduce_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_5_1x1_reduce_relu = nn.ReLU()
self.conv4_5_3x3 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv4_5_3x3_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_5_3x3_relu = nn.ReLU()
self.conv4_5_1x1_increase = nn.Conv2d(256, 1024, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_5_1x1_increase_bn = nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_5_relu = nn.ReLU()
self.conv4_6_1x1_reduce = nn.Conv2d(1024, 256, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_6_1x1_reduce_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_6_1x1_reduce_relu = nn.ReLU()
self.conv4_6_3x3 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv4_6_3x3_bn = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_6_3x3_relu = nn.ReLU()
self.conv4_6_1x1_increase = nn.Conv2d(256, 1024, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv4_6_1x1_increase_bn = nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv4_6_relu = nn.ReLU()
self.conv5_1_1x1_reduce = nn.Conv2d(1024, 512, kernel_size=[1, 1], stride=(2, 2), bias=False)
self.conv5_1_1x1_reduce_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_1_1x1_reduce_relu = nn.ReLU()
self.conv5_1_3x3 = nn.Conv2d(512, 512, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv5_1_3x3_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_1_3x3_relu = nn.ReLU()
self.conv5_1_1x1_increase = nn.Conv2d(512, 2048, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv5_1_1x1_increase_bn = nn.BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_1_1x1_proj = nn.Conv2d(1024, 2048, kernel_size=[1, 1], stride=(2, 2), bias=False)
self.conv5_1_1x1_proj_bn = nn.BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_1_relu = nn.ReLU()
self.conv5_2_1x1_reduce = nn.Conv2d(2048, 512, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv5_2_1x1_reduce_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_2_1x1_reduce_relu = nn.ReLU()
self.conv5_2_3x3 = nn.Conv2d(512, 512, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv5_2_3x3_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_2_3x3_relu = nn.ReLU()
self.conv5_2_1x1_increase = nn.Conv2d(512, 2048, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv5_2_1x1_increase_bn = nn.BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_2_relu = nn.ReLU()
self.conv5_3_1x1_reduce = nn.Conv2d(2048, 512, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv5_3_1x1_reduce_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_3_1x1_reduce_relu = nn.ReLU()
self.conv5_3_3x3 = nn.Conv2d(512, 512, kernel_size=[3, 3], stride=(1, 1), padding=(1, 1), bias=False)
self.conv5_3_3x3_bn = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_3_3x3_relu = nn.ReLU()
self.conv5_3_1x1_increase = nn.Conv2d(512, 2048, kernel_size=[1, 1], stride=(1, 1), bias=False)
self.conv5_3_1x1_increase_bn = nn.BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.conv5_3_relu = nn.ReLU()
self.pool5_7x7_s1 = nn.AvgPool2d(kernel_size=[7, 7], stride=[1, 1], padding=0)
self.classifier = nn.Conv2d(2048, 8631, kernel_size=[1, 1], stride=(1, 1))
def forward(self, data):
conv1_7x7_s2 = self.conv1_7x7_s2(data)
conv1_7x7_s2_bn = self.conv1_7x7_s2_bn(conv1_7x7_s2)
conv1_7x7_s2_bnxx = self.conv1_relu_7x7_s2(conv1_7x7_s2_bn)
pool1_3x3_s2 = self.pool1_3x3_s2(conv1_7x7_s2_bnxx)
conv2_1_1x1_reduce = self.conv2_1_1x1_reduce(pool1_3x3_s2)
conv2_1_1x1_reduce_bn = self.conv2_1_1x1_reduce_bn(conv2_1_1x1_reduce)
conv2_1_1x1_reduce_bnxx = self.conv2_1_1x1_reduce_relu(conv2_1_1x1_reduce_bn)
conv2_1_3x3 = self.conv2_1_3x3(conv2_1_1x1_reduce_bnxx)
conv2_1_3x3_bn = self.conv2_1_3x3_bn(conv2_1_3x3)
conv2_1_3x3_bnxx = self.conv2_1_3x3_relu(conv2_1_3x3_bn)
conv2_1_1x1_increase = self.conv2_1_1x1_increase(conv2_1_3x3_bnxx)
conv2_1_1x1_increase_bn = self.conv2_1_1x1_increase_bn(conv2_1_1x1_increase)
conv2_1_1x1_proj = self.conv2_1_1x1_proj(pool1_3x3_s2)
conv2_1_1x1_proj_bn = self.conv2_1_1x1_proj_bn(conv2_1_1x1_proj)
conv2_1 = torch.add(conv2_1_1x1_proj_bn, 1, conv2_1_1x1_increase_bn)
conv2_1x = self.conv2_1_relu(conv2_1)
conv2_2_1x1_reduce = self.conv2_2_1x1_reduce(conv2_1x)
conv2_2_1x1_reduce_bn = self.conv2_2_1x1_reduce_bn(conv2_2_1x1_reduce)
conv2_2_1x1_reduce_bnxx = self.conv2_2_1x1_reduce_relu(conv2_2_1x1_reduce_bn)
conv2_2_3x3 = self.conv2_2_3x3(conv2_2_1x1_reduce_bnxx)
conv2_2_3x3_bn = self.conv2_2_3x3_bn(conv2_2_3x3)
conv2_2_3x3_bnxx = self.conv2_2_3x3_relu(conv2_2_3x3_bn)
conv2_2_1x1_increase = self.conv2_2_1x1_increase(conv2_2_3x3_bnxx)
conv2_2_1x1_increase_bn = self.conv2_2_1x1_increase_bn(conv2_2_1x1_increase)
conv2_2 = torch.add(conv2_1x, 1, conv2_2_1x1_increase_bn)
conv2_2x = self.conv2_2_relu(conv2_2)
conv2_3_1x1_reduce = self.conv2_3_1x1_reduce(conv2_2x)
conv2_3_1x1_reduce_bn = self.conv2_3_1x1_reduce_bn(conv2_3_1x1_reduce)
conv2_3_1x1_reduce_bnxx = self.conv2_3_1x1_reduce_relu(conv2_3_1x1_reduce_bn)
conv2_3_3x3 = self.conv2_3_3x3(conv2_3_1x1_reduce_bnxx)
conv2_3_3x3_bn = self.conv2_3_3x3_bn(conv2_3_3x3)
conv2_3_3x3_bnxx = self.conv2_3_3x3_relu(conv2_3_3x3_bn)
conv2_3_1x1_increase = self.conv2_3_1x1_increase(conv2_3_3x3_bnxx)
conv2_3_1x1_increase_bn = self.conv2_3_1x1_increase_bn(conv2_3_1x1_increase)
conv2_3 = torch.add(conv2_2x, 1, conv2_3_1x1_increase_bn)
conv2_3x = self.conv2_3_relu(conv2_3)
conv3_1_1x1_reduce = self.conv3_1_1x1_reduce(conv2_3x)
conv3_1_1x1_reduce_bn = self.conv3_1_1x1_reduce_bn(conv3_1_1x1_reduce)
conv3_1_1x1_reduce_bnxx = self.conv3_1_1x1_reduce_relu(conv3_1_1x1_reduce_bn)
conv3_1_3x3 = self.conv3_1_3x3(conv3_1_1x1_reduce_bnxx)
conv3_1_3x3_bn = self.conv3_1_3x3_bn(conv3_1_3x3)
conv3_1_3x3_bnxx = self.conv3_1_3x3_relu(conv3_1_3x3_bn)
conv3_1_1x1_increase = self.conv3_1_1x1_increase(conv3_1_3x3_bnxx)
conv3_1_1x1_increase_bn = self.conv3_1_1x1_increase_bn(conv3_1_1x1_increase)
conv3_1_1x1_proj = self.conv3_1_1x1_proj(conv2_3x)
conv3_1_1x1_proj_bn = self.conv3_1_1x1_proj_bn(conv3_1_1x1_proj)
conv3_1 = torch.add(conv3_1_1x1_proj_bn, 1, conv3_1_1x1_increase_bn)
conv3_1x = self.conv3_1_relu(conv3_1)
conv3_2_1x1_reduce = self.conv3_2_1x1_reduce(conv3_1x)
conv3_2_1x1_reduce_bn = self.conv3_2_1x1_reduce_bn(conv3_2_1x1_reduce)
conv3_2_1x1_reduce_bnxx = self.conv3_2_1x1_reduce_relu(conv3_2_1x1_reduce_bn)
conv3_2_3x3 = self.conv3_2_3x3(conv3_2_1x1_reduce_bnxx)
conv3_2_3x3_bn = self.conv3_2_3x3_bn(conv3_2_3x3)
conv3_2_3x3_bnxx = self.conv3_2_3x3_relu(conv3_2_3x3_bn)
conv3_2_1x1_increase = self.conv3_2_1x1_increase(conv3_2_3x3_bnxx)
conv3_2_1x1_increase_bn = self.conv3_2_1x1_increase_bn(conv3_2_1x1_increase)
conv3_2 = torch.add(conv3_1x, 1, conv3_2_1x1_increase_bn)
conv3_2x = self.conv3_2_relu(conv3_2)
conv3_3_1x1_reduce = self.conv3_3_1x1_reduce(conv3_2x)
conv3_3_1x1_reduce_bn = self.conv3_3_1x1_reduce_bn(conv3_3_1x1_reduce)
conv3_3_1x1_reduce_bnxx = self.conv3_3_1x1_reduce_relu(conv3_3_1x1_reduce_bn)
conv3_3_3x3 = self.conv3_3_3x3(conv3_3_1x1_reduce_bnxx)
conv3_3_3x3_bn = self.conv3_3_3x3_bn(conv3_3_3x3)
conv3_3_3x3_bnxx = self.conv3_3_3x3_relu(conv3_3_3x3_bn)
conv3_3_1x1_increase = self.conv3_3_1x1_increase(conv3_3_3x3_bnxx)
conv3_3_1x1_increase_bn = self.conv3_3_1x1_increase_bn(conv3_3_1x1_increase)
conv3_3 = torch.add(conv3_2x, 1, conv3_3_1x1_increase_bn)
conv3_3x = self.conv3_3_relu(conv3_3)