line_net.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. from typing import Any, Callable, List, Optional, Tuple, Union
  2. import torch
  3. from torch import nn
  4. from torchvision.ops import MultiScaleRoIAlign
  5. from libs.vision_libs.models import MobileNet_V3_Large_Weights, mobilenet_v3_large
  6. from libs.vision_libs.models.detection.anchor_utils import AnchorGenerator
  7. from libs.vision_libs.models.detection.rpn import RPNHead, RegionProposalNetwork
  8. from libs.vision_libs.models.detection.ssdlite import _mobilenet_extractor
  9. from libs.vision_libs.models.detection.transform import GeneralizedRCNNTransform
  10. from libs.vision_libs.ops import misc as misc_nn_ops
  11. from libs.vision_libs.transforms._presets import ObjectDetection
  12. from .line_head import LineRCNNHeads
  13. from .line_predictor import LineRCNNPredictor
  14. from libs.vision_libs.models._api import register_model, Weights, WeightsEnum
  15. from libs.vision_libs.models._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES, _COCO_CATEGORIES
  16. from libs.vision_libs.models._utils import _ovewrite_value_param, handle_legacy_interface
  17. from libs.vision_libs.models.resnet import resnet50, ResNet50_Weights, ResNet18_Weights, resnet18
  18. from libs.vision_libs.models.detection._utils import overwrite_eps
  19. from libs.vision_libs.models.detection.backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
  20. from libs.vision_libs.models.detection.faster_rcnn import FasterRCNN, TwoMLPHead, FastRCNNPredictor
  21. from .roi_heads import RoIHeads
  22. from .trainer import Trainer
  23. from ..base import backbone_factory
  24. from ..base.base_detection_net import BaseDetectionNet
  25. import torch.nn.functional as F
  26. from .predict import Predict
  27. from ..config.config_tool import read_yaml
  28. FEATURE_DIM = 8
  29. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  30. __all__ = [
  31. "LineNet",
  32. "LineNet_ResNet50_FPN_Weights",
  33. "LineNet_ResNet50_FPN_V2_Weights",
  34. "LineNet_MobileNet_V3_Large_FPN_Weights",
  35. "LineNet_MobileNet_V3_Large_320_FPN_Weights",
  36. "linenet_resnet50_fpn",
  37. "linenet_resnet50_fpn_v2",
  38. "linenet_mobilenet_v3_large_fpn",
  39. "linenet_mobilenet_v3_large_320_fpn",
  40. ]
  41. def _default_anchorgen():
  42. anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
  43. aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
  44. return AnchorGenerator(anchor_sizes, aspect_ratios)
  45. class LineNet(BaseDetectionNet):
  46. # def __init__(self, cfg, **kwargs):
  47. # cfg = read_yaml(cfg)
  48. # self.cfg=cfg
  49. # backbone = cfg['backbone']
  50. # print(f'LineNet Backbone:{backbone}')
  51. # num_classes = cfg['num_classes']
  52. #
  53. # if backbone == 'resnet50_fpn':
  54. # backbone=backbone_factory.get_resnet50_fpn()
  55. # print(f'out_chanenels:{backbone.out_channels}')
  56. # elif backbone== 'mobilenet_v3_large_fpn':
  57. # backbone=backbone_factory.get_mobilenet_v3_large_fpn()
  58. # elif backbone=='resnet18_fpn':
  59. # backbone=backbone_factory.get_resnet18_fpn()
  60. #
  61. # self.__construct__(backbone=backbone, num_classes=num_classes, **kwargs)
  62. def __init__(
  63. self,
  64. backbone,
  65. num_classes=None,
  66. # transform parameters
  67. min_size=512,
  68. max_size=1333,
  69. image_mean=None,
  70. image_std=None,
  71. # RPN parameters
  72. rpn_anchor_generator=None,
  73. rpn_head=None,
  74. rpn_pre_nms_top_n_train=2000,
  75. rpn_pre_nms_top_n_test=1000,
  76. rpn_post_nms_top_n_train=2000,
  77. rpn_post_nms_top_n_test=1000,
  78. rpn_nms_thresh=0.7,
  79. rpn_fg_iou_thresh=0.7,
  80. rpn_bg_iou_thresh=0.3,
  81. rpn_batch_size_per_image=256,
  82. rpn_positive_fraction=0.5,
  83. rpn_score_thresh=0.0,
  84. # Box parameters
  85. box_roi_pool=None,
  86. box_head=None,
  87. box_predictor=None,
  88. box_score_thresh=0.05,
  89. box_nms_thresh=0.5,
  90. box_detections_per_img=100,
  91. box_fg_iou_thresh=0.5,
  92. box_bg_iou_thresh=0.5,
  93. box_batch_size_per_image=512,
  94. box_positive_fraction=0.25,
  95. bbox_reg_weights=None,
  96. # line parameters
  97. line_head=None,
  98. line_predictor=None,
  99. **kwargs,
  100. ):
  101. if not hasattr(backbone, "out_channels"):
  102. raise ValueError(
  103. "backbone should contain an attribute out_channels "
  104. "specifying the number of output channels (assumed to be the "
  105. "same for all the levels)"
  106. )
  107. if not isinstance(rpn_anchor_generator, (AnchorGenerator, type(None))):
  108. raise TypeError(
  109. f"rpn_anchor_generator should be of type AnchorGenerator or None instead of {type(rpn_anchor_generator)}"
  110. )
  111. if not isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None))):
  112. raise TypeError(
  113. f"box_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(box_roi_pool)}"
  114. )
  115. if num_classes is not None:
  116. if box_predictor is not None:
  117. raise ValueError("num_classes should be None when box_predictor is specified")
  118. else:
  119. if box_predictor is None:
  120. raise ValueError("num_classes should not be None when box_predictor is not specified")
  121. out_channels = backbone.out_channels
  122. # cfg = read_yaml(cfg)
  123. # self.cfg=cfg
  124. if line_head is None:
  125. num_class = 5
  126. line_head = LineRCNNHeads(out_channels, num_class)
  127. if line_predictor is None:
  128. line_predictor = LineRCNNPredictor()
  129. if rpn_anchor_generator is None:
  130. rpn_anchor_generator = _default_anchorgen()
  131. if rpn_head is None:
  132. rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0])
  133. rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)
  134. rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)
  135. rpn = RegionProposalNetwork(
  136. rpn_anchor_generator,
  137. rpn_head,
  138. rpn_fg_iou_thresh,
  139. rpn_bg_iou_thresh,
  140. rpn_batch_size_per_image,
  141. rpn_positive_fraction,
  142. rpn_pre_nms_top_n,
  143. rpn_post_nms_top_n,
  144. rpn_nms_thresh,
  145. score_thresh=rpn_score_thresh,
  146. )
  147. if box_roi_pool is None:
  148. box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=7, sampling_ratio=2)
  149. if box_head is None:
  150. resolution = box_roi_pool.output_size[0]
  151. representation_size = 1024
  152. box_head = TwoMLPHead(out_channels * resolution ** 2, representation_size)
  153. if box_predictor is None:
  154. representation_size = 1024
  155. box_predictor = BoxPredictor(representation_size, num_classes)
  156. roi_heads = RoIHeads(
  157. # Box
  158. box_roi_pool,
  159. box_head,
  160. box_predictor,
  161. line_head,
  162. line_predictor,
  163. box_fg_iou_thresh,
  164. box_bg_iou_thresh,
  165. box_batch_size_per_image,
  166. box_positive_fraction,
  167. bbox_reg_weights,
  168. box_score_thresh,
  169. box_nms_thresh,
  170. box_detections_per_img,
  171. )
  172. if image_mean is None:
  173. image_mean = [0.485, 0.456, 0.406]
  174. if image_std is None:
  175. image_std = [0.229, 0.224, 0.225]
  176. transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs)
  177. super().__init__(backbone, rpn, roi_heads, transform)
  178. self.roi_heads = roi_heads
  179. # self.roi_heads.line_head = line_head
  180. # self.roi_heads.line_predictor = line_predictor
  181. def train_by_cfg(self, cfg):
  182. # cfg = read_yaml(cfg)
  183. self.trainer = Trainer()
  184. self.trainer.train_cfg(model=self, cfg=cfg)
  185. def predict(self, pt_path, model, img_path, type=0, threshold=0.5, save_path=None, show=False):
  186. self.predict = Predict(pt_path, model, img_path, type, threshold, save_path, show)
  187. self.predict.run()
  188. class TwoMLPHead(nn.Module):
  189. """
  190. Standard heads for FPN-based models
  191. Args:
  192. in_channels (int): number of input channels
  193. representation_size (int): size of the intermediate representation
  194. """
  195. def __init__(self, in_channels, representation_size):
  196. super().__init__()
  197. self.fc6 = nn.Linear(in_channels, representation_size)
  198. self.fc7 = nn.Linear(representation_size, representation_size)
  199. def forward(self, x):
  200. x = x.flatten(start_dim=1)
  201. x = F.relu(self.fc6(x))
  202. x = F.relu(self.fc7(x))
  203. return x
  204. class LineNetConvFCHead(nn.Sequential):
  205. def __init__(
  206. self,
  207. input_size: Tuple[int, int, int],
  208. conv_layers: List[int],
  209. fc_layers: List[int],
  210. norm_layer: Optional[Callable[..., nn.Module]] = None,
  211. ):
  212. """
  213. Args:
  214. input_size (Tuple[int, int, int]): the input size in CHW format.
  215. conv_layers (list): feature dimensions of each Convolution layer
  216. fc_layers (list): feature dimensions of each FCN layer
  217. norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
  218. """
  219. in_channels, in_height, in_width = input_size
  220. blocks = []
  221. previous_channels = in_channels
  222. for current_channels in conv_layers:
  223. blocks.append(misc_nn_ops.Conv2dNormActivation(previous_channels, current_channels, norm_layer=norm_layer))
  224. previous_channels = current_channels
  225. blocks.append(nn.Flatten())
  226. previous_channels = previous_channels * in_height * in_width
  227. for current_channels in fc_layers:
  228. blocks.append(nn.Linear(previous_channels, current_channels))
  229. blocks.append(nn.ReLU(inplace=True))
  230. previous_channels = current_channels
  231. super().__init__(*blocks)
  232. for layer in self.modules():
  233. if isinstance(layer, nn.Conv2d):
  234. nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu")
  235. if layer.bias is not None:
  236. nn.init.zeros_(layer.bias)
  237. class BoxPredictor(nn.Module):
  238. """
  239. Standard classification + bounding box regression layers
  240. for Fast R-CNN.
  241. Args:
  242. in_channels (int): number of input channels
  243. num_classes (int): number of output classes (including background)
  244. """
  245. def __init__(self, in_channels, num_classes):
  246. super().__init__()
  247. self.cls_score = nn.Linear(in_channels, num_classes)
  248. self.bbox_pred = nn.Linear(in_channels, num_classes * 4)
  249. def forward(self, x):
  250. if x.dim() == 4:
  251. torch._assert(
  252. list(x.shape[2:]) == [1, 1],
  253. f"x has the wrong shape, expecting the last two dimensions to be [1,1] instead of {list(x.shape[2:])}",
  254. )
  255. x = x.flatten(start_dim=1)
  256. scores = self.cls_score(x)
  257. bbox_deltas = self.bbox_pred(x)
  258. return scores, bbox_deltas
  259. _COMMON_META = {
  260. "categories": _COCO_CATEGORIES,
  261. "min_size": (1, 1),
  262. }
  263. class LineNet_ResNet50_FPN_Weights(WeightsEnum):
  264. COCO_V1 = Weights(
  265. url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth",
  266. transforms=ObjectDetection,
  267. meta={
  268. **_COMMON_META,
  269. "num_params": 41755286,
  270. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-resnet-50-fpn",
  271. "_metrics": {
  272. "COCO-val2017": {
  273. "box_map": 37.0,
  274. }
  275. },
  276. "_ops": 134.38,
  277. "_file_size": 159.743,
  278. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  279. },
  280. )
  281. DEFAULT = COCO_V1
  282. class LineNet_ResNet50_FPN_V2_Weights(WeightsEnum):
  283. COCO_V1 = Weights(
  284. url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_v2_coco-dd69338a.pth",
  285. transforms=ObjectDetection,
  286. meta={
  287. **_COMMON_META,
  288. "num_params": 43712278,
  289. "recipe": "https://github.com/pytorch/vision/pull/5763",
  290. "_metrics": {
  291. "COCO-val2017": {
  292. "box_map": 46.7,
  293. }
  294. },
  295. "_ops": 280.371,
  296. "_file_size": 167.104,
  297. "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""",
  298. },
  299. )
  300. DEFAULT = COCO_V1
  301. class LineNet_MobileNet_V3_Large_FPN_Weights(WeightsEnum):
  302. COCO_V1 = Weights(
  303. url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_fpn-fb6a3cc7.pth",
  304. transforms=ObjectDetection,
  305. meta={
  306. **_COMMON_META,
  307. "num_params": 19386354,
  308. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-fpn",
  309. "_metrics": {
  310. "COCO-val2017": {
  311. "box_map": 32.8,
  312. }
  313. },
  314. "_ops": 4.494,
  315. "_file_size": 74.239,
  316. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  317. },
  318. )
  319. DEFAULT = COCO_V1
  320. class LineNet_MobileNet_V3_Large_320_FPN_Weights(WeightsEnum):
  321. COCO_V1 = Weights(
  322. url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth",
  323. transforms=ObjectDetection,
  324. meta={
  325. **_COMMON_META,
  326. "num_params": 19386354,
  327. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-320-fpn",
  328. "_metrics": {
  329. "COCO-val2017": {
  330. "box_map": 22.8,
  331. }
  332. },
  333. "_ops": 0.719,
  334. "_file_size": 74.239,
  335. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  336. },
  337. )
  338. DEFAULT = COCO_V1
  339. @register_model()
  340. @handle_legacy_interface(
  341. weights=("pretrained", LineNet_ResNet50_FPN_Weights.COCO_V1),
  342. weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  343. )
  344. def linenet_resnet18_fpn(
  345. *,
  346. weights: Optional[LineNet_ResNet50_FPN_Weights] = None,
  347. progress: bool = True,
  348. num_classes: Optional[int] = None,
  349. weights_backbone: Optional[ResNet18_Weights] = ResNet18_Weights.IMAGENET1K_V1,
  350. trainable_backbone_layers: Optional[int] = None,
  351. **kwargs: Any,
  352. ) -> LineNet:
  353. # weights = LineNet_ResNet50_FPN_Weights.verify(weights)
  354. # weights_backbone = ResNet50_Weights.verify(weights_backbone)
  355. if weights is not None:
  356. weights_backbone = None
  357. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  358. elif num_classes is None:
  359. num_classes = 91
  360. if weights_backbone is not None:
  361. print(f'resnet50 weights is not None')
  362. is_trained = weights is not None or weights_backbone is not None
  363. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  364. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  365. backbone = resnet18(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  366. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  367. model = LineNet(backbone, num_classes=num_classes, **kwargs)
  368. if weights is not None:
  369. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  370. if weights == LineNet_ResNet50_FPN_Weights.COCO_V1:
  371. overwrite_eps(model, 0.0)
  372. return model
  373. def linenet_resnet50_fpn(
  374. *,
  375. weights: Optional[LineNet_ResNet50_FPN_Weights] = None,
  376. progress: bool = True,
  377. num_classes: Optional[int] = None,
  378. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  379. trainable_backbone_layers: Optional[int] = None,
  380. **kwargs: Any,
  381. ) -> LineNet:
  382. """
  383. Faster R-CNN model with a ResNet-50-FPN backbone from the `Faster R-CNN: Towards Real-Time Object
  384. Detection with Region Proposal Networks <https://arxiv.org/abs/1506.01497>`__
  385. paper.
  386. .. betastatus:: detection module
  387. The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
  388. image, and should be in ``0-1`` range. Different images can have different sizes.
  389. The behavior of the model changes depending on if it is in training or evaluation mode.
  390. During training, the model expects both the input tensors and a targets (list of dictionary),
  391. containing:
  392. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  393. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  394. - labels (``Int64Tensor[N]``): the class label for each ground-truth box
  395. The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
  396. losses for both the RPN and the R-CNN.
  397. During inference, the model requires only the input tensors, and returns the post-processed
  398. predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
  399. follows, where ``N`` is the number of detections:
  400. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  401. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  402. - labels (``Int64Tensor[N]``): the predicted labels for each detection
  403. - scores (``Tensor[N]``): the scores of each detection
  404. For more details on the output, you may refer to :ref:`instance_seg_output`.
  405. Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
  406. Example::
  407. >>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT)
  408. >>> # For training
  409. >>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4)
  410. >>> boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4]
  411. >>> labels = torch.randint(1, 91, (4, 11))
  412. >>> images = list(image for image in images)
  413. >>> targets = []
  414. >>> for i in range(len(images)):
  415. >>> d = {}
  416. >>> d['boxes'] = boxes[i]
  417. >>> d['labels'] = labels[i]
  418. >>> targets.append(d)
  419. >>> output = model(images, targets)
  420. >>> # For inference
  421. >>> model.eval()
  422. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  423. >>> predictions = model(x)
  424. >>>
  425. >>> # optionally, if you want to export the model to ONNX:
  426. >>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11)
  427. Args:
  428. weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights`, optional): The
  429. pretrained weights to use. See
  430. :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights` below for
  431. more details, and possible values. By default, no pre-trained
  432. weights are used.
  433. progress (bool, optional): If True, displays a progress bar of the
  434. download to stderr. Default is True.
  435. num_classes (int, optional): number of output classes of the model (including the background)
  436. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  437. pretrained weights for the backbone.
  438. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  439. final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
  440. trainable. If ``None`` is passed (the default) this value is set to 3.
  441. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  442. base class. Please refer to the `source code
  443. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  444. for more details about this class.
  445. .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights
  446. :members:
  447. """
  448. weights = LineNet_ResNet50_FPN_Weights.verify(weights)
  449. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  450. if weights is not None:
  451. weights_backbone = None
  452. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  453. elif num_classes is None:
  454. num_classes = 91
  455. if weights_backbone is not None:
  456. print(f'resnet50 weights is not None')
  457. is_trained = weights is not None or weights_backbone is not None
  458. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  459. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  460. backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  461. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  462. model = LineNet(backbone, num_classes=num_classes, **kwargs)
  463. if weights is not None:
  464. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  465. if weights == LineNet_ResNet50_FPN_Weights.COCO_V1:
  466. overwrite_eps(model, 0.0)
  467. return model
  468. @register_model()
  469. @handle_legacy_interface(
  470. weights=("pretrained", LineNet_ResNet50_FPN_V2_Weights.COCO_V1),
  471. weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  472. )
  473. def linenet_resnet50_fpn_v2(
  474. *,
  475. weights: Optional[LineNet_ResNet50_FPN_V2_Weights] = None,
  476. progress: bool = True,
  477. num_classes: Optional[int] = None,
  478. weights_backbone: Optional[ResNet50_Weights] = None,
  479. trainable_backbone_layers: Optional[int] = None,
  480. **kwargs: Any,
  481. ) -> LineNet:
  482. """
  483. Constructs an improved Faster R-CNN model with a ResNet-50-FPN backbone from `Benchmarking Detection
  484. Transfer Learning with Vision Transformers <https://arxiv.org/abs/2111.11429>`__ paper.
  485. .. betastatus:: detection module
  486. It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
  487. :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
  488. details.
  489. Args:
  490. weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights`, optional): The
  491. pretrained weights to use. See
  492. :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights` below for
  493. more details, and possible values. By default, no pre-trained
  494. weights are used.
  495. progress (bool, optional): If True, displays a progress bar of the
  496. download to stderr. Default is True.
  497. num_classes (int, optional): number of output classes of the model (including the background)
  498. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  499. pretrained weights for the backbone.
  500. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  501. final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
  502. trainable. If ``None`` is passed (the default) this value is set to 3.
  503. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  504. base class. Please refer to the `source code
  505. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  506. for more details about this class.
  507. .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights
  508. :members:
  509. """
  510. weights = LineNet_ResNet50_FPN_V2_Weights.verify(weights)
  511. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  512. if weights is not None:
  513. weights_backbone = None
  514. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  515. elif num_classes is None:
  516. num_classes = 91
  517. is_trained = weights is not None or weights_backbone is not None
  518. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  519. backbone = resnet50(weights=weights_backbone, progress=progress)
  520. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d)
  521. rpn_anchor_generator = _default_anchorgen()
  522. rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2)
  523. box_head = LineNetConvFCHead(
  524. (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d
  525. )
  526. model = LineNet(
  527. backbone,
  528. num_classes=num_classes,
  529. rpn_anchor_generator=rpn_anchor_generator,
  530. rpn_head=rpn_head,
  531. box_head=box_head,
  532. **kwargs,
  533. )
  534. if weights is not None:
  535. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  536. return model
  537. def _linenet_mobilenet_v3_large_fpn(
  538. *,
  539. weights: Optional[Union[LineNet_MobileNet_V3_Large_FPN_Weights, LineNet_MobileNet_V3_Large_320_FPN_Weights]],
  540. progress: bool,
  541. num_classes: Optional[int],
  542. weights_backbone: Optional[MobileNet_V3_Large_Weights],
  543. trainable_backbone_layers: Optional[int],
  544. **kwargs: Any,
  545. ) -> LineNet:
  546. if weights is not None:
  547. weights_backbone = None
  548. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  549. elif num_classes is None:
  550. num_classes = 91
  551. is_trained = weights is not None or weights_backbone is not None
  552. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 6, 3)
  553. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  554. backbone = mobilenet_v3_large(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  555. backbone = _mobilenet_extractor(backbone, True, trainable_backbone_layers)
  556. anchor_sizes = (
  557. (
  558. 32,
  559. 64,
  560. 128,
  561. 256,
  562. 512,
  563. ),
  564. ) * 3
  565. aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
  566. model = LineNet(
  567. backbone, num_classes, rpn_anchor_generator=AnchorGenerator(anchor_sizes, aspect_ratios), **kwargs
  568. )
  569. if weights is not None:
  570. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  571. return model
  572. @register_model()
  573. @handle_legacy_interface(
  574. weights=("pretrained", LineNet_MobileNet_V3_Large_320_FPN_Weights.COCO_V1),
  575. weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
  576. )
  577. def linenet_mobilenet_v3_large_320_fpn(
  578. *,
  579. weights: Optional[LineNet_MobileNet_V3_Large_320_FPN_Weights] = None,
  580. progress: bool = True,
  581. num_classes: Optional[int] = None,
  582. weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
  583. trainable_backbone_layers: Optional[int] = None,
  584. **kwargs: Any,
  585. ) -> LineNet:
  586. """
  587. Low resolution Faster R-CNN model with a MobileNetV3-Large backbone tuned for mobile use cases.
  588. .. betastatus:: detection module
  589. It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
  590. :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
  591. details.
  592. Example::
  593. >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(weights=FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.DEFAULT)
  594. >>> model.eval()
  595. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  596. >>> predictions = model(x)
  597. Args:
  598. weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights`, optional): The
  599. pretrained weights to use. See
  600. :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights` below for
  601. more details, and possible values. By default, no pre-trained
  602. weights are used.
  603. progress (bool, optional): If True, displays a progress bar of the
  604. download to stderr. Default is True.
  605. num_classes (int, optional): number of output classes of the model (including the background)
  606. weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
  607. pretrained weights for the backbone.
  608. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  609. final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are
  610. trainable. If ``None`` is passed (the default) this value is set to 3.
  611. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  612. base class. Please refer to the `source code
  613. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  614. for more details about this class.
  615. .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights
  616. :members:
  617. """
  618. weights = LineNet_MobileNet_V3_Large_320_FPN_Weights.verify(weights)
  619. weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
  620. defaults = {
  621. "min_size": 320,
  622. "max_size": 640,
  623. "rpn_pre_nms_top_n_test": 150,
  624. "rpn_post_nms_top_n_test": 150,
  625. "rpn_score_thresh": 0.05,
  626. }
  627. kwargs = {**defaults, **kwargs}
  628. return _linenet_mobilenet_v3_large_fpn(
  629. weights=weights,
  630. progress=progress,
  631. num_classes=num_classes,
  632. weights_backbone=weights_backbone,
  633. trainable_backbone_layers=trainable_backbone_layers,
  634. **kwargs,
  635. )
  636. @register_model()
  637. @handle_legacy_interface(
  638. weights=("pretrained", LineNet_MobileNet_V3_Large_FPN_Weights.COCO_V1),
  639. weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
  640. )
  641. def linenet_mobilenet_v3_large_fpn(
  642. *,
  643. weights: Optional[LineNet_MobileNet_V3_Large_FPN_Weights] = None,
  644. progress: bool = True,
  645. num_classes: Optional[int] = None,
  646. weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
  647. trainable_backbone_layers: Optional[int] = None,
  648. **kwargs: Any,
  649. ) -> LineNet:
  650. """
  651. Constructs a high resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone.
  652. .. betastatus:: detection module
  653. It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
  654. :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
  655. details.
  656. Example::
  657. >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(weights=FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT)
  658. >>> model.eval()
  659. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  660. >>> predictions = model(x)
  661. Args:
  662. weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights`, optional): The
  663. pretrained weights to use. See
  664. :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights` below for
  665. more details, and possible values. By default, no pre-trained
  666. weights are used.
  667. progress (bool, optional): If True, displays a progress bar of the
  668. download to stderr. Default is True.
  669. num_classes (int, optional): number of output classes of the model (including the background)
  670. weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
  671. pretrained weights for the backbone.
  672. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  673. final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are
  674. trainable. If ``None`` is passed (the default) this value is set to 3.
  675. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  676. base class. Please refer to the `source code
  677. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  678. for more details about this class.
  679. .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights
  680. :members:
  681. """
  682. weights = LineNet_MobileNet_V3_Large_FPN_Weights.verify(weights)
  683. weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
  684. defaults = {
  685. "rpn_score_thresh": 0.05,
  686. }
  687. kwargs = {**defaults, **kwargs}
  688. return _linenet_mobilenet_v3_large_fpn(
  689. weights=weights,
  690. progress=progress,
  691. num_classes=num_classes,
  692. weights_backbone=weights_backbone,
  693. trainable_backbone_layers=trainable_backbone_layers,
  694. **kwargs,
  695. )