MPlexA 0.7.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. MPlexA/__init__.py +1 -0
  2. MPlexA/__main__.py +12 -0
  3. MPlexA/detector.py +169 -0
  4. MPlexA/detectors/__init__.py +0 -0
  5. MPlexA/detectron2/__init__.py +6 -0
  6. MPlexA/detectron2/checkpoint/__init__.py +7 -0
  7. MPlexA/detectron2/checkpoint/c2_model_loading.py +382 -0
  8. MPlexA/detectron2/checkpoint/catalog.py +112 -0
  9. MPlexA/detectron2/checkpoint/detection_checkpoint.py +142 -0
  10. MPlexA/detectron2/config/__init__.py +20 -0
  11. MPlexA/detectron2/config/compat.py +229 -0
  12. MPlexA/detectron2/config/config.py +254 -0
  13. MPlexA/detectron2/config/defaults.py +571 -0
  14. MPlexA/detectron2/config/instantiate.py +81 -0
  15. MPlexA/detectron2/config/lazy.py +431 -0
  16. MPlexA/detectron2/data/__init__.py +16 -0
  17. MPlexA/detectron2/data/benchmark.py +228 -0
  18. MPlexA/detectron2/data/build.py +661 -0
  19. MPlexA/detectron2/data/catalog.py +241 -0
  20. MPlexA/detectron2/data/common.py +352 -0
  21. MPlexA/detectron2/data/dataset_mapper.py +180 -0
  22. MPlexA/detectron2/data/datasets/__init__.py +7 -0
  23. MPlexA/detectron2/data/datasets/builtin.py +238 -0
  24. MPlexA/detectron2/data/datasets/builtin_meta.py +334 -0
  25. MPlexA/detectron2/data/datasets/cityscapes.py +292 -0
  26. MPlexA/detectron2/data/datasets/cityscapes_panoptic.py +170 -0
  27. MPlexA/detectron2/data/datasets/coco.py +501 -0
  28. MPlexA/detectron2/data/datasets/coco_panoptic.py +217 -0
  29. MPlexA/detectron2/data/datasets/lvis.py +228 -0
  30. MPlexA/detectron2/data/datasets/lvis_v0_5_categories.py +12 -0
  31. MPlexA/detectron2/data/datasets/lvis_v1_categories.py +15 -0
  32. MPlexA/detectron2/data/datasets/lvis_v1_category_image_count.py +19 -0
  33. MPlexA/detectron2/data/datasets/pascal_voc.py +73 -0
  34. MPlexA/detectron2/data/datasets/register_coco.py +3 -0
  35. MPlexA/detectron2/data/detection_utils.py +620 -0
  36. MPlexA/detectron2/data/samplers/__init__.py +15 -0
  37. MPlexA/detectron2/data/samplers/distributed_sampler.py +293 -0
  38. MPlexA/detectron2/data/samplers/grouped_batch_sampler.py +50 -0
  39. MPlexA/detectron2/data/transforms/__init__.py +10 -0
  40. MPlexA/detectron2/data/transforms/augmentation.py +386 -0
  41. MPlexA/detectron2/data/transforms/augmentation_impl.py +767 -0
  42. MPlexA/detectron2/data/transforms/transform.py +367 -0
  43. MPlexA/detectron2/engine/__init__.py +15 -0
  44. MPlexA/detectron2/engine/defaults.py +737 -0
  45. MPlexA/detectron2/engine/hooks.py +719 -0
  46. MPlexA/detectron2/engine/launch.py +114 -0
  47. MPlexA/detectron2/engine/train_loop.py +534 -0
  48. MPlexA/detectron2/evaluation/__init__.py +11 -0
  49. MPlexA/detectron2/evaluation/cityscapes_evaluation.py +192 -0
  50. MPlexA/detectron2/evaluation/coco_evaluation.py +680 -0
  51. MPlexA/detectron2/evaluation/evaluator.py +233 -0
  52. MPlexA/detectron2/evaluation/fast_eval_api.py +111 -0
  53. MPlexA/detectron2/evaluation/lvis_evaluation.py +349 -0
  54. MPlexA/detectron2/evaluation/panoptic_evaluation.py +183 -0
  55. MPlexA/detectron2/evaluation/pascal_voc_evaluation.py +275 -0
  56. MPlexA/detectron2/evaluation/rotated_coco_evaluation.py +196 -0
  57. MPlexA/detectron2/evaluation/sem_seg_evaluation.py +252 -0
  58. MPlexA/detectron2/evaluation/testing.py +82 -0
  59. MPlexA/detectron2/export/__init__.py +22 -0
  60. MPlexA/detectron2/export/api.py +232 -0
  61. MPlexA/detectron2/export/c10.py +568 -0
  62. MPlexA/detectron2/export/caffe2_export.py +187 -0
  63. MPlexA/detectron2/export/caffe2_inference.py +157 -0
  64. MPlexA/detectron2/export/caffe2_modeling.py +416 -0
  65. MPlexA/detectron2/export/caffe2_patch.py +189 -0
  66. MPlexA/detectron2/export/flatten.py +346 -0
  67. MPlexA/detectron2/export/shared.py +983 -0
  68. MPlexA/detectron2/export/torchscript.py +123 -0
  69. MPlexA/detectron2/export/torchscript_patch.py +383 -0
  70. MPlexA/detectron2/layers/__init__.py +25 -0
  71. MPlexA/detectron2/layers/aspp.py +144 -0
  72. MPlexA/detectron2/layers/batch_norm.py +356 -0
  73. MPlexA/detectron2/layers/blocks.py +112 -0
  74. MPlexA/detectron2/layers/deform_conv.py +509 -0
  75. MPlexA/detectron2/layers/losses.py +116 -0
  76. MPlexA/detectron2/layers/mask_ops.py +250 -0
  77. MPlexA/detectron2/layers/nms.py +141 -0
  78. MPlexA/detectron2/layers/roi_align.py +77 -0
  79. MPlexA/detectron2/layers/roi_align_rotated.py +107 -0
  80. MPlexA/detectron2/layers/rotated_boxes.py +21 -0
  81. MPlexA/detectron2/layers/shape_spec.py +18 -0
  82. MPlexA/detectron2/layers/wrappers.py +177 -0
  83. MPlexA/detectron2/model_zoo/__init__.py +8 -0
  84. MPlexA/detectron2/model_zoo/configs/Base-RCNN-C4.yaml +18 -0
  85. MPlexA/detectron2/model_zoo/configs/Base-RCNN-DilatedC5.yaml +31 -0
  86. MPlexA/detectron2/model_zoo/configs/Base-RCNN-FPN.yaml +42 -0
  87. MPlexA/detectron2/model_zoo/configs/Base-RetinaNet.yaml +25 -0
  88. MPlexA/detectron2/model_zoo/configs/COCO-Detection/fast_rcnn_R_50_FPN_1x.yaml +17 -0
  89. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_101_C4_3x.yaml +9 -0
  90. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_101_DC5_3x.yaml +9 -0
  91. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml +9 -0
  92. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_50_C4_1x.yaml +6 -0
  93. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_50_C4_3x.yaml +9 -0
  94. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_50_DC5_1x.yaml +6 -0
  95. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_50_DC5_3x.yaml +9 -0
  96. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_50_FPN_1x.yaml +6 -0
  97. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml +9 -0
  98. MPlexA/detectron2/model_zoo/configs/COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml +13 -0
  99. MPlexA/detectron2/model_zoo/configs/COCO-Detection/fcos_R_50_FPN_1x.py +9 -0
  100. MPlexA/detectron2/model_zoo/configs/COCO-Detection/retinanet_R_101_FPN_3x.yaml +8 -0
  101. MPlexA/detectron2/model_zoo/configs/COCO-Detection/retinanet_R_50_FPN_1x.py +9 -0
  102. MPlexA/detectron2/model_zoo/configs/COCO-Detection/retinanet_R_50_FPN_1x.yaml +5 -0
  103. MPlexA/detectron2/model_zoo/configs/COCO-Detection/retinanet_R_50_FPN_3x.yaml +8 -0
  104. MPlexA/detectron2/model_zoo/configs/COCO-Detection/rpn_R_50_C4_1x.yaml +10 -0
  105. MPlexA/detectron2/model_zoo/configs/COCO-Detection/rpn_R_50_FPN_1x.yaml +9 -0
  106. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_101_C4_3x.yaml +9 -0
  107. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_101_DC5_3x.yaml +9 -0
  108. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml +9 -0
  109. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x.py +7 -0
  110. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x.yaml +6 -0
  111. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_C4_3x.yaml +9 -0
  112. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_1x.yaml +6 -0
  113. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_3x.yaml +9 -0
  114. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.py +7 -0
  115. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml +6 -0
  116. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x_giou.yaml +12 -0
  117. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml +9 -0
  118. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml +13 -0
  119. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_regnetx_4gf_dds_fpn_1x.py +30 -0
  120. MPlexA/detectron2/model_zoo/configs/COCO-InstanceSegmentation/mask_rcnn_regnety_4gf_dds_fpn_1x.py +31 -0
  121. MPlexA/detectron2/model_zoo/configs/COCO-Keypoints/Base-Keypoint-RCNN-FPN.yaml +15 -0
  122. MPlexA/detectron2/model_zoo/configs/COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x.yaml +8 -0
  123. MPlexA/detectron2/model_zoo/configs/COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x.py +7 -0
  124. MPlexA/detectron2/model_zoo/configs/COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x.yaml +5 -0
  125. MPlexA/detectron2/model_zoo/configs/COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml +8 -0
  126. MPlexA/detectron2/model_zoo/configs/COCO-Keypoints/keypoint_rcnn_X_101_32x8d_FPN_3x.yaml +12 -0
  127. MPlexA/detectron2/model_zoo/configs/COCO-PanopticSegmentation/Base-Panoptic-FPN.yaml +11 -0
  128. MPlexA/detectron2/model_zoo/configs/COCO-PanopticSegmentation/panoptic_fpn_R_101_3x.yaml +8 -0
  129. MPlexA/detectron2/model_zoo/configs/COCO-PanopticSegmentation/panoptic_fpn_R_50_1x.py +7 -0
  130. MPlexA/detectron2/model_zoo/configs/COCO-PanopticSegmentation/panoptic_fpn_R_50_1x.yaml +5 -0
  131. MPlexA/detectron2/model_zoo/configs/COCO-PanopticSegmentation/panoptic_fpn_R_50_3x.yaml +8 -0
  132. MPlexA/detectron2/model_zoo/configs/Cityscapes/mask_rcnn_R_50_FPN.yaml +27 -0
  133. MPlexA/detectron2/model_zoo/configs/Detectron1-Comparisons/faster_rcnn_R_50_FPN_noaug_1x.yaml +17 -0
  134. MPlexA/detectron2/model_zoo/configs/Detectron1-Comparisons/keypoint_rcnn_R_50_FPN_1x.yaml +27 -0
  135. MPlexA/detectron2/model_zoo/configs/Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x.yaml +20 -0
  136. MPlexA/detectron2/model_zoo/configs/LVISv0.5-InstanceSegmentation/mask_rcnn_R_101_FPN_1x.yaml +19 -0
  137. MPlexA/detectron2/model_zoo/configs/LVISv0.5-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml +19 -0
  138. MPlexA/detectron2/model_zoo/configs/LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml +23 -0
  139. MPlexA/detectron2/model_zoo/configs/LVISv1-InstanceSegmentation/mask_rcnn_R_101_FPN_1x.yaml +22 -0
  140. MPlexA/detectron2/model_zoo/configs/LVISv1-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml +22 -0
  141. MPlexA/detectron2/model_zoo/configs/LVISv1-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml +26 -0
  142. MPlexA/detectron2/model_zoo/configs/Misc/cascade_mask_rcnn_R_50_FPN_1x.yaml +12 -0
  143. MPlexA/detectron2/model_zoo/configs/Misc/cascade_mask_rcnn_R_50_FPN_3x.yaml +15 -0
  144. MPlexA/detectron2/model_zoo/configs/Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv.yaml +36 -0
  145. MPlexA/detectron2/model_zoo/configs/Misc/mask_rcnn_R_50_FPN_1x_cls_agnostic.yaml +10 -0
  146. MPlexA/detectron2/model_zoo/configs/Misc/mask_rcnn_R_50_FPN_1x_dconv_c3-c5.yaml +8 -0
  147. MPlexA/detectron2/model_zoo/configs/Misc/mask_rcnn_R_50_FPN_3x_dconv_c3-c5.yaml +11 -0
  148. MPlexA/detectron2/model_zoo/configs/Misc/mask_rcnn_R_50_FPN_3x_gn.yaml +21 -0
  149. MPlexA/detectron2/model_zoo/configs/Misc/mask_rcnn_R_50_FPN_3x_syncbn.yaml +24 -0
  150. MPlexA/detectron2/model_zoo/configs/Misc/mmdet_mask_rcnn_R_50_FPN_1x.py +148 -0
  151. MPlexA/detectron2/model_zoo/configs/Misc/panoptic_fpn_R_101_dconv_cascade_gn_3x.yaml +26 -0
  152. MPlexA/detectron2/model_zoo/configs/Misc/scratch_mask_rcnn_R_50_FPN_3x_gn.yaml +13 -0
  153. MPlexA/detectron2/model_zoo/configs/Misc/scratch_mask_rcnn_R_50_FPN_9x_gn.yaml +19 -0
  154. MPlexA/detectron2/model_zoo/configs/Misc/scratch_mask_rcnn_R_50_FPN_9x_syncbn.yaml +19 -0
  155. MPlexA/detectron2/model_zoo/configs/Misc/semantic_R_50_FPN_1x.yaml +11 -0
  156. MPlexA/detectron2/model_zoo/configs/Misc/torchvision_imagenet_R_50.py +143 -0
  157. MPlexA/detectron2/model_zoo/configs/PascalVOC-Detection/faster_rcnn_R_50_C4.yaml +18 -0
  158. MPlexA/detectron2/model_zoo/configs/PascalVOC-Detection/faster_rcnn_R_50_FPN.yaml +18 -0
  159. MPlexA/detectron2/model_zoo/configs/common/coco_schedule.py +43 -0
  160. MPlexA/detectron2/model_zoo/configs/common/data/coco.py +43 -0
  161. MPlexA/detectron2/model_zoo/configs/common/data/coco_keypoint.py +10 -0
  162. MPlexA/detectron2/model_zoo/configs/common/data/coco_panoptic_separated.py +22 -0
  163. MPlexA/detectron2/model_zoo/configs/common/data/constants.py +9 -0
  164. MPlexA/detectron2/model_zoo/configs/common/models/cascade_rcnn.py +33 -0
  165. MPlexA/detectron2/model_zoo/configs/common/models/fcos.py +17 -0
  166. MPlexA/detectron2/model_zoo/configs/common/models/keypoint_rcnn_fpn.py +28 -0
  167. MPlexA/detectron2/model_zoo/configs/common/models/mask_rcnn_c4.py +88 -0
  168. MPlexA/detectron2/model_zoo/configs/common/models/mask_rcnn_fpn.py +93 -0
  169. MPlexA/detectron2/model_zoo/configs/common/models/mask_rcnn_vitdet.py +53 -0
  170. MPlexA/detectron2/model_zoo/configs/common/models/panoptic_fpn.py +18 -0
  171. MPlexA/detectron2/model_zoo/configs/common/models/retinanet.py +52 -0
  172. MPlexA/detectron2/model_zoo/configs/common/optim.py +24 -0
  173. MPlexA/detectron2/model_zoo/configs/common/train.py +18 -0
  174. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_R_101_FPN_100ep_LSJ.py +8 -0
  175. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_R_101_FPN_200ep_LSJ.py +12 -0
  176. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_R_101_FPN_400ep_LSJ.py +12 -0
  177. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_R_50_FPN_100ep_LSJ.py +60 -0
  178. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_R_50_FPN_200ep_LSJ.py +12 -0
  179. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_R_50_FPN_400ep_LSJ.py +12 -0
  180. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_R_50_FPN_50ep_LSJ.py +12 -0
  181. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ.py +27 -0
  182. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_200ep_LSJ.py +12 -0
  183. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_400ep_LSJ.py +12 -0
  184. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_regnety_4gf_dds_FPN_100ep_LSJ.py +28 -0
  185. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_regnety_4gf_dds_FPN_200ep_LSJ.py +12 -0
  186. MPlexA/detectron2/model_zoo/configs/new_baselines/mask_rcnn_regnety_4gf_dds_FPN_400ep_LSJ.py +12 -0
  187. MPlexA/detectron2/model_zoo/configs/quick_schedules/cascade_mask_rcnn_R_50_FPN_inference_acc_test.yaml +8 -0
  188. MPlexA/detectron2/model_zoo/configs/quick_schedules/cascade_mask_rcnn_R_50_FPN_instant_test.yaml +11 -0
  189. MPlexA/detectron2/model_zoo/configs/quick_schedules/fast_rcnn_R_50_FPN_inference_acc_test.yaml +8 -0
  190. MPlexA/detectron2/model_zoo/configs/quick_schedules/fast_rcnn_R_50_FPN_instant_test.yaml +15 -0
  191. MPlexA/detectron2/model_zoo/configs/quick_schedules/keypoint_rcnn_R_50_FPN_inference_acc_test.yaml +8 -0
  192. MPlexA/detectron2/model_zoo/configs/quick_schedules/keypoint_rcnn_R_50_FPN_instant_test.yaml +16 -0
  193. MPlexA/detectron2/model_zoo/configs/quick_schedules/keypoint_rcnn_R_50_FPN_normalized_training_acc_test.yaml +30 -0
  194. MPlexA/detectron2/model_zoo/configs/quick_schedules/keypoint_rcnn_R_50_FPN_training_acc_test.yaml +28 -0
  195. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_C4_GCV_instant_test.yaml +18 -0
  196. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_C4_inference_acc_test.yaml +8 -0
  197. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_C4_instant_test.yaml +14 -0
  198. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_C4_training_acc_test.yaml +22 -0
  199. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_DC5_inference_acc_test.yaml +8 -0
  200. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_FPN_inference_acc_test.yaml +11 -0
  201. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_FPN_instant_test.yaml +14 -0
  202. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_FPN_pred_boxes_training_acc_test.yaml +6 -0
  203. MPlexA/detectron2/model_zoo/configs/quick_schedules/mask_rcnn_R_50_FPN_training_acc_test.yaml +21 -0
  204. MPlexA/detectron2/model_zoo/configs/quick_schedules/panoptic_fpn_R_50_inference_acc_test.yaml +8 -0
  205. MPlexA/detectron2/model_zoo/configs/quick_schedules/panoptic_fpn_R_50_instant_test.yaml +19 -0
  206. MPlexA/detectron2/model_zoo/configs/quick_schedules/panoptic_fpn_R_50_training_acc_test.yaml +20 -0
  207. MPlexA/detectron2/model_zoo/configs/quick_schedules/retinanet_R_50_FPN_inference_acc_test.yaml +7 -0
  208. MPlexA/detectron2/model_zoo/configs/quick_schedules/retinanet_R_50_FPN_instant_test.yaml +13 -0
  209. MPlexA/detectron2/model_zoo/configs/quick_schedules/rpn_R_50_FPN_inference_acc_test.yaml +8 -0
  210. MPlexA/detectron2/model_zoo/configs/quick_schedules/rpn_R_50_FPN_instant_test.yaml +13 -0
  211. MPlexA/detectron2/model_zoo/configs/quick_schedules/semantic_R_50_FPN_inference_acc_test.yaml +10 -0
  212. MPlexA/detectron2/model_zoo/configs/quick_schedules/semantic_R_50_FPN_instant_test.yaml +18 -0
  213. MPlexA/detectron2/model_zoo/configs/quick_schedules/semantic_R_50_FPN_training_acc_test.yaml +20 -0
  214. MPlexA/detectron2/model_zoo/model_zoo.py +211 -0
  215. MPlexA/detectron2/modeling/__init__.py +59 -0
  216. MPlexA/detectron2/modeling/anchor_generator.py +396 -0
  217. MPlexA/detectron2/modeling/backbone/__init__.py +18 -0
  218. MPlexA/detectron2/modeling/backbone/backbone.py +78 -0
  219. MPlexA/detectron2/modeling/backbone/build.py +30 -0
  220. MPlexA/detectron2/modeling/backbone/fpn.py +268 -0
  221. MPlexA/detectron2/modeling/backbone/mvit.py +418 -0
  222. MPlexA/detectron2/modeling/backbone/regnet.py +478 -0
  223. MPlexA/detectron2/modeling/backbone/resnet.py +663 -0
  224. MPlexA/detectron2/modeling/backbone/swin.py +659 -0
  225. MPlexA/detectron2/modeling/backbone/utils.py +177 -0
  226. MPlexA/detectron2/modeling/backbone/vit.py +496 -0
  227. MPlexA/detectron2/modeling/box_regression.py +348 -0
  228. MPlexA/detectron2/modeling/matcher.py +124 -0
  229. MPlexA/detectron2/modeling/meta_arch/__init__.py +11 -0
  230. MPlexA/detectron2/modeling/meta_arch/build.py +23 -0
  231. MPlexA/detectron2/modeling/meta_arch/dense_detector.py +295 -0
  232. MPlexA/detectron2/modeling/meta_arch/fcos.py +309 -0
  233. MPlexA/detectron2/modeling/meta_arch/panoptic_fpn.py +252 -0
  234. MPlexA/detectron2/modeling/meta_arch/rcnn.py +339 -0
  235. MPlexA/detectron2/modeling/meta_arch/retinanet.py +428 -0
  236. MPlexA/detectron2/modeling/meta_arch/semantic_seg.py +267 -0
  237. MPlexA/detectron2/modeling/mmdet_wrapper.py +266 -0
  238. MPlexA/detectron2/modeling/poolers.py +252 -0
  239. MPlexA/detectron2/modeling/postprocessing.py +92 -0
  240. MPlexA/detectron2/modeling/proposal_generator/__init__.py +4 -0
  241. MPlexA/detectron2/modeling/proposal_generator/build.py +21 -0
  242. MPlexA/detectron2/modeling/proposal_generator/proposal_utils.py +186 -0
  243. MPlexA/detectron2/modeling/proposal_generator/rpn.py +526 -0
  244. MPlexA/detectron2/modeling/proposal_generator/rrpn.py +196 -0
  245. MPlexA/detectron2/modeling/roi_heads/__init__.py +27 -0
  246. MPlexA/detectron2/modeling/roi_heads/box_head.py +116 -0
  247. MPlexA/detectron2/modeling/roi_heads/cascade_rcnn.py +302 -0
  248. MPlexA/detectron2/modeling/roi_heads/fast_rcnn.py +553 -0
  249. MPlexA/detectron2/modeling/roi_heads/keypoint_head.py +262 -0
  250. MPlexA/detectron2/modeling/roi_heads/mask_head.py +286 -0
  251. MPlexA/detectron2/modeling/roi_heads/roi_heads.py +862 -0
  252. MPlexA/detectron2/modeling/roi_heads/rotated_fast_rcnn.py +261 -0
  253. MPlexA/detectron2/modeling/sampling.py +49 -0
  254. MPlexA/detectron2/modeling/test_time_augmentation.py +307 -0
  255. MPlexA/detectron2/projects/__init__.py +33 -0
  256. MPlexA/detectron2/projects/deeplab/__init__.py +5 -0
  257. MPlexA/detectron2/projects/deeplab/build_solver.py +25 -0
  258. MPlexA/detectron2/projects/deeplab/config.py +28 -0
  259. MPlexA/detectron2/projects/deeplab/loss.py +42 -0
  260. MPlexA/detectron2/projects/deeplab/lr_scheduler.py +63 -0
  261. MPlexA/detectron2/projects/deeplab/resnet.py +156 -0
  262. MPlexA/detectron2/projects/deeplab/semantic_seg.py +343 -0
  263. MPlexA/detectron2/projects/panoptic_deeplab/__init__.py +10 -0
  264. MPlexA/detectron2/projects/panoptic_deeplab/config.py +58 -0
  265. MPlexA/detectron2/projects/panoptic_deeplab/dataset_mapper.py +110 -0
  266. MPlexA/detectron2/projects/panoptic_deeplab/panoptic_seg.py +569 -0
  267. MPlexA/detectron2/projects/panoptic_deeplab/post_processing.py +220 -0
  268. MPlexA/detectron2/projects/panoptic_deeplab/target_generator.py +150 -0
  269. MPlexA/detectron2/projects/point_rend/__init__.py +6 -0
  270. MPlexA/detectron2/projects/point_rend/color_augmentation.py +108 -0
  271. MPlexA/detectron2/projects/point_rend/config.py +52 -0
  272. MPlexA/detectron2/projects/point_rend/mask_head.py +436 -0
  273. MPlexA/detectron2/projects/point_rend/point_features.py +250 -0
  274. MPlexA/detectron2/projects/point_rend/point_head.py +263 -0
  275. MPlexA/detectron2/projects/point_rend/roi_heads.py +50 -0
  276. MPlexA/detectron2/projects/point_rend/semantic_seg.py +130 -0
  277. MPlexA/detectron2/solver/__init__.py +10 -0
  278. MPlexA/detectron2/solver/build.py +316 -0
  279. MPlexA/detectron2/solver/lr_scheduler.py +255 -0
  280. MPlexA/detectron2/structures/__init__.py +12 -0
  281. MPlexA/detectron2/structures/boxes.py +429 -0
  282. MPlexA/detectron2/structures/image_list.py +130 -0
  283. MPlexA/detectron2/structures/instances.py +207 -0
  284. MPlexA/detectron2/structures/keypoints.py +220 -0
  285. MPlexA/detectron2/structures/masks.py +555 -0
  286. MPlexA/detectron2/structures/rotated_boxes.py +505 -0
  287. MPlexA/detectron2/tracking/__init__.py +14 -0
  288. MPlexA/detectron2/tracking/base_tracker.py +66 -0
  289. MPlexA/detectron2/tracking/bbox_iou_tracker.py +282 -0
  290. MPlexA/detectron2/tracking/hungarian_tracker.py +176 -0
  291. MPlexA/detectron2/tracking/iou_weighted_hungarian_bbox_iou_tracker.py +103 -0
  292. MPlexA/detectron2/tracking/utils.py +37 -0
  293. MPlexA/detectron2/tracking/vanilla_hungarian_bbox_iou_tracker.py +131 -0
  294. MPlexA/detectron2/utils/__init__.py +1 -0
  295. MPlexA/detectron2/utils/analysis.py +179 -0
  296. MPlexA/detectron2/utils/collect_env.py +234 -0
  297. MPlexA/detectron2/utils/colormap.py +151 -0
  298. MPlexA/detectron2/utils/comm.py +234 -0
  299. MPlexA/detectron2/utils/develop.py +65 -0
  300. MPlexA/detectron2/utils/env.py +159 -0
  301. MPlexA/detectron2/utils/events.py +578 -0
  302. MPlexA/detectron2/utils/file_io.py +37 -0
  303. MPlexA/detectron2/utils/logger.py +250 -0
  304. MPlexA/detectron2/utils/memory.py +81 -0
  305. MPlexA/detectron2/utils/registry.py +54 -0
  306. MPlexA/detectron2/utils/serialize.py +37 -0
  307. MPlexA/detectron2/utils/testing.py +457 -0
  308. MPlexA/detectron2/utils/tracing.py +68 -0
  309. MPlexA/detectron2/utils/video_visualizer.py +276 -0
  310. MPlexA/detectron2/utils/visualizer.py +1254 -0
  311. MPlexA/gui.py +3544 -0
  312. MPlexA/multiplex/__init__.py +234 -0
  313. MPlexA/multiplex/checkpoints.py +428 -0
  314. MPlexA/multiplex/coco_export.py +259 -0
  315. MPlexA/multiplex/exceptions.py +25 -0
  316. MPlexA/multiplex/image_source.py +753 -0
  317. MPlexA/multiplex/metadata.py +86 -0
  318. MPlexA/multiplex/phenotyping.py +570 -0
  319. MPlexA/multiplex/quantification.py +1478 -0
  320. MPlexA/multiplex/reconciliation.py +1475 -0
  321. MPlexA/multiplex/roi_extraction.py +412 -0
  322. MPlexA/multiplex/segmentation.py +1618 -0
  323. MPlexA/multiplex/spatial.py +427 -0
  324. MPlexA/multiplex/spatial_viewer.py +257 -0
  325. MPlexA/multiplex/tiling.py +541 -0
  326. MPlexA/multiplex/viewer.py +388 -0
  327. mplexa-0.7.2.dist-info/METADATA +56 -0
  328. mplexa-0.7.2.dist-info/RECORD +332 -0
  329. mplexa-0.7.2.dist-info/WHEEL +4 -0
  330. mplexa-0.7.2.dist-info/entry_points.txt +6 -0
  331. mplexa-0.7.2.dist-info/licenses/LICENSE +674 -0
  332. mplexa-0.7.2.dist-info/licenses/NOTICE.txt +2 -0
