Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

customizable_detector.py 8.6 KB

You have to be logged in to leave a comment. Sign In
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
  1. """
  2. A base for a detection network built according to the following scheme:
  3. * constructed from nested arch_params;
  4. * inside arch_params each nested level (module) has an explicit type and its required parameters
  5. * each module accepts in_channels and other parameters
  6. * each module defines out_channels property on construction
  7. """
  8. from typing import Union, Optional, List
  9. from torch import nn
  10. from omegaconf import DictConfig
  11. from super_gradients.common.decorators.factory_decorator import resolve_param
  12. from super_gradients.common.factories.processing_factory import ProcessingFactory
  13. from super_gradients.training.utils.utils import HpmStruct
  14. from super_gradients.training.models.sg_module import SgModule
  15. import super_gradients.common.factories.detection_modules_factory as det_factory
  16. from super_gradients.training.models.prediction_results import ImagesDetectionPrediction
  17. from super_gradients.training.pipelines.pipelines import DetectionPipeline
  18. from super_gradients.training.processing.processing import Processing
  19. from super_gradients.training.utils.detection_utils import DetectionPostPredictionCallback
  20. from super_gradients.training.utils.media.image import ImageSource
  21. class CustomizableDetector(SgModule):
  22. """
  23. A customizable detector with backbone -> neck -> heads
  24. Each submodule with its parameters must be defined explicitly.
  25. Modules should follow the interface of BaseDetectionModule
  26. """
  27. def __init__(
  28. self,
  29. backbone: Union[str, dict, HpmStruct, DictConfig],
  30. heads: Union[str, dict, HpmStruct, DictConfig],
  31. neck: Optional[Union[str, dict, HpmStruct, DictConfig]] = None,
  32. num_classes: int = None,
  33. bn_eps: Optional[float] = None,
  34. bn_momentum: Optional[float] = None,
  35. inplace_act: Optional[bool] = True,
  36. in_channels: int = 3,
  37. ):
  38. """
  39. :param backbone: Backbone configuration.
  40. :param heads: Head configuration.
  41. :param neck: Neck configuration.
  42. :param num_classes: num classes to predict.
  43. :param bn_eps: Epsilon for batch norm.
  44. :param bn_momentum: Momentum for batch norm.
  45. :param inplace_act: If True, do the operations operation in-place when possible.
  46. :param in_channels: number of input channels
  47. """
  48. super().__init__()
  49. self.heads_params = heads
  50. self.bn_eps = bn_eps
  51. self.bn_momentum = bn_momentum
  52. self.inplace_act = inplace_act
  53. factory = det_factory.DetectionModulesFactory()
  54. # move num_classes into heads params
  55. if num_classes is not None:
  56. self.heads_params = factory.insert_module_param(self.heads_params, "num_classes", num_classes)
  57. self.backbone = factory.get(factory.insert_module_param(backbone, "in_channels", in_channels))
  58. if neck is not None:
  59. self.neck = factory.get(factory.insert_module_param(neck, "in_channels", self.backbone.out_channels))
  60. self.heads = factory.get(factory.insert_module_param(heads, "in_channels", self.neck.out_channels))
  61. else:
  62. self.neck = nn.Identity()
  63. self.heads = factory.get(factory.insert_module_param(heads, "in_channels", self.backbone.out_channels))
  64. self._initialize_weights(bn_eps, bn_momentum, inplace_act)
  65. # Processing params
  66. self._class_names: Optional[List[str]] = None
  67. self._image_processor: Optional[Processing] = None
  68. self._default_nms_iou: Optional[float] = None
  69. self._default_nms_conf: Optional[float] = None
  70. def forward(self, x):
  71. x = self.backbone(x)
  72. x = self.neck(x)
  73. return self.heads(x)
  74. def _initialize_weights(self, bn_eps: Optional[float] = None, bn_momentum: Optional[float] = None, inplace_act: Optional[bool] = True):
  75. for m in self.modules():
  76. t = type(m)
  77. if t is nn.BatchNorm2d:
  78. m.eps = bn_eps if bn_eps else m.eps
  79. m.momentum = bn_momentum if bn_momentum else m.momentum
  80. elif inplace_act and t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, nn.Mish]:
  81. m.inplace = True
  82. def prep_model_for_conversion(self, input_size: Optional[Union[tuple, list]] = None, **kwargs):
  83. for module in self.modules():
  84. if module != self and hasattr(module, "prep_model_for_conversion"):
  85. module.prep_model_for_conversion(input_size, **kwargs)
  86. def replace_head(self, new_num_classes: Optional[int] = None, new_head: Optional[nn.Module] = None):
  87. if new_num_classes is None and new_head is None:
  88. raise ValueError("At least one of new_num_classes, new_head must be given to replace output layer.")
  89. if new_head is not None:
  90. self.heads = new_head
  91. else:
  92. factory = det_factory.DetectionModulesFactory()
  93. self.heads_params = factory.insert_module_param(self.heads_params, "num_classes", new_num_classes)
  94. self.heads = factory.get(factory.insert_module_param(self.heads_params, "in_channels", self.neck.out_channels))
  95. self._initialize_weights(self.bn_eps, self.bn_momentum, self.inplace_act)
  96. @staticmethod
  97. def get_post_prediction_callback(conf: float, iou: float) -> DetectionPostPredictionCallback:
  98. raise NotImplementedError
  99. @resolve_param("image_processor", ProcessingFactory())
  100. def set_dataset_processing_params(
  101. self,
  102. class_names: Optional[List[str]] = None,
  103. image_processor: Optional[Processing] = None,
  104. iou: Optional[float] = None,
  105. conf: Optional[float] = None,
  106. ) -> None:
  107. """Set the processing parameters for the dataset.
  108. :param class_names: (Optional) Names of the dataset the model was trained on.
  109. :param image_processor: (Optional) Image processing objects to reproduce the dataset preprocessing used for training.
  110. :param iou: (Optional) IoU threshold for the nms algorithm
  111. :param conf: (Optional) Below the confidence threshold, prediction are discarded
  112. """
  113. self._class_names = class_names or self._class_names
  114. self._image_processor = image_processor or self._image_processor
  115. self._default_nms_iou = iou or self._default_nms_iou
  116. self._default_nms_conf = conf or self._default_nms_conf
  117. def _get_pipeline(self, iou: Optional[float] = None, conf: Optional[float] = None) -> DetectionPipeline:
  118. """Instantiate the prediction pipeline of this model.
  119. :param iou: (Optional) IoU threshold for the nms algorithm. If None, the default value associated to the training is used.
  120. :param conf: (Optional) Below the confidence threshold, prediction are discarded.
  121. If None, the default value associated to the training is used.
  122. """
  123. if None in (self._class_names, self._image_processor, self._default_nms_iou, self._default_nms_conf):
  124. raise RuntimeError(
  125. "You must set the dataset processing parameters before calling predict.\n" "Please call `model.set_dataset_processing_params(...)` first."
  126. )
  127. iou = iou or self._default_nms_iou
  128. conf = conf or self._default_nms_conf
  129. pipeline = DetectionPipeline(
  130. model=self,
  131. image_processor=self._image_processor,
  132. post_prediction_callback=self.get_post_prediction_callback(iou=iou, conf=conf),
  133. class_names=self._class_names,
  134. )
  135. return pipeline
  136. def predict(self, images: ImageSource, iou: Optional[float] = None, conf: Optional[float] = None) -> ImagesDetectionPrediction:
  137. """Predict an image or a list of images.
  138. :param images: Images to predict.
  139. :param iou: (Optional) IoU threshold for the nms algorithm. If None, the default value associated to the training is used.
  140. :param conf: (Optional) Below the confidence threshold, prediction are discarded.
  141. If None, the default value associated to the training is used.
  142. """
  143. pipeline = self._get_pipeline(iou=iou, conf=conf)
  144. return pipeline(images) # type: ignore
  145. def predict_webcam(self, iou: Optional[float] = None, conf: Optional[float] = None):
  146. """Predict using webcam.
  147. :param iou: (Optional) IoU threshold for the nms algorithm. If None, the default value associated to the training is used.
  148. :param conf: (Optional) Below the confidence threshold, prediction are discarded.
  149. If None, the default value associated to the training is used.
  150. """
  151. pipeline = self._get_pipeline(iou=iou, conf=conf)
  152. pipeline.predict_webcam()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...