keypoint_rcnn.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. from typing import Any, Optional
  2. import torch
  3. from torch import nn
  4. from torchvision.ops import MultiScaleRoIAlign
  5. from ...ops import misc as misc_nn_ops
  6. from ...transforms._presets import ObjectDetection
  7. from .._api import register_model, Weights, WeightsEnum
  8. from .._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES
  9. from .._utils import _ovewrite_value_param, handle_legacy_interface
  10. from ..resnet import resnet50, ResNet50_Weights
  11. from ._utils import overwrite_eps
  12. from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
  13. from .faster_rcnn import FasterRCNN
  14. __all__ = [
  15. "KeypointRCNN",
  16. "KeypointRCNN_ResNet50_FPN_Weights",
  17. "keypointrcnn_resnet50_fpn",
  18. ]
  19. class KeypointRCNN(FasterRCNN):
  20. """
  21. Implements Keypoint R-CNN.
  22. The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
  23. image, and should be in 0-1 range. Different images can have different sizes.
  24. The behavior of the model changes depending on if it is in training or evaluation mode.
  25. During training, the model expects both the input tensors and targets (list of dictionary),
  26. containing:
  27. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  28. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  29. - labels (Int64Tensor[N]): the class label for each ground-truth box
  30. - keypoints (FloatTensor[N, K, 3]): the K keypoints location for each of the N instances, in the
  31. format [x, y, visibility], where visibility=0 means that the keypoint is not visible.
  32. The model returns a Dict[Tensor] during training, containing the classification and regression
  33. losses for both the RPN and the R-CNN, and the keypoint loss.
  34. During inference, the model requires only the input tensors, and returns the post-processed
  35. predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
  36. follows:
  37. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  38. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  39. - labels (Int64Tensor[N]): the predicted labels for each image
  40. - scores (Tensor[N]): the scores or each prediction
  41. - keypoints (FloatTensor[N, K, 3]): the locations of the predicted keypoints, in [x, y, v] format.
  42. Args:
  43. backbone (nn.Module): the network used to compute the features for the model.
  44. It should contain an out_channels attribute, which indicates the number of output
  45. channels that each feature map has (and it should be the same for all feature maps).
  46. The backbone should return a single Tensor or and OrderedDict[Tensor].
  47. num_classes (int): number of output classes of the model (including the background).
  48. If box_predictor is specified, num_classes should be None.
  49. min_size (int): Images are rescaled before feeding them to the backbone:
  50. we attempt to preserve the aspect ratio and scale the shorter edge
  51. to ``min_size``. If the resulting longer edge exceeds ``max_size``,
  52. then downscale so that the longer edge does not exceed ``max_size``.
  53. This may result in the shorter edge beeing lower than ``min_size``.
  54. max_size (int): See ``min_size``.
  55. image_mean (Tuple[float, float, float]): mean values used for input normalization.
  56. They are generally the mean values of the dataset on which the backbone has been trained
  57. on
  58. image_std (Tuple[float, float, float]): std values used for input normalization.
  59. They are generally the std values of the dataset on which the backbone has been trained on
  60. rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
  61. maps.
  62. rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
  63. rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
  64. rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
  65. rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
  66. rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
  67. rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
  68. rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
  69. considered as positive during training of the RPN.
  70. rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
  71. considered as negative during training of the RPN.
  72. rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
  73. for computing the loss
  74. rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
  75. of the RPN
  76. rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh
  77. box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
  78. the locations indicated by the bounding boxes
  79. box_head (nn.Module): module that takes the cropped feature maps as input
  80. box_predictor (nn.Module): module that takes the output of box_head and returns the
  81. classification logits and box regression deltas.
  82. box_score_thresh (float): during inference, only return proposals with a classification score
  83. greater than box_score_thresh
  84. box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
  85. box_detections_per_img (int): maximum number of detections per image, for all classes.
  86. box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
  87. considered as positive during training of the classification head
  88. box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
  89. considered as negative during training of the classification head
  90. box_batch_size_per_image (int): number of proposals that are sampled during training of the
  91. classification head
  92. box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
  93. of the classification head
  94. bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
  95. bounding boxes
  96. keypoint_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
  97. the locations indicated by the bounding boxes, which will be used for the keypoint head.
  98. keypoint_head (nn.Module): module that takes the cropped feature maps as input
  99. keypoint_predictor (nn.Module): module that takes the output of the keypoint_head and returns the
  100. heatmap logits
  101. Example::
  102. >>> import torch
  103. >>> import torchvision
  104. >>> from torchvision.models.detection import KeypointRCNN
  105. >>> from torchvision.models.detection.anchor_utils import AnchorGenerator
  106. >>>
  107. >>> # load a pre-trained model for classification and return
  108. >>> # only the features
  109. >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features
  110. >>> # KeypointRCNN needs to know the number of
  111. >>> # output channels in a backbone. For mobilenet_v2, it's 1280,
  112. >>> # so we need to add it here
  113. >>> backbone.out_channels = 1280
  114. >>>
  115. >>> # let's make the RPN generate 5 x 3 anchors per spatial
  116. >>> # location, with 5 different sizes and 3 different aspect
  117. >>> # ratios. We have a Tuple[Tuple[int]] because each feature
  118. >>> # map could potentially have different sizes and
  119. >>> # aspect ratios
  120. >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
  121. >>> aspect_ratios=((0.5, 1.0, 2.0),))
  122. >>>
  123. >>> # let's define what are the feature maps that we will
  124. >>> # use to perform the region of interest cropping, as well as
  125. >>> # the size of the crop after rescaling.
  126. >>> # if your backbone returns a Tensor, featmap_names is expected to
  127. >>> # be ['0']. More generally, the backbone should return an
  128. >>> # OrderedDict[Tensor], and in featmap_names you can choose which
  129. >>> # feature maps to use.
  130. >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
  131. >>> output_size=7,
  132. >>> sampling_ratio=2)
  133. >>>
  134. >>> keypoint_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
  135. >>> output_size=14,
  136. >>> sampling_ratio=2)
  137. >>> # put the pieces together inside a KeypointRCNN model
  138. >>> model = KeypointRCNN(backbone,
  139. >>> num_classes=2,
  140. >>> rpn_anchor_generator=anchor_generator,
  141. >>> box_roi_pool=roi_pooler,
  142. >>> keypoint_roi_pool=keypoint_roi_pooler)
  143. >>> model.eval()
  144. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  145. >>> predictions = model(x)
  146. """
  147. def __init__(
  148. self,
  149. backbone,
  150. num_classes=None,
  151. # transform parameters
  152. min_size=None,
  153. max_size=1333,
  154. image_mean=None,
  155. image_std=None,
  156. # RPN parameters
  157. rpn_anchor_generator=None,
  158. rpn_head=None,
  159. rpn_pre_nms_top_n_train=2000,
  160. rpn_pre_nms_top_n_test=1000,
  161. rpn_post_nms_top_n_train=2000,
  162. rpn_post_nms_top_n_test=1000,
  163. rpn_nms_thresh=0.7,
  164. rpn_fg_iou_thresh=0.7,
  165. rpn_bg_iou_thresh=0.3,
  166. rpn_batch_size_per_image=256,
  167. rpn_positive_fraction=0.5,
  168. rpn_score_thresh=0.0,
  169. # Box parameters
  170. box_roi_pool=None,
  171. box_head=None,
  172. box_predictor=None,
  173. box_score_thresh=0.05,
  174. box_nms_thresh=0.5,
  175. box_detections_per_img=100,
  176. box_fg_iou_thresh=0.5,
  177. box_bg_iou_thresh=0.5,
  178. box_batch_size_per_image=512,
  179. box_positive_fraction=0.25,
  180. bbox_reg_weights=None,
  181. # keypoint parameters
  182. keypoint_roi_pool=None,
  183. keypoint_head=None,
  184. keypoint_predictor=None,
  185. num_keypoints=None,
  186. **kwargs,
  187. ):
  188. if not isinstance(keypoint_roi_pool, (MultiScaleRoIAlign, type(None))):
  189. raise TypeError(
  190. "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}"
  191. )
  192. if min_size is None:
  193. min_size = (640, 672, 704, 736, 768, 800)
  194. if num_keypoints is not None:
  195. if keypoint_predictor is not None:
  196. raise ValueError("num_keypoints should be None when keypoint_predictor is specified")
  197. else:
  198. num_keypoints = 17
  199. out_channels = backbone.out_channels
  200. if keypoint_roi_pool is None:
  201. keypoint_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2)
  202. if keypoint_head is None:
  203. keypoint_layers = tuple(512 for _ in range(8))
  204. keypoint_head = KeypointRCNNHeads(out_channels, keypoint_layers)
  205. if keypoint_predictor is None:
  206. keypoint_dim_reduced = 512 # == keypoint_layers[-1]
  207. keypoint_predictor = KeypointRCNNPredictor(keypoint_dim_reduced, num_keypoints)
  208. super().__init__(
  209. backbone,
  210. num_classes,
  211. # transform parameters
  212. min_size,
  213. max_size,
  214. image_mean,
  215. image_std,
  216. # RPN-specific parameters
  217. rpn_anchor_generator,
  218. rpn_head,
  219. rpn_pre_nms_top_n_train,
  220. rpn_pre_nms_top_n_test,
  221. rpn_post_nms_top_n_train,
  222. rpn_post_nms_top_n_test,
  223. rpn_nms_thresh,
  224. rpn_fg_iou_thresh,
  225. rpn_bg_iou_thresh,
  226. rpn_batch_size_per_image,
  227. rpn_positive_fraction,
  228. rpn_score_thresh,
  229. # Box parameters
  230. box_roi_pool,
  231. box_head,
  232. box_predictor,
  233. box_score_thresh,
  234. box_nms_thresh,
  235. box_detections_per_img,
  236. box_fg_iou_thresh,
  237. box_bg_iou_thresh,
  238. box_batch_size_per_image,
  239. box_positive_fraction,
  240. bbox_reg_weights,
  241. **kwargs,
  242. )
  243. self.roi_heads.keypoint_roi_pool = keypoint_roi_pool
  244. self.roi_heads.keypoint_head = keypoint_head
  245. self.roi_heads.keypoint_predictor = keypoint_predictor
  246. class KeypointRCNNHeads(nn.Sequential):
  247. def __init__(self, in_channels, layers):
  248. d = []
  249. next_feature = in_channels
  250. for out_channels in layers:
  251. d.append(nn.Conv2d(next_feature, out_channels, 3, stride=1, padding=1))
  252. d.append(nn.ReLU(inplace=True))
  253. next_feature = out_channels
  254. super().__init__(*d)
  255. for m in self.children():
  256. if isinstance(m, nn.Conv2d):
  257. nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
  258. nn.init.constant_(m.bias, 0)
  259. class KeypointRCNNPredictor(nn.Module):
  260. def __init__(self, in_channels, num_keypoints):
  261. super().__init__()
  262. input_features = in_channels
  263. deconv_kernel = 4
  264. self.kps_score_lowres = nn.ConvTranspose2d(
  265. input_features,
  266. num_keypoints,
  267. deconv_kernel,
  268. stride=2,
  269. padding=deconv_kernel // 2 - 1,
  270. )
  271. nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu")
  272. nn.init.constant_(self.kps_score_lowres.bias, 0)
  273. self.up_scale = 2
  274. self.out_channels = num_keypoints
  275. def forward(self, x):
  276. x = self.kps_score_lowres(x)
  277. return torch.nn.functional.interpolate(
  278. x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False
  279. )
  280. _COMMON_META = {
  281. "categories": _COCO_PERSON_CATEGORIES,
  282. "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES,
  283. "min_size": (1, 1),
  284. }
  285. class KeypointRCNN_ResNet50_FPN_Weights(WeightsEnum):
  286. COCO_LEGACY = Weights(
  287. url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-9f466800.pth",
  288. transforms=ObjectDetection,
  289. meta={
  290. **_COMMON_META,
  291. "num_params": 59137258,
  292. "recipe": "https://github.com/pytorch/vision/issues/1606",
  293. "_metrics": {
  294. "COCO-val2017": {
  295. "box_map": 50.6,
  296. "kp_map": 61.1,
  297. }
  298. },
  299. "_ops": 133.924,
  300. "_file_size": 226.054,
  301. "_docs": """
  302. These weights were produced by following a similar training recipe as on the paper but use a checkpoint
  303. from an early epoch.
  304. """,
  305. },
  306. )
  307. COCO_V1 = Weights(
  308. url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-fc266e95.pth",
  309. transforms=ObjectDetection,
  310. meta={
  311. **_COMMON_META,
  312. "num_params": 59137258,
  313. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#keypoint-r-cnn",
  314. "_metrics": {
  315. "COCO-val2017": {
  316. "box_map": 54.6,
  317. "kp_map": 65.0,
  318. }
  319. },
  320. "_ops": 137.42,
  321. "_file_size": 226.054,
  322. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  323. },
  324. )
  325. DEFAULT = COCO_V1
  326. @register_model()
  327. @handle_legacy_interface(
  328. weights=(
  329. "pretrained",
  330. lambda kwargs: (
  331. KeypointRCNN_ResNet50_FPN_Weights.COCO_LEGACY
  332. if kwargs["pretrained"] == "legacy"
  333. else KeypointRCNN_ResNet50_FPN_Weights.COCO_V1
  334. ),
  335. ),
  336. weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  337. )
  338. def keypointrcnn_resnet50_fpn(
  339. *,
  340. weights: Optional[KeypointRCNN_ResNet50_FPN_Weights] = None,
  341. progress: bool = True,
  342. num_classes: Optional[int] = None,
  343. num_keypoints: Optional[int] = None,
  344. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  345. trainable_backbone_layers: Optional[int] = None,
  346. **kwargs: Any,
  347. ) -> KeypointRCNN:
  348. """
  349. Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone.
  350. .. betastatus:: detection module
  351. Reference: `Mask R-CNN <https://arxiv.org/abs/1703.06870>`__.
  352. The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
  353. image, and should be in ``0-1`` range. Different images can have different sizes.
  354. The behavior of the model changes depending on if it is in training or evaluation mode.
  355. During training, the model expects both the input tensors and targets (list of dictionary),
  356. containing:
  357. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  358. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  359. - labels (``Int64Tensor[N]``): the class label for each ground-truth box
  360. - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the
  361. format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible.
  362. The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
  363. losses for both the RPN and the R-CNN, and the keypoint loss.
  364. During inference, the model requires only the input tensors, and returns the post-processed
  365. predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
  366. follows, where ``N`` is the number of detected instances:
  367. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  368. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  369. - labels (``Int64Tensor[N]``): the predicted labels for each instance
  370. - scores (``Tensor[N]``): the scores or each instance
  371. - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format.
  372. For more details on the output, you may refer to :ref:`instance_seg_output`.
  373. Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
  374. Example::
  375. >>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(weights=KeypointRCNN_ResNet50_FPN_Weights.DEFAULT)
  376. >>> model.eval()
  377. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  378. >>> predictions = model(x)
  379. >>>
  380. >>> # optionally, if you want to export the model to ONNX:
  381. >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11)
  382. Args:
  383. weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The
  384. pretrained weights to use. See
  385. :class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`
  386. below for more details, and possible values. By default, no
  387. pre-trained weights are used.
  388. progress (bool): If True, displays a progress bar of the download to stderr
  389. num_classes (int, optional): number of output classes of the model (including the background)
  390. num_keypoints (int, optional): number of keypoints
  391. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  392. pretrained weights for the backbone.
  393. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block.
  394. Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
  395. passed (the default) this value is set to 3.
  396. .. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights
  397. :members:
  398. """
  399. weights = KeypointRCNN_ResNet50_FPN_Weights.verify(weights)
  400. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  401. if weights is not None:
  402. weights_backbone = None
  403. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  404. num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"]))
  405. else:
  406. if num_classes is None:
  407. num_classes = 2
  408. if num_keypoints is None:
  409. num_keypoints = 17
  410. is_trained = weights is not None or weights_backbone is not None
  411. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  412. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  413. backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  414. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  415. model = KeypointRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs)
  416. if weights is not None:
  417. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  418. if weights == KeypointRCNN_ResNet50_FPN_Weights.COCO_V1:
  419. overwrite_eps(model, 0.0)
  420. return model