MPlexA/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__='0.7.2'
MPlexA/__main__.py ADDED
@@ -0,0 +1,12 @@
1
+ from.import gui
2
+
3
+
4
+
5
+ def main():
6
+
7
+ gui.main_window()
8
+
9
+
10
+ if __name__=='__main__':
11
+
12
+ main()
MPlexA/detector.py ADDED
@@ -0,0 +1,169 @@
1
+ import os
2
+ import cv2
3
+ import json
4
+ import torch
5
+ from MPlexA.detectron2 import model_zoo
6
+ from MPlexA.detectron2.checkpoint import DetectionCheckpointer
7
+ from MPlexA.detectron2.config import get_cfg
8
+ from MPlexA.detectron2.data import MetadataCatalog,DatasetCatalog,build_detection_test_loader
9
+ from MPlexA.detectron2.data.datasets import register_coco_instances
10
+ from MPlexA.detectron2.engine import DefaultTrainer,DefaultPredictor
11
+ from MPlexA.detectron2.utils.visualizer import Visualizer
12
+ from MPlexA.detectron2.evaluation import COCOEvaluator,inference_on_dataset
13
+ from MPlexA.detectron2.modeling import build_model
14
+
15
+
16
+
17
+ class Detector():
18
+
19
+
20
+ def __init__(self):
21
+ self.device='cuda'if torch.cuda.is_available()else'cpu'# whether the GPU is available, if so, use GPU
22
+ self.cell_mapping=None# the celln categories and names in a Detector
23
+ self.inferencing_framesize=None
24
+ self.black_background=None
25
+ self.current_detector=None# the current Detector used for inference
26
+
27
+
28
+ def train(self,path_to_annotation,path_to_trainingimages,path_to_detector,iteration_num,inference_size,num_rois,black_background=0):
29
+ # path_to_annotation: the path to the .json file that stores the annotations in coco format
30
+ # path_to_trainingimages: the folder that stores all the training images
31
+ # iteration_num: the number of training iterations
32
+ # inference_size: the Detector inferencing frame size
33
+ # num_rois: the batch size of ROI heads per image
34
+ # black_background: whether the background of images to analyze is black/darker
35
+ if str('MPlexA_detector_train')in DatasetCatalog.list():
36
+ DatasetCatalog.remove('MPlexA_detector_train')
37
+ MetadataCatalog.remove('MPlexA_detector_train')
38
+ register_coco_instances('MPlexA_detector_train',{},path_to_annotation,path_to_trainingimages)
39
+ datasetcat=DatasetCatalog.get('MPlexA_detector_train')
40
+ metadatacat=MetadataCatalog.get('MPlexA_detector_train')
41
+ classnames=metadatacat.thing_classes
42
+ model_parameters_dict={}
43
+ model_parameters_dict['cell_names']=[]
44
+ annotation_data=json.load(open(path_to_annotation))
45
+ for i in annotation_data['categories']:
46
+ if i['id']>0:
47
+ model_parameters_dict['cell_names'].append(i['name'])
48
+ print('Cell names in annotation file: '+str(model_parameters_dict['cell_names']))
49
+ cfg=get_cfg()
50
+ cfg.merge_from_file(model_zoo.get_config_file('COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'))
51
+ cfg.OUTPUT_DIR=path_to_detector
52
+ cfg.DATASETS.TRAIN=('MPlexA_detector_train',)
53
+ cfg.DATASETS.TEST=()
54
+ cfg.DATALOADER.NUM_WORKERS=4
55
+ cfg.MODEL.WEIGHTS=model_zoo.get_checkpoint_url('COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml')
56
+ cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE=num_rois
57
+ cfg.MODEL.ROI_HEADS.NUM_CLASSES=int(len(classnames))
58
+ cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST=0.5
59
+ cfg.MODEL.DEVICE=self.device
60
+ cfg.SOLVER.IMS_PER_BATCH=4
61
+ cfg.SOLVER.MAX_ITER=int(iteration_num)
62
+ cfg.SOLVER.BASE_LR=0.001
63
+ cfg.SOLVER.WARMUP_ITERS=int(iteration_num*0.1)
64
+ cfg.SOLVER.STEPS=(int(iteration_num*0.4),int(iteration_num*0.8))
65
+ cfg.SOLVER.GAMMA=0.5
66
+ cfg.SOLVER.CHECKPOINT_PERIOD=100000000000000000
67
+ cfg.INPUT.MIN_SIZE_TEST=int(inference_size)
68
+ cfg.INPUT.MAX_SIZE_TEST=int(inference_size)
69
+ cfg.INPUT.MIN_SIZE_TRAIN=(int(inference_size),)
70
+ cfg.INPUT.MAX_SIZE_TRAIN=int(inference_size)
71
+ os.makedirs(cfg.OUTPUT_DIR)
72
+ trainer=DefaultTrainer(cfg)
73
+ trainer.resume_or_load(False)
74
+ trainer.train()
75
+ model_parameters=os.path.join(cfg.OUTPUT_DIR,'model_parameters.txt')
76
+ model_parameters_dict['cell_mapping']={}
77
+ model_parameters_dict['inferencing_framesize']=int(inference_size)
78
+ model_parameters_dict['black_background']=int(black_background)
79
+ for i in range(len(classnames)):
80
+ model_parameters_dict['cell_mapping'][i]=classnames[i]
81
+ with open(model_parameters,'w')as f:
82
+ f.write(json.dumps(model_parameters_dict))
83
+ predictor=DefaultPredictor(cfg)
84
+ model=predictor.model
85
+ DetectionCheckpointer(model).resume_or_load(os.path.join(cfg.OUTPUT_DIR,'model_final.pth'))
86
+ model.eval()
87
+ config=os.path.join(cfg.OUTPUT_DIR,'config.yaml')
88
+ with open(config,'w')as f:
89
+ f.write(cfg.dump())
90
+ print('Detector training completed!')
91
+
92
+
93
+ def test(self,path_to_annotation,path_to_testingimages,path_to_detector,output_path):
94
+ # path_to_annotation: the path to the .json file that stores the annotations in coco format
95
+ # path_to_testingimages: the folder that stores all the ground-truth testing images
96
+ # output_path: the folder that stores the testing images with annotations
97
+ if str('MPlexA_detector_test')in DatasetCatalog.list():
98
+ DatasetCatalog.remove('MPlexA_detector_test')
99
+ MetadataCatalog.remove('MPlexA_detector_test')
100
+ register_coco_instances('MPlexA_detector_test',{},path_to_annotation,path_to_testingimages)
101
+ datasetcat=DatasetCatalog.get('MPlexA_detector_test')
102
+ metadatacat=MetadataCatalog.get('MPlexA_detector_test')
103
+ cellmapping=os.path.join(path_to_detector,'model_parameters.txt')
104
+ with open(cellmapping)as f:
105
+ model_parameters=f.read()
106
+ cell_names=json.loads(model_parameters)['cell_names']
107
+ dt_infersize=int(json.loads(model_parameters)['inferencing_framesize'])
108
+ bg=int(json.loads(model_parameters)['black_background'])
109
+ print('The total categories of cells in this Detector: '+str(cell_names))
110
+ print('The inferencing framesize of this Detector: '+str(dt_infersize))
111
+ if bg==0:
112
+ print('The images that can be analyzed by this Detector have black/darker background')
113
+ else:
114
+ print('The images that can be analyzed by this Detector have white/lighter background')
115
+ cfg=get_cfg()
116
+ cfg.set_new_allowed(True)
117
+ cfg.merge_from_file(os.path.join(path_to_detector,'config.yaml'))
118
+ cfg.MODEL.WEIGHTS=os.path.join(path_to_detector,'model_final.pth')
119
+ cfg.MODEL.DEVICE=self.device
120
+ predictor=DefaultPredictor(cfg)
121
+ for d in datasetcat:
122
+ im=cv2.imread(d['file_name'])
123
+ outputs=predictor(im)
124
+ v=Visualizer(im[:,:,::-1],MetadataCatalog.get('MPlexA_detector_test'),scale=1.2)
125
+ out=v.draw_instance_predictions(outputs['instances'].to('cpu'))
126
+ cv2.imwrite(os.path.join(output_path,os.path.basename(d['file_name'])),out.get_image()[:,:,::-1])
127
+ evaluator=COCOEvaluator('MPlexA_detector_test',cfg,False,output_dir=output_path)
128
+ val_loader=build_detection_test_loader(cfg,'MPlexA_detector_test')
129
+ inference_on_dataset(predictor.model,val_loader,evaluator)
130
+ mAP=evaluator._results['bbox']['AP']
131
+ print(f'The mean average precision (mAP) of the Detector is: {mAP:.4f}%.')
132
+ print('Detector testing completed!')
133
+
134
+
135
+ def load(self,path_to_detector,cell_kinds):
136
+ # cell_kinds: the catgories of cells / objects to be analyzed
137
+ config=os.path.join(path_to_detector,'config.yaml')
138
+ detector_model=os.path.join(path_to_detector,'model_final.pth')
139
+ cellmapping=os.path.join(path_to_detector,'model_parameters.txt')
140
+ with open(cellmapping)as f:
141
+ model_parameters=f.read()
142
+ self.cell_mapping=json.loads(model_parameters)['cell_mapping']
143
+ cell_names=json.loads(model_parameters)['cell_names']
144
+ self.inferencing_framesize=int(json.loads(model_parameters)['inferencing_framesize'])
145
+ bg=int(json.loads(model_parameters)['black_background'])
146
+ print('The total categories of cells in this Detector: '+str(cell_names))
147
+ print('The cells of interest in this Detector: '+str(cell_kinds))
148
+ print('The inferencing framesize of this Detector: '+str(self.inferencing_framesize))
149
+ if bg==0:
150
+ self.black_background=True
151
+ print('The images that can be analyzed by this Detector have black/darker background')
152
+ else:
153
+ self.black_background=False
154
+ print('The images that can be analyzed by this Detector have white/lighter background')
155
+ cfg=get_cfg()
156
+ cfg.set_new_allowed(True)
157
+ cfg.merge_from_file(config)
158
+ cfg.MODEL.DEVICE=self.device
159
+ self.current_detector=build_model(cfg)
160
+ DetectionCheckpointer(self.current_detector).load(detector_model)
161
+ self.current_detector.eval()
162
+
163
+
164
+ def inference(self,inputs):
165
+ # inputs: images that the current Detector runs on
166
+ with torch.no_grad():
167
+ outputs=self.current_detector(inputs)
168
+ return outputs
169
+
File without changes
@@ -0,0 +1,6 @@
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ from.utils.env import setup_environment
3
+ setup_environment()
4
+ # This line will be programatically read/write by setup.py.
5
+ # Leave them at the bottom of this file and don't touch them.
6
+ __version__='0.6'
@@ -0,0 +1,7 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+ # File:
4
+ from.import catalog as _UNUSED# register the handler
5
+ from.detection_checkpoint import DetectionCheckpointer
6
+ from fvcore.common.checkpoint import Checkpointer,PeriodicCheckpointer
7
+ __all__=['Checkpointer','PeriodicCheckpointer','DetectionCheckpointer']
@@ -0,0 +1,382 @@
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ import copy
3
+ import logging
4
+ import re
5
+ from typing import Dict,List
6
+ import torch
7
+
8
+
9
+ def convert_basic_c2_names(original_keys):
10
+ '''
11
+ Apply some basic name conversion to names in C2 weights.
12
+ It only deals with typical backbone models.
13
+
14
+ Args:
15
+ original_keys (list[str]):
16
+ Returns:
17
+ list[str]: The same number of strings matching those in original_keys.
18
+ '''
19
+ layer_keys=copy.deepcopy(original_keys)
20
+ layer_keys=[
21
+ {'pred_b':'linear_b','pred_w':'linear_w'}.get(k,k)for k in layer_keys
22
+ ]# some hard-coded mappings
23
+ layer_keys=[k.replace('_','.')for k in layer_keys]
24
+ layer_keys=[re.sub('\\.b$','.bias',k)for k in layer_keys]
25
+ layer_keys=[re.sub('\\.w$','.weight',k)for k in layer_keys]
26
+ # Uniform both bn and gn names to "norm"
27
+ layer_keys=[re.sub('bn\\.s$','norm.weight',k)for k in layer_keys]
28
+ layer_keys=[re.sub('bn\\.bias$','norm.bias',k)for k in layer_keys]
29
+ layer_keys=[re.sub('bn\\.rm','norm.running_mean',k)for k in layer_keys]
30
+ layer_keys=[re.sub('bn\\.running.mean$','norm.running_mean',k)for k in layer_keys]
31
+ layer_keys=[re.sub('bn\\.riv$','norm.running_var',k)for k in layer_keys]
32
+ layer_keys=[re.sub('bn\\.running.var$','norm.running_var',k)for k in layer_keys]
33
+ layer_keys=[re.sub('bn\\.gamma$','norm.weight',k)for k in layer_keys]
34
+ layer_keys=[re.sub('bn\\.beta$','norm.bias',k)for k in layer_keys]
35
+ layer_keys=[re.sub('gn\\.s$','norm.weight',k)for k in layer_keys]
36
+ layer_keys=[re.sub('gn\\.bias$','norm.bias',k)for k in layer_keys]
37
+ # stem
38
+ layer_keys=[re.sub('^res\\.conv1\\.norm\\.','conv1.norm.',k)for k in layer_keys]
39
+ # to avoid mis-matching with "conv1" in other components (e.g. detection head)
40
+ layer_keys=[re.sub('^conv1\\.','stem.conv1.',k)for k in layer_keys]
41
+ # layer1-4 is used by torchvision, however we follow the C2 naming strategy (res2-5)
42
+ # layer_keys = [re.sub("^res2.", "layer1.", k) for k in layer_keys]
43
+ # layer_keys = [re.sub("^res3.", "layer2.", k) for k in layer_keys]
44
+ # layer_keys = [re.sub("^res4.", "layer3.", k) for k in layer_keys]
45
+ # layer_keys = [re.sub("^res5.", "layer4.", k) for k in layer_keys]
46
+ # blocks
47
+ layer_keys=[k.replace('.branch1.','.shortcut.')for k in layer_keys]
48
+ layer_keys=[k.replace('.branch2a.','.conv1.')for k in layer_keys]
49
+ layer_keys=[k.replace('.branch2b.','.conv2.')for k in layer_keys]
50
+ layer_keys=[k.replace('.branch2c.','.conv3.')for k in layer_keys]
51
+ # DensePose substitutions
52
+ layer_keys=[re.sub('^body.conv.fcn','body_conv_fcn',k)for k in layer_keys]
53
+ layer_keys=[k.replace('AnnIndex.lowres','ann_index_lowres')for k in layer_keys]
54
+ layer_keys=[k.replace('Index.UV.lowres','index_uv_lowres')for k in layer_keys]
55
+ layer_keys=[k.replace('U.lowres','u_lowres')for k in layer_keys]
56
+ layer_keys=[k.replace('V.lowres','v_lowres')for k in layer_keys]
57
+ return layer_keys
58
+
59
+
60
+ def convert_c2_detectron_names(weights):
61
+ '''
62
+ Map Caffe2 Detectron weight names to Detectron2 names.
63
+
64
+ Args:
65
+ weights (dict): name -> tensor
66
+
67
+ Returns:
68
+ dict: detectron2 names -> tensor
69
+ dict: detectron2 names -> C2 names
70
+ '''
71
+ logger=logging.getLogger(__name__)
72
+ logger.info('Renaming Caffe2 weights ......')
73
+ original_keys=sorted(weights.keys())
74
+ layer_keys=copy.deepcopy(original_keys)
75
+ layer_keys=convert_basic_c2_names(layer_keys)
76
+ # --------------------------------------------------------------------------
77
+ # RPN hidden representation conv
78
+ # --------------------------------------------------------------------------
79
+ # FPN case
80
+ # In the C2 model, the RPN hidden layer conv is defined for FPN level 2 and then
81
+ # shared for all other levels, hence the appearance of "fpn2"
82
+ layer_keys=[
83
+ k.replace('conv.rpn.fpn2','proposal_generator.rpn_head.conv')for k in layer_keys
84
+ ]
85
+ # Non-FPN case
86
+ layer_keys=[k.replace('conv.rpn','proposal_generator.rpn_head.conv')for k in layer_keys]
87
+ # --------------------------------------------------------------------------
88
+ # RPN box transformation conv
89
+ # --------------------------------------------------------------------------
90
+ # FPN case (see note above about "fpn2")
91
+ layer_keys=[
92
+ k.replace('rpn.bbox.pred.fpn2','proposal_generator.rpn_head.anchor_deltas')
93
+ for k in layer_keys
94
+ ]
95
+ layer_keys=[
96
+ k.replace('rpn.cls.logits.fpn2','proposal_generator.rpn_head.objectness_logits')
97
+ for k in layer_keys
98
+ ]
99
+ # Non-FPN case
100
+ layer_keys=[
101
+ k.replace('rpn.bbox.pred','proposal_generator.rpn_head.anchor_deltas')for k in layer_keys
102
+ ]
103
+ layer_keys=[
104
+ k.replace('rpn.cls.logits','proposal_generator.rpn_head.objectness_logits')
105
+ for k in layer_keys
106
+ ]
107
+ # --------------------------------------------------------------------------
108
+ # Fast R-CNN box head
109
+ # --------------------------------------------------------------------------
110
+ layer_keys=[re.sub('^bbox\\.pred','bbox_pred',k)for k in layer_keys]
111
+ layer_keys=[re.sub('^cls\\.score','cls_score',k)for k in layer_keys]
112
+ layer_keys=[re.sub('^fc6\\.','box_head.fc1.',k)for k in layer_keys]
113
+ layer_keys=[re.sub('^fc7\\.','box_head.fc2.',k)for k in layer_keys]
114
+ # 4conv1fc head tensor names: head_conv1_w, head_conv1_gn_s
115
+ layer_keys=[re.sub('^head\\.conv','box_head.conv',k)for k in layer_keys]
116
+ # --------------------------------------------------------------------------
117
+ # FPN lateral and output convolutions
118
+ # --------------------------------------------------------------------------
119
+
120
+
121
+ def fpn_map(name):
122
+ '''
123
+ Look for keys with the following patterns:
124
+ 1) Starts with "fpn.inner."
125
+ Example: "fpn.inner.res2.2.sum.lateral.weight"
126
+ Meaning: These are lateral pathway convolutions
127
+ 2) Starts with "fpn.res"
128
+ Example: "fpn.res2.2.sum.weight"
129
+ Meaning: These are FPN output convolutions
130
+ '''
131
+ splits=name.split('.')
132
+ norm='.norm'if'norm'in splits else''
133
+ if name.startswith('fpn.inner.'):
134
+ # splits example: ['fpn', 'inner', 'res2', '2', 'sum', 'lateral', 'weight']
135
+ stage=int(splits[2][len('res'):])
136
+ return'fpn_lateral{}{}.{}'.format(stage,norm,splits[-1])
137
+ elif name.startswith('fpn.res'):
138
+ # splits example: ['fpn', 'res2', '2', 'sum', 'weight']
139
+ stage=int(splits[1][len('res'):])
140
+ return'fpn_output{}{}.{}'.format(stage,norm,splits[-1])
141
+ return name
142
+ layer_keys=[fpn_map(k)for k in layer_keys]
143
+ # --------------------------------------------------------------------------
144
+ # Mask R-CNN mask head
145
+ # --------------------------------------------------------------------------
146
+ # roi_heads.StandardROIHeads case
147
+ layer_keys=[k.replace('.[mask].fcn','mask_head.mask_fcn')for k in layer_keys]
148
+ layer_keys=[re.sub('^\\.mask\\.fcn','mask_head.mask_fcn',k)for k in layer_keys]
149
+ layer_keys=[k.replace('mask.fcn.logits','mask_head.predictor')for k in layer_keys]
150
+ # roi_heads.Res5ROIHeads case
151
+ layer_keys=[k.replace('conv5.mask','mask_head.deconv')for k in layer_keys]
152
+ # --------------------------------------------------------------------------
153
+ # Keypoint R-CNN head
154
+ # --------------------------------------------------------------------------
155
+ # interestingly, the keypoint head convs have blob names that are simply "conv_fcnX"
156
+ layer_keys=[k.replace('conv.fcn','roi_heads.keypoint_head.conv_fcn')for k in layer_keys]
157
+ layer_keys=[
158
+ k.replace('kps.score.lowres','roi_heads.keypoint_head.score_lowres')for k in layer_keys
159
+ ]
160
+ layer_keys=[k.replace('kps.score.','roi_heads.keypoint_head.score.')for k in layer_keys]
161
+ # --------------------------------------------------------------------------
162
+ # Done with replacements
163
+ # --------------------------------------------------------------------------
164
+ assert len(set(layer_keys))==len(layer_keys)
165
+ assert len(original_keys)==len(layer_keys)
166
+ new_weights={}
167
+ new_keys_to_original_keys={}
168
+ for orig,renamed in zip(original_keys,layer_keys):
169
+ new_keys_to_original_keys[renamed]=orig
170
+ if renamed.startswith('bbox_pred.')or renamed.startswith('mask_head.predictor.'):
171
+ # remove the meaningless prediction weight for background class
172
+ new_start_idx=4 if renamed.startswith('bbox_pred.')else 1
173
+ new_weights[renamed]=weights[orig][new_start_idx:]
174
+ logger.info(
175
+ 'Remove prediction weight for background class in {}. The shape changes from '
176
+ '{} to {}.'.format(
177
+ renamed,tuple(weights[orig].shape),tuple(new_weights[renamed].shape)
178
+ )
179
+ )
180
+ elif renamed.startswith('cls_score.'):
181
+ # move weights of bg class from original index 0 to last index
182
+ logger.info(
183
+ 'Move classification weights for background class in {} from index 0 to '
184
+ 'index {}.'.format(renamed,weights[orig].shape[0]-1)
185
+ )
186
+ new_weights[renamed]=torch.cat([weights[orig][1:],weights[orig][:1]])
187
+ else:
188
+ new_weights[renamed]=weights[orig]
189
+ return new_weights,new_keys_to_original_keys
190
+ # Note the current matching is not symmetric.
191
+ # it assumes model_state_dict will have longer names.
192
+
193
+
194
+ def align_and_update_state_dicts(model_state_dict,ckpt_state_dict,c2_conversion=True):
195
+ '''
196
+ Match names between the two state-dict, and returns a new chkpt_state_dict with names
197
+ converted to match model_state_dict with heuristics. The returned dict can be later
198
+ loaded with fvcore checkpointer.
199
+ If `c2_conversion==True`, `ckpt_state_dict` is assumed to be a Caffe2
200
+ model and will be renamed at first.
201
+
202
+ Strategy: suppose that the models that we will create will have prefixes appended
203
+ to each of its keys, for example due to an extra level of nesting that the original
204
+ pre-trained weights from ImageNet won't contain. For example, model.state_dict()
205
+ might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains
206
+ res2.conv1.weight. We thus want to match both parameters together.
207
+ For that, we look for each model weight, look among all loaded keys if there is one
208
+ that is a suffix of the current weight name, and use it if that's the case.
209
+ If multiple matches exist, take the one with longest size
210
+ of the corresponding name. For example, for the same model as before, the pretrained
211
+ weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case,
212
+ we want to match backbone[0].body.conv1.weight to conv1.weight, and
213
+ backbone[0].body.res2.conv1.weight to res2.conv1.weight.
214
+ '''
215
+ model_keys=sorted(model_state_dict.keys())
216
+ if c2_conversion:
217
+ ckpt_state_dict,original_keys=convert_c2_detectron_names(ckpt_state_dict)
218
+ # original_keys: the name in the original dict (before renaming)
219
+ else:
220
+ original_keys={x:x for x in ckpt_state_dict.keys()}
221
+ ckpt_keys=sorted(ckpt_state_dict.keys())
222
+
223
+
224
+ def match(a,b):
225
+ # Matched ckpt_key should be a complete (starts with '.') suffix.
226
+ # For example, roi_heads.mesh_head.whatever_conv1 does not match conv1,
227
+ # but matches whatever_conv1 or mesh_head.whatever_conv1.
228
+ return a==b or a.endswith('.'+b)
229
+ # get a matrix of string matches, where each (i, j) entry correspond to the size of the
230
+ # ckpt_key string, if it matches
231
+ match_matrix=[len(j)if match(i,j)else 0 for i in model_keys for j in ckpt_keys]
232
+ match_matrix=torch.as_tensor(match_matrix).view(len(model_keys),len(ckpt_keys))
233
+ # use the matched one with longest size in case of multiple matches
234
+ max_match_size,idxs=match_matrix.max(1)
235
+ # remove indices that correspond to no-match
236
+ idxs[max_match_size==0]=-1
237
+ logger=logging.getLogger(__name__)
238
+ # matched_pairs (matched checkpoint key --> matched model key)
239
+ matched_keys={}
240
+ result_state_dict={}
241
+ for idx_model,idx_ckpt in enumerate(idxs.tolist()):
242
+ if idx_ckpt==-1:
243
+ continue
244
+ key_model=model_keys[idx_model]
245
+ key_ckpt=ckpt_keys[idx_ckpt]
246
+ value_ckpt=ckpt_state_dict[key_ckpt]
247
+ shape_in_model=model_state_dict[key_model].shape
248
+ if shape_in_model!=value_ckpt.shape:
249
+ logger.warning(
250
+ 'Shape of {} in checkpoint is {}, while shape of {} in model is {}.'.format(
251
+ key_ckpt,value_ckpt.shape,key_model,shape_in_model
252
+ )
253
+ )
254
+ logger.warning(
255
+ '{} will not be loaded. Please double check and see if this is desired.'.format(
256
+ key_ckpt
257
+ )
258
+ )
259
+ continue
260
+ assert key_model not in result_state_dict
261
+ result_state_dict[key_model]=value_ckpt
262
+ if key_ckpt in matched_keys:# already added to matched_keys
263
+ logger.error(
264
+ 'Ambiguity found for {} in checkpoint!'
265
+ 'It matches at least two keys in the model ({} and {}).'.format(
266
+ key_ckpt,key_model,matched_keys[key_ckpt]
267
+ )
268
+ )
269
+ raise ValueError('Cannot match one checkpoint key to multiple keys in the model.')
270
+ matched_keys[key_ckpt]=key_model
271
+ # logging:
272
+ matched_model_keys=sorted(matched_keys.values())
273
+ if len(matched_model_keys)==0:
274
+ logger.warning('No weights in checkpoint matched with model.')
275
+ return ckpt_state_dict
276
+ common_prefix=_longest_common_prefix(matched_model_keys)
277
+ rev_matched_keys={v:k for k,v in matched_keys.items()}
278
+ original_keys={k:original_keys[rev_matched_keys[k]]for k in matched_model_keys}
279
+ model_key_groups=_group_keys_by_module(matched_model_keys,original_keys)
280
+ table=[]
281
+ memo=set()
282
+ for key_model in matched_model_keys:
283
+ if key_model in memo:
284
+ continue
285
+ if key_model in model_key_groups:
286
+ group=model_key_groups[key_model]
287
+ memo|=set(group)
288
+ shapes=[tuple(model_state_dict[k].shape)for k in group]
289
+ table.append(
290
+ (
291
+ _longest_common_prefix([k[len(common_prefix):]for k in group])+'*',
292
+ _group_str([original_keys[k]for k in group]),
293
+ ' '.join([str(x).replace(' ','')for x in shapes]),
294
+ )
295
+ )
296
+ else:
297
+ key_checkpoint=original_keys[key_model]
298
+ shape=str(tuple(model_state_dict[key_model].shape))
299
+ table.append((key_model[len(common_prefix):],key_checkpoint,shape))
300
+ submodule_str=common_prefix[:-1]if common_prefix else'model'
301
+ logger.info(
302
+ f'Following weights matched with submodule {submodule_str} - Total num: {len(table)}'
303
+ )
304
+ unmatched_ckpt_keys=[k for k in ckpt_keys if k not in set(matched_keys.keys())]
305
+ for k in unmatched_ckpt_keys:
306
+ result_state_dict[k]=ckpt_state_dict[k]
307
+ return result_state_dict
308
+
309
+
310
+ def _group_keys_by_module(keys:List[str],original_names:Dict[str,str]):
311
+ '''
312
+ Params in the same submodule are grouped together.
313
+
314
+ Args:
315
+ keys: names of all parameters
316
+ original_names: mapping from parameter name to their name in the checkpoint
317
+
318
+ Returns:
319
+ dict[name -> all other names in the same group]
320
+ '''
321
+
322
+
323
+ def _submodule_name(key):
324
+ pos=key.rfind('.')
325
+ if pos<0:
326
+ return None
327
+ prefix=key[:pos+1]
328
+ return prefix
329
+ all_submodules=[_submodule_name(k)for k in keys]
330
+ all_submodules=[x for x in all_submodules if x]
331
+ all_submodules=sorted(all_submodules,key=len)
332
+ ret={}
333
+ for prefix in all_submodules:
334
+ group=[k for k in keys if k.startswith(prefix)]
335
+ if len(group)<=1:
336
+ continue
337
+ original_name_lcp=_longest_common_prefix_str([original_names[k]for k in group])
338
+ if len(original_name_lcp)==0:
339
+ # don't group weights if original names don't share prefix
340
+ continue
341
+ for k in group:
342
+ if k in ret:
343
+ continue
344
+ ret[k]=group
345
+ return ret
346
+
347
+
348
+ def _longest_common_prefix(names:List[str])->str:
349
+ '''
350
+ ["abc.zfg", "abc.zef"] -> "abc."
351
+ '''
352
+ names=[n.split('.')for n in names]
353
+ m1,m2=min(names),max(names)
354
+ ret=[a for a,b in zip(m1,m2)if a==b]
355
+ ret='.'.join(ret)+'.'if len(ret)else''
356
+ return ret
357
+
358
+
359
+ def _longest_common_prefix_str(names:List[str])->str:
360
+ m1,m2=min(names),max(names)
361
+ lcp=[]
362
+ for a,b in zip(m1,m2):
363
+ if a==b:
364
+ lcp.append(a)
365
+ else:
366
+ break
367
+ lcp=''.join(lcp)
368
+ return lcp
369
+
370
+
371
+ def _group_str(names:List[str])->str:
372
+ '''
373
+ Turn "common1", "common2", "common3" into "common{1,2,3}"
374
+ '''
375
+ lcp=_longest_common_prefix_str(names)
376
+ rest=[x[len(lcp):]for x in names]
377
+ rest='{'+','.join(rest)+'}'
378
+ ret=lcp+rest
379
+ # add some simplification for BN specifically
380
+ ret=ret.replace('bn_{beta,running_mean,running_var,gamma}','bn_*')
381
+ ret=ret.replace('bn_beta,bn_running_mean,bn_running_var,bn_gamma','bn_*')
382
+ return ret