line_net.py 37 KB

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