test_scnet.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from unittest import TestCase
  3. import torch
  4. from torch.nn.modules.batchnorm import _BatchNorm
  5. from mmpose.models.backbones import SCNet
  6. from mmpose.models.backbones.scnet import SCBottleneck, SCConv
  7. class TestSCnet(TestCase):
  8. @staticmethod
  9. def is_block(modules):
  10. """Check if is SCNet building block."""
  11. if isinstance(modules, (SCBottleneck, )):
  12. return True
  13. return False
  14. @staticmethod
  15. def is_norm(modules):
  16. """Check if is one of the norms."""
  17. if isinstance(modules, (_BatchNorm, )):
  18. return True
  19. return False
  20. @staticmethod
  21. def all_zeros(modules):
  22. """Check if the weight(and bias) is all zero."""
  23. weight_zero = torch.equal(modules.weight.data,
  24. torch.zeros_like(modules.weight.data))
  25. if hasattr(modules, 'bias'):
  26. bias_zero = torch.equal(modules.bias.data,
  27. torch.zeros_like(modules.bias.data))
  28. else:
  29. bias_zero = True
  30. return weight_zero and bias_zero
  31. @staticmethod
  32. def check_norm_state(modules, train_state):
  33. """Check if norm layer is in correct train state."""
  34. for mod in modules:
  35. if isinstance(mod, _BatchNorm):
  36. if mod.training != train_state:
  37. return False
  38. return True
  39. def test_scnet_scconv(self):
  40. # Test scconv forward
  41. layer = SCConv(64, 64, 1, 4)
  42. x = torch.randn(1, 64, 56, 56)
  43. x_out = layer(x)
  44. self.assertEqual(x_out.shape, torch.Size([1, 64, 56, 56]))
  45. def test_scnet_bottleneck(self):
  46. # Test Bottleneck forward
  47. block = SCBottleneck(64, 64)
  48. x = torch.randn(1, 64, 56, 56)
  49. x_out = block(x)
  50. self.assertEqual(x_out.shape, torch.Size([1, 64, 56, 56]))
  51. def test_scnet_backbone(self):
  52. """Test scnet backbone."""
  53. with self.assertRaises(KeyError):
  54. # SCNet depth should be in [50, 101]
  55. SCNet(20)
  56. with self.assertRaises(TypeError):
  57. # pretrained must be a string path
  58. model = SCNet(50)
  59. model.init_weights(pretrained=0)
  60. # Test SCNet norm_eval=True
  61. model = SCNet(50, norm_eval=True)
  62. model.init_weights()
  63. model.train()
  64. self.assertTrue(self.check_norm_state(model.modules(), False))
  65. # Test SCNet50 with first stage frozen
  66. frozen_stages = 1
  67. model = SCNet(50, frozen_stages=frozen_stages)
  68. model.init_weights()
  69. model.train()
  70. self.assertFalse(model.norm1.training)
  71. for layer in [model.conv1, model.norm1]:
  72. for param in layer.parameters():
  73. self.assertFalse(param.requires_grad)
  74. for i in range(1, frozen_stages + 1):
  75. layer = getattr(model, f'layer{i}')
  76. for mod in layer.modules():
  77. if isinstance(mod, _BatchNorm):
  78. self.assertFalse(mod.training)
  79. for param in layer.parameters():
  80. self.assertFalse(param.requires_grad)
  81. # Test SCNet with BatchNorm forward
  82. model = SCNet(50, out_indices=(0, 1, 2, 3))
  83. for m in model.modules():
  84. if self.is_norm(m):
  85. self.assertIsInstance(m, _BatchNorm)
  86. model.init_weights()
  87. model.train()
  88. imgs = torch.randn(2, 3, 224, 224)
  89. feat = model(imgs)
  90. self.assertEqual(len(feat), 4)
  91. self.assertEqual(feat[0].shape, torch.Size([2, 256, 56, 56]))
  92. self.assertEqual(feat[1].shape, torch.Size([2, 512, 28, 28]))
  93. self.assertEqual(feat[2].shape, torch.Size([2, 1024, 14, 14]))
  94. self.assertEqual(feat[3].shape, torch.Size([2, 2048, 7, 7]))
  95. # Test SCNet with layers 1, 2, 3 out forward
  96. model = SCNet(50, out_indices=(0, 1, 2))
  97. model.init_weights()
  98. model.train()
  99. imgs = torch.randn(2, 3, 224, 224)
  100. feat = model(imgs)
  101. self.assertEqual(len(feat), 3)
  102. self.assertEqual(feat[0].shape, torch.Size([2, 256, 56, 56]))
  103. self.assertEqual(feat[1].shape, torch.Size([2, 512, 28, 28]))
  104. self.assertEqual(feat[2].shape, torch.Size([2, 1024, 14, 14]))
  105. # Test SEResNet50 with layers 3 (top feature maps) out forward
  106. model = SCNet(50, out_indices=(3, ))
  107. model.init_weights()
  108. model.train()
  109. imgs = torch.randn(2, 3, 224, 224)
  110. feat = model(imgs)
  111. self.assertIsInstance(feat, tuple)
  112. self.assertEqual(feat[-1].shape, torch.Size([2, 2048, 7, 7]))
  113. # Test SEResNet50 with checkpoint forward
  114. model = SCNet(50, out_indices=(0, 1, 2, 3), with_cp=True)
  115. for m in model.modules():
  116. if self.is_block(m):
  117. self.assertTrue(m.with_cp)
  118. model.init_weights()
  119. model.train()
  120. imgs = torch.randn(2, 3, 224, 224)
  121. feat = model(imgs)
  122. self.assertEqual(len(feat), 4)
  123. self.assertEqual(feat[0].shape, torch.Size([2, 256, 56, 56]))
  124. self.assertEqual(feat[1].shape, torch.Size([2, 512, 28, 28]))
  125. self.assertEqual(feat[2].shape, torch.Size([2, 1024, 14, 14]))
  126. self.assertEqual(feat[3].shape, torch.Size([2, 2048, 7, 7]))
  127. # Test SCNet zero initialization of residual
  128. model = SCNet(50, out_indices=(0, 1, 2, 3), zero_init_residual=True)
  129. model.init_weights()
  130. for m in model.modules():
  131. if isinstance(m, SCBottleneck):
  132. self.assertTrue(self.all_zeros(m.norm3))
  133. model.train()
  134. imgs = torch.randn(2, 3, 224, 224)
  135. feat = model(imgs)
  136. self.assertEqual(len(feat), 4)
  137. self.assertEqual(feat[0].shape, torch.Size([2, 256, 56, 56]))
  138. self.assertEqual(feat[1].shape, torch.Size([2, 512, 28, 28]))
  139. self.assertEqual(feat[2].shape, torch.Size([2, 1024, 14, 14]))
  140. self.assertEqual(feat[3].shape, torch.Size([2, 2048, 7, 7]))