line_net.py 37 KB

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