line_net.py 38 KB

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