line_net.py 37 KB

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