Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- FateZero-main/data/shape/man_skate/00003.png +3 -0
- RAVE-main/annotator/oneformer/detectron2/__init__.py +10 -0
- RAVE-main/annotator/oneformer/detectron2/checkpoint/__init__.py +10 -0
- RAVE-main/annotator/oneformer/detectron2/checkpoint/c2_model_loading.py +412 -0
- RAVE-main/annotator/oneformer/detectron2/checkpoint/catalog.py +115 -0
- RAVE-main/annotator/oneformer/detectron2/checkpoint/detection_checkpoint.py +145 -0
- RAVE-main/annotator/oneformer/detectron2/config/__init__.py +24 -0
- RAVE-main/annotator/oneformer/detectron2/config/compat.py +229 -0
- RAVE-main/annotator/oneformer/detectron2/config/config.py +265 -0
- RAVE-main/annotator/oneformer/detectron2/config/defaults.py +650 -0
- RAVE-main/annotator/oneformer/detectron2/config/instantiate.py +88 -0
- RAVE-main/annotator/oneformer/detectron2/config/lazy.py +435 -0
- RAVE-main/annotator/oneformer/detectron2/engine/defaults.py +715 -0
- RAVE-main/annotator/oneformer/detectron2/engine/hooks.py +690 -0
- RAVE-main/annotator/oneformer/detectron2/engine/launch.py +123 -0
- RAVE-main/annotator/oneformer/detectron2/engine/train_loop.py +469 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/__init__.py +12 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/cityscapes_evaluation.py +197 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/coco_evaluation.py +722 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/evaluator.py +224 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/fast_eval_api.py +121 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/lvis_evaluation.py +380 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/panoptic_evaluation.py +199 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/pascal_voc_evaluation.py +300 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/rotated_coco_evaluation.py +207 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/sem_seg_evaluation.py +265 -0
- RAVE-main/annotator/oneformer/detectron2/evaluation/testing.py +85 -0
- RAVE-main/annotator/oneformer/detectron2/model_zoo/__init__.py +10 -0
- RAVE-main/annotator/oneformer/detectron2/model_zoo/model_zoo.py +213 -0
- RAVE-main/annotator/oneformer/detectron2/projects/README.md +2 -0
- RAVE-main/annotator/oneformer/detectron2/projects/__init__.py +34 -0
- RAVE-main/annotator/oneformer/detectron2/projects/deeplab/__init__.py +5 -0
- RAVE-main/annotator/oneformer/detectron2/projects/deeplab/build_solver.py +27 -0
- RAVE-main/annotator/oneformer/detectron2/projects/deeplab/config.py +28 -0
- RAVE-main/annotator/oneformer/detectron2/projects/deeplab/loss.py +40 -0
- RAVE-main/annotator/oneformer/detectron2/projects/deeplab/lr_scheduler.py +62 -0
- RAVE-main/annotator/oneformer/detectron2/projects/deeplab/resnet.py +158 -0
- RAVE-main/annotator/oneformer/detectron2/projects/deeplab/semantic_seg.py +348 -0
- RAVE-main/annotator/oneformer/detectron2/tracking/__init__.py +15 -0
- RAVE-main/annotator/oneformer/detectron2/tracking/base_tracker.py +64 -0
- RAVE-main/annotator/oneformer/detectron2/tracking/bbox_iou_tracker.py +276 -0
- RAVE-main/annotator/oneformer/detectron2/tracking/hungarian_tracker.py +171 -0
- RAVE-main/annotator/oneformer/detectron2/tracking/iou_weighted_hungarian_bbox_iou_tracker.py +102 -0
- RAVE-main/annotator/oneformer/detectron2/tracking/utils.py +40 -0
- RAVE-main/annotator/oneformer/detectron2/tracking/vanilla_hungarian_bbox_iou_tracker.py +129 -0
- RAVE-main/annotator/oneformer/detectron2/utils/README.md +5 -0
- RAVE-main/annotator/oneformer/detectron2/utils/colormap.py +158 -0
- RAVE-main/annotator/oneformer/detectron2/utils/env.py +170 -0
- RAVE-main/annotator/oneformer/detectron2/utils/events.py +534 -0
- RAVE-main/annotator/oneformer/detectron2/utils/file_io.py +39 -0
FateZero-main/data/shape/man_skate/00003.png
ADDED
|
Git LFS Details
|
RAVE-main/annotator/oneformer/detectron2/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
|
| 3 |
+
from .utils.env import setup_environment
|
| 4 |
+
|
| 5 |
+
setup_environment()
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# This line will be programatically read/write by setup.py.
|
| 9 |
+
# Leave them at the bottom of this file and don't touch them.
|
| 10 |
+
__version__ = "0.6"
|
RAVE-main/annotator/oneformer/detectron2/checkpoint/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
# File:
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from . import catalog as _UNUSED # register the handler
|
| 7 |
+
from .detection_checkpoint import DetectionCheckpointer
|
| 8 |
+
from fvcore.common.checkpoint import Checkpointer, PeriodicCheckpointer
|
| 9 |
+
|
| 10 |
+
__all__ = ["Checkpointer", "PeriodicCheckpointer", "DetectionCheckpointer"]
|
RAVE-main/annotator/oneformer/detectron2/checkpoint/c2_model_loading.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from tabulate import tabulate
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def convert_basic_c2_names(original_keys):
|
| 11 |
+
"""
|
| 12 |
+
Apply some basic name conversion to names in C2 weights.
|
| 13 |
+
It only deals with typical backbone models.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
original_keys (list[str]):
|
| 17 |
+
Returns:
|
| 18 |
+
list[str]: The same number of strings matching those in original_keys.
|
| 19 |
+
"""
|
| 20 |
+
layer_keys = copy.deepcopy(original_keys)
|
| 21 |
+
layer_keys = [
|
| 22 |
+
{"pred_b": "linear_b", "pred_w": "linear_w"}.get(k, k) for k in layer_keys
|
| 23 |
+
] # some hard-coded mappings
|
| 24 |
+
|
| 25 |
+
layer_keys = [k.replace("_", ".") for k in layer_keys]
|
| 26 |
+
layer_keys = [re.sub("\\.b$", ".bias", k) for k in layer_keys]
|
| 27 |
+
layer_keys = [re.sub("\\.w$", ".weight", k) for k in layer_keys]
|
| 28 |
+
# Uniform both bn and gn names to "norm"
|
| 29 |
+
layer_keys = [re.sub("bn\\.s$", "norm.weight", k) for k in layer_keys]
|
| 30 |
+
layer_keys = [re.sub("bn\\.bias$", "norm.bias", k) for k in layer_keys]
|
| 31 |
+
layer_keys = [re.sub("bn\\.rm", "norm.running_mean", k) for k in layer_keys]
|
| 32 |
+
layer_keys = [re.sub("bn\\.running.mean$", "norm.running_mean", k) for k in layer_keys]
|
| 33 |
+
layer_keys = [re.sub("bn\\.riv$", "norm.running_var", k) for k in layer_keys]
|
| 34 |
+
layer_keys = [re.sub("bn\\.running.var$", "norm.running_var", k) for k in layer_keys]
|
| 35 |
+
layer_keys = [re.sub("bn\\.gamma$", "norm.weight", k) for k in layer_keys]
|
| 36 |
+
layer_keys = [re.sub("bn\\.beta$", "norm.bias", k) for k in layer_keys]
|
| 37 |
+
layer_keys = [re.sub("gn\\.s$", "norm.weight", k) for k in layer_keys]
|
| 38 |
+
layer_keys = [re.sub("gn\\.bias$", "norm.bias", k) for k in layer_keys]
|
| 39 |
+
|
| 40 |
+
# stem
|
| 41 |
+
layer_keys = [re.sub("^res\\.conv1\\.norm\\.", "conv1.norm.", k) for k in layer_keys]
|
| 42 |
+
# to avoid mis-matching with "conv1" in other components (e.g. detection head)
|
| 43 |
+
layer_keys = [re.sub("^conv1\\.", "stem.conv1.", k) for k in layer_keys]
|
| 44 |
+
|
| 45 |
+
# layer1-4 is used by torchvision, however we follow the C2 naming strategy (res2-5)
|
| 46 |
+
# layer_keys = [re.sub("^res2.", "layer1.", k) for k in layer_keys]
|
| 47 |
+
# layer_keys = [re.sub("^res3.", "layer2.", k) for k in layer_keys]
|
| 48 |
+
# layer_keys = [re.sub("^res4.", "layer3.", k) for k in layer_keys]
|
| 49 |
+
# layer_keys = [re.sub("^res5.", "layer4.", k) for k in layer_keys]
|
| 50 |
+
|
| 51 |
+
# blocks
|
| 52 |
+
layer_keys = [k.replace(".branch1.", ".shortcut.") for k in layer_keys]
|
| 53 |
+
layer_keys = [k.replace(".branch2a.", ".conv1.") for k in layer_keys]
|
| 54 |
+
layer_keys = [k.replace(".branch2b.", ".conv2.") for k in layer_keys]
|
| 55 |
+
layer_keys = [k.replace(".branch2c.", ".conv3.") for k in layer_keys]
|
| 56 |
+
|
| 57 |
+
# DensePose substitutions
|
| 58 |
+
layer_keys = [re.sub("^body.conv.fcn", "body_conv_fcn", k) for k in layer_keys]
|
| 59 |
+
layer_keys = [k.replace("AnnIndex.lowres", "ann_index_lowres") for k in layer_keys]
|
| 60 |
+
layer_keys = [k.replace("Index.UV.lowres", "index_uv_lowres") for k in layer_keys]
|
| 61 |
+
layer_keys = [k.replace("U.lowres", "u_lowres") for k in layer_keys]
|
| 62 |
+
layer_keys = [k.replace("V.lowres", "v_lowres") for k in layer_keys]
|
| 63 |
+
return layer_keys
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def convert_c2_detectron_names(weights):
|
| 67 |
+
"""
|
| 68 |
+
Map Caffe2 Detectron weight names to Detectron2 names.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
weights (dict): name -> tensor
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
dict: detectron2 names -> tensor
|
| 75 |
+
dict: detectron2 names -> C2 names
|
| 76 |
+
"""
|
| 77 |
+
logger = logging.getLogger(__name__)
|
| 78 |
+
logger.info("Renaming Caffe2 weights ......")
|
| 79 |
+
original_keys = sorted(weights.keys())
|
| 80 |
+
layer_keys = copy.deepcopy(original_keys)
|
| 81 |
+
|
| 82 |
+
layer_keys = convert_basic_c2_names(layer_keys)
|
| 83 |
+
|
| 84 |
+
# --------------------------------------------------------------------------
|
| 85 |
+
# RPN hidden representation conv
|
| 86 |
+
# --------------------------------------------------------------------------
|
| 87 |
+
# FPN case
|
| 88 |
+
# In the C2 model, the RPN hidden layer conv is defined for FPN level 2 and then
|
| 89 |
+
# shared for all other levels, hence the appearance of "fpn2"
|
| 90 |
+
layer_keys = [
|
| 91 |
+
k.replace("conv.rpn.fpn2", "proposal_generator.rpn_head.conv") for k in layer_keys
|
| 92 |
+
]
|
| 93 |
+
# Non-FPN case
|
| 94 |
+
layer_keys = [k.replace("conv.rpn", "proposal_generator.rpn_head.conv") for k in layer_keys]
|
| 95 |
+
|
| 96 |
+
# --------------------------------------------------------------------------
|
| 97 |
+
# RPN box transformation conv
|
| 98 |
+
# --------------------------------------------------------------------------
|
| 99 |
+
# FPN case (see note above about "fpn2")
|
| 100 |
+
layer_keys = [
|
| 101 |
+
k.replace("rpn.bbox.pred.fpn2", "proposal_generator.rpn_head.anchor_deltas")
|
| 102 |
+
for k in layer_keys
|
| 103 |
+
]
|
| 104 |
+
layer_keys = [
|
| 105 |
+
k.replace("rpn.cls.logits.fpn2", "proposal_generator.rpn_head.objectness_logits")
|
| 106 |
+
for k in layer_keys
|
| 107 |
+
]
|
| 108 |
+
# Non-FPN case
|
| 109 |
+
layer_keys = [
|
| 110 |
+
k.replace("rpn.bbox.pred", "proposal_generator.rpn_head.anchor_deltas") for k in layer_keys
|
| 111 |
+
]
|
| 112 |
+
layer_keys = [
|
| 113 |
+
k.replace("rpn.cls.logits", "proposal_generator.rpn_head.objectness_logits")
|
| 114 |
+
for k in layer_keys
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
# --------------------------------------------------------------------------
|
| 118 |
+
# Fast R-CNN box head
|
| 119 |
+
# --------------------------------------------------------------------------
|
| 120 |
+
layer_keys = [re.sub("^bbox\\.pred", "bbox_pred", k) for k in layer_keys]
|
| 121 |
+
layer_keys = [re.sub("^cls\\.score", "cls_score", k) for k in layer_keys]
|
| 122 |
+
layer_keys = [re.sub("^fc6\\.", "box_head.fc1.", k) for k in layer_keys]
|
| 123 |
+
layer_keys = [re.sub("^fc7\\.", "box_head.fc2.", k) for k in layer_keys]
|
| 124 |
+
# 4conv1fc head tensor names: head_conv1_w, head_conv1_gn_s
|
| 125 |
+
layer_keys = [re.sub("^head\\.conv", "box_head.conv", k) for k in layer_keys]
|
| 126 |
+
|
| 127 |
+
# --------------------------------------------------------------------------
|
| 128 |
+
# FPN lateral and output convolutions
|
| 129 |
+
# --------------------------------------------------------------------------
|
| 130 |
+
def fpn_map(name):
|
| 131 |
+
"""
|
| 132 |
+
Look for keys with the following patterns:
|
| 133 |
+
1) Starts with "fpn.inner."
|
| 134 |
+
Example: "fpn.inner.res2.2.sum.lateral.weight"
|
| 135 |
+
Meaning: These are lateral pathway convolutions
|
| 136 |
+
2) Starts with "fpn.res"
|
| 137 |
+
Example: "fpn.res2.2.sum.weight"
|
| 138 |
+
Meaning: These are FPN output convolutions
|
| 139 |
+
"""
|
| 140 |
+
splits = name.split(".")
|
| 141 |
+
norm = ".norm" if "norm" in splits else ""
|
| 142 |
+
if name.startswith("fpn.inner."):
|
| 143 |
+
# splits example: ['fpn', 'inner', 'res2', '2', 'sum', 'lateral', 'weight']
|
| 144 |
+
stage = int(splits[2][len("res") :])
|
| 145 |
+
return "fpn_lateral{}{}.{}".format(stage, norm, splits[-1])
|
| 146 |
+
elif name.startswith("fpn.res"):
|
| 147 |
+
# splits example: ['fpn', 'res2', '2', 'sum', 'weight']
|
| 148 |
+
stage = int(splits[1][len("res") :])
|
| 149 |
+
return "fpn_output{}{}.{}".format(stage, norm, splits[-1])
|
| 150 |
+
return name
|
| 151 |
+
|
| 152 |
+
layer_keys = [fpn_map(k) for k in layer_keys]
|
| 153 |
+
|
| 154 |
+
# --------------------------------------------------------------------------
|
| 155 |
+
# Mask R-CNN mask head
|
| 156 |
+
# --------------------------------------------------------------------------
|
| 157 |
+
# roi_heads.StandardROIHeads case
|
| 158 |
+
layer_keys = [k.replace(".[mask].fcn", "mask_head.mask_fcn") for k in layer_keys]
|
| 159 |
+
layer_keys = [re.sub("^\\.mask\\.fcn", "mask_head.mask_fcn", k) for k in layer_keys]
|
| 160 |
+
layer_keys = [k.replace("mask.fcn.logits", "mask_head.predictor") for k in layer_keys]
|
| 161 |
+
# roi_heads.Res5ROIHeads case
|
| 162 |
+
layer_keys = [k.replace("conv5.mask", "mask_head.deconv") for k in layer_keys]
|
| 163 |
+
|
| 164 |
+
# --------------------------------------------------------------------------
|
| 165 |
+
# Keypoint R-CNN head
|
| 166 |
+
# --------------------------------------------------------------------------
|
| 167 |
+
# interestingly, the keypoint head convs have blob names that are simply "conv_fcnX"
|
| 168 |
+
layer_keys = [k.replace("conv.fcn", "roi_heads.keypoint_head.conv_fcn") for k in layer_keys]
|
| 169 |
+
layer_keys = [
|
| 170 |
+
k.replace("kps.score.lowres", "roi_heads.keypoint_head.score_lowres") for k in layer_keys
|
| 171 |
+
]
|
| 172 |
+
layer_keys = [k.replace("kps.score.", "roi_heads.keypoint_head.score.") for k in layer_keys]
|
| 173 |
+
|
| 174 |
+
# --------------------------------------------------------------------------
|
| 175 |
+
# Done with replacements
|
| 176 |
+
# --------------------------------------------------------------------------
|
| 177 |
+
assert len(set(layer_keys)) == len(layer_keys)
|
| 178 |
+
assert len(original_keys) == len(layer_keys)
|
| 179 |
+
|
| 180 |
+
new_weights = {}
|
| 181 |
+
new_keys_to_original_keys = {}
|
| 182 |
+
for orig, renamed in zip(original_keys, layer_keys):
|
| 183 |
+
new_keys_to_original_keys[renamed] = orig
|
| 184 |
+
if renamed.startswith("bbox_pred.") or renamed.startswith("mask_head.predictor."):
|
| 185 |
+
# remove the meaningless prediction weight for background class
|
| 186 |
+
new_start_idx = 4 if renamed.startswith("bbox_pred.") else 1
|
| 187 |
+
new_weights[renamed] = weights[orig][new_start_idx:]
|
| 188 |
+
logger.info(
|
| 189 |
+
"Remove prediction weight for background class in {}. The shape changes from "
|
| 190 |
+
"{} to {}.".format(
|
| 191 |
+
renamed, tuple(weights[orig].shape), tuple(new_weights[renamed].shape)
|
| 192 |
+
)
|
| 193 |
+
)
|
| 194 |
+
elif renamed.startswith("cls_score."):
|
| 195 |
+
# move weights of bg class from original index 0 to last index
|
| 196 |
+
logger.info(
|
| 197 |
+
"Move classification weights for background class in {} from index 0 to "
|
| 198 |
+
"index {}.".format(renamed, weights[orig].shape[0] - 1)
|
| 199 |
+
)
|
| 200 |
+
new_weights[renamed] = torch.cat([weights[orig][1:], weights[orig][:1]])
|
| 201 |
+
else:
|
| 202 |
+
new_weights[renamed] = weights[orig]
|
| 203 |
+
|
| 204 |
+
return new_weights, new_keys_to_original_keys
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# Note the current matching is not symmetric.
|
| 208 |
+
# it assumes model_state_dict will have longer names.
|
| 209 |
+
def align_and_update_state_dicts(model_state_dict, ckpt_state_dict, c2_conversion=True):
|
| 210 |
+
"""
|
| 211 |
+
Match names between the two state-dict, and returns a new chkpt_state_dict with names
|
| 212 |
+
converted to match model_state_dict with heuristics. The returned dict can be later
|
| 213 |
+
loaded with fvcore checkpointer.
|
| 214 |
+
If `c2_conversion==True`, `ckpt_state_dict` is assumed to be a Caffe2
|
| 215 |
+
model and will be renamed at first.
|
| 216 |
+
|
| 217 |
+
Strategy: suppose that the models that we will create will have prefixes appended
|
| 218 |
+
to each of its keys, for example due to an extra level of nesting that the original
|
| 219 |
+
pre-trained weights from ImageNet won't contain. For example, model.state_dict()
|
| 220 |
+
might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains
|
| 221 |
+
res2.conv1.weight. We thus want to match both parameters together.
|
| 222 |
+
For that, we look for each model weight, look among all loaded keys if there is one
|
| 223 |
+
that is a suffix of the current weight name, and use it if that's the case.
|
| 224 |
+
If multiple matches exist, take the one with longest size
|
| 225 |
+
of the corresponding name. For example, for the same model as before, the pretrained
|
| 226 |
+
weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case,
|
| 227 |
+
we want to match backbone[0].body.conv1.weight to conv1.weight, and
|
| 228 |
+
backbone[0].body.res2.conv1.weight to res2.conv1.weight.
|
| 229 |
+
"""
|
| 230 |
+
model_keys = sorted(model_state_dict.keys())
|
| 231 |
+
if c2_conversion:
|
| 232 |
+
ckpt_state_dict, original_keys = convert_c2_detectron_names(ckpt_state_dict)
|
| 233 |
+
# original_keys: the name in the original dict (before renaming)
|
| 234 |
+
else:
|
| 235 |
+
original_keys = {x: x for x in ckpt_state_dict.keys()}
|
| 236 |
+
ckpt_keys = sorted(ckpt_state_dict.keys())
|
| 237 |
+
|
| 238 |
+
def match(a, b):
|
| 239 |
+
# Matched ckpt_key should be a complete (starts with '.') suffix.
|
| 240 |
+
# For example, roi_heads.mesh_head.whatever_conv1 does not match conv1,
|
| 241 |
+
# but matches whatever_conv1 or mesh_head.whatever_conv1.
|
| 242 |
+
return a == b or a.endswith("." + b)
|
| 243 |
+
|
| 244 |
+
# get a matrix of string matches, where each (i, j) entry correspond to the size of the
|
| 245 |
+
# ckpt_key string, if it matches
|
| 246 |
+
match_matrix = [len(j) if match(i, j) else 0 for i in model_keys for j in ckpt_keys]
|
| 247 |
+
match_matrix = torch.as_tensor(match_matrix).view(len(model_keys), len(ckpt_keys))
|
| 248 |
+
# use the matched one with longest size in case of multiple matches
|
| 249 |
+
max_match_size, idxs = match_matrix.max(1)
|
| 250 |
+
# remove indices that correspond to no-match
|
| 251 |
+
idxs[max_match_size == 0] = -1
|
| 252 |
+
|
| 253 |
+
logger = logging.getLogger(__name__)
|
| 254 |
+
# matched_pairs (matched checkpoint key --> matched model key)
|
| 255 |
+
matched_keys = {}
|
| 256 |
+
result_state_dict = {}
|
| 257 |
+
for idx_model, idx_ckpt in enumerate(idxs.tolist()):
|
| 258 |
+
if idx_ckpt == -1:
|
| 259 |
+
continue
|
| 260 |
+
key_model = model_keys[idx_model]
|
| 261 |
+
key_ckpt = ckpt_keys[idx_ckpt]
|
| 262 |
+
value_ckpt = ckpt_state_dict[key_ckpt]
|
| 263 |
+
shape_in_model = model_state_dict[key_model].shape
|
| 264 |
+
|
| 265 |
+
if shape_in_model != value_ckpt.shape:
|
| 266 |
+
logger.warning(
|
| 267 |
+
"Shape of {} in checkpoint is {}, while shape of {} in model is {}.".format(
|
| 268 |
+
key_ckpt, value_ckpt.shape, key_model, shape_in_model
|
| 269 |
+
)
|
| 270 |
+
)
|
| 271 |
+
logger.warning(
|
| 272 |
+
"{} will not be loaded. Please double check and see if this is desired.".format(
|
| 273 |
+
key_ckpt
|
| 274 |
+
)
|
| 275 |
+
)
|
| 276 |
+
continue
|
| 277 |
+
|
| 278 |
+
assert key_model not in result_state_dict
|
| 279 |
+
result_state_dict[key_model] = value_ckpt
|
| 280 |
+
if key_ckpt in matched_keys: # already added to matched_keys
|
| 281 |
+
logger.error(
|
| 282 |
+
"Ambiguity found for {} in checkpoint!"
|
| 283 |
+
"It matches at least two keys in the model ({} and {}).".format(
|
| 284 |
+
key_ckpt, key_model, matched_keys[key_ckpt]
|
| 285 |
+
)
|
| 286 |
+
)
|
| 287 |
+
raise ValueError("Cannot match one checkpoint key to multiple keys in the model.")
|
| 288 |
+
|
| 289 |
+
matched_keys[key_ckpt] = key_model
|
| 290 |
+
|
| 291 |
+
# logging:
|
| 292 |
+
matched_model_keys = sorted(matched_keys.values())
|
| 293 |
+
if len(matched_model_keys) == 0:
|
| 294 |
+
logger.warning("No weights in checkpoint matched with model.")
|
| 295 |
+
return ckpt_state_dict
|
| 296 |
+
common_prefix = _longest_common_prefix(matched_model_keys)
|
| 297 |
+
rev_matched_keys = {v: k for k, v in matched_keys.items()}
|
| 298 |
+
original_keys = {k: original_keys[rev_matched_keys[k]] for k in matched_model_keys}
|
| 299 |
+
|
| 300 |
+
model_key_groups = _group_keys_by_module(matched_model_keys, original_keys)
|
| 301 |
+
table = []
|
| 302 |
+
memo = set()
|
| 303 |
+
for key_model in matched_model_keys:
|
| 304 |
+
if key_model in memo:
|
| 305 |
+
continue
|
| 306 |
+
if key_model in model_key_groups:
|
| 307 |
+
group = model_key_groups[key_model]
|
| 308 |
+
memo |= set(group)
|
| 309 |
+
shapes = [tuple(model_state_dict[k].shape) for k in group]
|
| 310 |
+
table.append(
|
| 311 |
+
(
|
| 312 |
+
_longest_common_prefix([k[len(common_prefix) :] for k in group]) + "*",
|
| 313 |
+
_group_str([original_keys[k] for k in group]),
|
| 314 |
+
" ".join([str(x).replace(" ", "") for x in shapes]),
|
| 315 |
+
)
|
| 316 |
+
)
|
| 317 |
+
else:
|
| 318 |
+
key_checkpoint = original_keys[key_model]
|
| 319 |
+
shape = str(tuple(model_state_dict[key_model].shape))
|
| 320 |
+
table.append((key_model[len(common_prefix) :], key_checkpoint, shape))
|
| 321 |
+
table_str = tabulate(
|
| 322 |
+
table, tablefmt="pipe", headers=["Names in Model", "Names in Checkpoint", "Shapes"]
|
| 323 |
+
)
|
| 324 |
+
logger.info(
|
| 325 |
+
"Following weights matched with "
|
| 326 |
+
+ (f"submodule {common_prefix[:-1]}" if common_prefix else "model")
|
| 327 |
+
+ ":\n"
|
| 328 |
+
+ table_str
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
unmatched_ckpt_keys = [k for k in ckpt_keys if k not in set(matched_keys.keys())]
|
| 332 |
+
for k in unmatched_ckpt_keys:
|
| 333 |
+
result_state_dict[k] = ckpt_state_dict[k]
|
| 334 |
+
return result_state_dict
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _group_keys_by_module(keys: List[str], original_names: Dict[str, str]):
|
| 338 |
+
"""
|
| 339 |
+
Params in the same submodule are grouped together.
|
| 340 |
+
|
| 341 |
+
Args:
|
| 342 |
+
keys: names of all parameters
|
| 343 |
+
original_names: mapping from parameter name to their name in the checkpoint
|
| 344 |
+
|
| 345 |
+
Returns:
|
| 346 |
+
dict[name -> all other names in the same group]
|
| 347 |
+
"""
|
| 348 |
+
|
| 349 |
+
def _submodule_name(key):
|
| 350 |
+
pos = key.rfind(".")
|
| 351 |
+
if pos < 0:
|
| 352 |
+
return None
|
| 353 |
+
prefix = key[: pos + 1]
|
| 354 |
+
return prefix
|
| 355 |
+
|
| 356 |
+
all_submodules = [_submodule_name(k) for k in keys]
|
| 357 |
+
all_submodules = [x for x in all_submodules if x]
|
| 358 |
+
all_submodules = sorted(all_submodules, key=len)
|
| 359 |
+
|
| 360 |
+
ret = {}
|
| 361 |
+
for prefix in all_submodules:
|
| 362 |
+
group = [k for k in keys if k.startswith(prefix)]
|
| 363 |
+
if len(group) <= 1:
|
| 364 |
+
continue
|
| 365 |
+
original_name_lcp = _longest_common_prefix_str([original_names[k] for k in group])
|
| 366 |
+
if len(original_name_lcp) == 0:
|
| 367 |
+
# don't group weights if original names don't share prefix
|
| 368 |
+
continue
|
| 369 |
+
|
| 370 |
+
for k in group:
|
| 371 |
+
if k in ret:
|
| 372 |
+
continue
|
| 373 |
+
ret[k] = group
|
| 374 |
+
return ret
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _longest_common_prefix(names: List[str]) -> str:
|
| 378 |
+
"""
|
| 379 |
+
["abc.zfg", "abc.zef"] -> "abc."
|
| 380 |
+
"""
|
| 381 |
+
names = [n.split(".") for n in names]
|
| 382 |
+
m1, m2 = min(names), max(names)
|
| 383 |
+
ret = [a for a, b in zip(m1, m2) if a == b]
|
| 384 |
+
ret = ".".join(ret) + "." if len(ret) else ""
|
| 385 |
+
return ret
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _longest_common_prefix_str(names: List[str]) -> str:
|
| 389 |
+
m1, m2 = min(names), max(names)
|
| 390 |
+
lcp = []
|
| 391 |
+
for a, b in zip(m1, m2):
|
| 392 |
+
if a == b:
|
| 393 |
+
lcp.append(a)
|
| 394 |
+
else:
|
| 395 |
+
break
|
| 396 |
+
lcp = "".join(lcp)
|
| 397 |
+
return lcp
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def _group_str(names: List[str]) -> str:
|
| 401 |
+
"""
|
| 402 |
+
Turn "common1", "common2", "common3" into "common{1,2,3}"
|
| 403 |
+
"""
|
| 404 |
+
lcp = _longest_common_prefix_str(names)
|
| 405 |
+
rest = [x[len(lcp) :] for x in names]
|
| 406 |
+
rest = "{" + ",".join(rest) + "}"
|
| 407 |
+
ret = lcp + rest
|
| 408 |
+
|
| 409 |
+
# add some simplification for BN specifically
|
| 410 |
+
ret = ret.replace("bn_{beta,running_mean,running_var,gamma}", "bn_*")
|
| 411 |
+
ret = ret.replace("bn_beta,bn_running_mean,bn_running_var,bn_gamma", "bn_*")
|
| 412 |
+
return ret
|
RAVE-main/annotator/oneformer/detectron2/checkpoint/catalog.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
from annotator.oneformer.detectron2.utils.file_io import PathHandler, PathManager
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ModelCatalog(object):
|
| 8 |
+
"""
|
| 9 |
+
Store mappings from names to third-party models.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
S3_C2_DETECTRON_PREFIX = "https://dl.fbaipublicfiles.com/detectron"
|
| 13 |
+
|
| 14 |
+
# MSRA models have STRIDE_IN_1X1=True. False otherwise.
|
| 15 |
+
# NOTE: all BN models here have fused BN into an affine layer.
|
| 16 |
+
# As a result, you should only load them to a model with "FrozenBN".
|
| 17 |
+
# Loading them to a model with regular BN or SyncBN is wrong.
|
| 18 |
+
# Even when loaded to FrozenBN, it is still different from affine by an epsilon,
|
| 19 |
+
# which should be negligible for training.
|
| 20 |
+
# NOTE: all models here uses PIXEL_STD=[1,1,1]
|
| 21 |
+
# NOTE: Most of the BN models here are no longer used. We use the
|
| 22 |
+
# re-converted pre-trained models under detectron2 model zoo instead.
|
| 23 |
+
C2_IMAGENET_MODELS = {
|
| 24 |
+
"MSRA/R-50": "ImageNetPretrained/MSRA/R-50.pkl",
|
| 25 |
+
"MSRA/R-101": "ImageNetPretrained/MSRA/R-101.pkl",
|
| 26 |
+
"FAIR/R-50-GN": "ImageNetPretrained/47261647/R-50-GN.pkl",
|
| 27 |
+
"FAIR/R-101-GN": "ImageNetPretrained/47592356/R-101-GN.pkl",
|
| 28 |
+
"FAIR/X-101-32x8d": "ImageNetPretrained/20171220/X-101-32x8d.pkl",
|
| 29 |
+
"FAIR/X-101-64x4d": "ImageNetPretrained/FBResNeXt/X-101-64x4d.pkl",
|
| 30 |
+
"FAIR/X-152-32x8d-IN5k": "ImageNetPretrained/25093814/X-152-32x8d-IN5k.pkl",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
C2_DETECTRON_PATH_FORMAT = (
|
| 34 |
+
"{prefix}/{url}/output/train/{dataset}/{type}/model_final.pkl" # noqa B950
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
C2_DATASET_COCO = "coco_2014_train%3Acoco_2014_valminusminival"
|
| 38 |
+
C2_DATASET_COCO_KEYPOINTS = "keypoints_coco_2014_train%3Akeypoints_coco_2014_valminusminival"
|
| 39 |
+
|
| 40 |
+
# format: {model_name} -> part of the url
|
| 41 |
+
C2_DETECTRON_MODELS = {
|
| 42 |
+
"35857197/e2e_faster_rcnn_R-50-C4_1x": "35857197/12_2017_baselines/e2e_faster_rcnn_R-50-C4_1x.yaml.01_33_49.iAX0mXvW", # noqa B950
|
| 43 |
+
"35857345/e2e_faster_rcnn_R-50-FPN_1x": "35857345/12_2017_baselines/e2e_faster_rcnn_R-50-FPN_1x.yaml.01_36_30.cUF7QR7I", # noqa B950
|
| 44 |
+
"35857890/e2e_faster_rcnn_R-101-FPN_1x": "35857890/12_2017_baselines/e2e_faster_rcnn_R-101-FPN_1x.yaml.01_38_50.sNxI7sX7", # noqa B950
|
| 45 |
+
"36761737/e2e_faster_rcnn_X-101-32x8d-FPN_1x": "36761737/12_2017_baselines/e2e_faster_rcnn_X-101-32x8d-FPN_1x.yaml.06_31_39.5MIHi1fZ", # noqa B950
|
| 46 |
+
"35858791/e2e_mask_rcnn_R-50-C4_1x": "35858791/12_2017_baselines/e2e_mask_rcnn_R-50-C4_1x.yaml.01_45_57.ZgkA7hPB", # noqa B950
|
| 47 |
+
"35858933/e2e_mask_rcnn_R-50-FPN_1x": "35858933/12_2017_baselines/e2e_mask_rcnn_R-50-FPN_1x.yaml.01_48_14.DzEQe4wC", # noqa B950
|
| 48 |
+
"35861795/e2e_mask_rcnn_R-101-FPN_1x": "35861795/12_2017_baselines/e2e_mask_rcnn_R-101-FPN_1x.yaml.02_31_37.KqyEK4tT", # noqa B950
|
| 49 |
+
"36761843/e2e_mask_rcnn_X-101-32x8d-FPN_1x": "36761843/12_2017_baselines/e2e_mask_rcnn_X-101-32x8d-FPN_1x.yaml.06_35_59.RZotkLKI", # noqa B950
|
| 50 |
+
"48616381/e2e_mask_rcnn_R-50-FPN_2x_gn": "GN/48616381/04_2018_gn_baselines/e2e_mask_rcnn_R-50-FPN_2x_gn_0416.13_23_38.bTlTI97Q", # noqa B950
|
| 51 |
+
"37697547/e2e_keypoint_rcnn_R-50-FPN_1x": "37697547/12_2017_baselines/e2e_keypoint_rcnn_R-50-FPN_1x.yaml.08_42_54.kdzV35ao", # noqa B950
|
| 52 |
+
"35998355/rpn_R-50-C4_1x": "35998355/12_2017_baselines/rpn_R-50-C4_1x.yaml.08_00_43.njH5oD9L", # noqa B950
|
| 53 |
+
"35998814/rpn_R-50-FPN_1x": "35998814/12_2017_baselines/rpn_R-50-FPN_1x.yaml.08_06_03.Axg0r179", # noqa B950
|
| 54 |
+
"36225147/fast_R-50-FPN_1x": "36225147/12_2017_baselines/fast_rcnn_R-50-FPN_1x.yaml.08_39_09.L3obSdQ2", # noqa B950
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
@staticmethod
|
| 58 |
+
def get(name):
|
| 59 |
+
if name.startswith("Caffe2Detectron/COCO"):
|
| 60 |
+
return ModelCatalog._get_c2_detectron_baseline(name)
|
| 61 |
+
if name.startswith("ImageNetPretrained/"):
|
| 62 |
+
return ModelCatalog._get_c2_imagenet_pretrained(name)
|
| 63 |
+
raise RuntimeError("model not present in the catalog: {}".format(name))
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def _get_c2_imagenet_pretrained(name):
|
| 67 |
+
prefix = ModelCatalog.S3_C2_DETECTRON_PREFIX
|
| 68 |
+
name = name[len("ImageNetPretrained/") :]
|
| 69 |
+
name = ModelCatalog.C2_IMAGENET_MODELS[name]
|
| 70 |
+
url = "/".join([prefix, name])
|
| 71 |
+
return url
|
| 72 |
+
|
| 73 |
+
@staticmethod
|
| 74 |
+
def _get_c2_detectron_baseline(name):
|
| 75 |
+
name = name[len("Caffe2Detectron/COCO/") :]
|
| 76 |
+
url = ModelCatalog.C2_DETECTRON_MODELS[name]
|
| 77 |
+
if "keypoint_rcnn" in name:
|
| 78 |
+
dataset = ModelCatalog.C2_DATASET_COCO_KEYPOINTS
|
| 79 |
+
else:
|
| 80 |
+
dataset = ModelCatalog.C2_DATASET_COCO
|
| 81 |
+
|
| 82 |
+
if "35998355/rpn_R-50-C4_1x" in name:
|
| 83 |
+
# this one model is somehow different from others ..
|
| 84 |
+
type = "rpn"
|
| 85 |
+
else:
|
| 86 |
+
type = "generalized_rcnn"
|
| 87 |
+
|
| 88 |
+
# Detectron C2 models are stored in the structure defined in `C2_DETECTRON_PATH_FORMAT`.
|
| 89 |
+
url = ModelCatalog.C2_DETECTRON_PATH_FORMAT.format(
|
| 90 |
+
prefix=ModelCatalog.S3_C2_DETECTRON_PREFIX, url=url, type=type, dataset=dataset
|
| 91 |
+
)
|
| 92 |
+
return url
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ModelCatalogHandler(PathHandler):
|
| 96 |
+
"""
|
| 97 |
+
Resolve URL like catalog://.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
PREFIX = "catalog://"
|
| 101 |
+
|
| 102 |
+
def _get_supported_prefixes(self):
|
| 103 |
+
return [self.PREFIX]
|
| 104 |
+
|
| 105 |
+
def _get_local_path(self, path, **kwargs):
|
| 106 |
+
logger = logging.getLogger(__name__)
|
| 107 |
+
catalog_path = ModelCatalog.get(path[len(self.PREFIX) :])
|
| 108 |
+
logger.info("Catalog entry {} points to {}".format(path, catalog_path))
|
| 109 |
+
return PathManager.get_local_path(catalog_path, **kwargs)
|
| 110 |
+
|
| 111 |
+
def _open(self, path, mode="r", **kwargs):
|
| 112 |
+
return PathManager.open(self._get_local_path(path), mode, **kwargs)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
PathManager.register_handler(ModelCatalogHandler())
|
RAVE-main/annotator/oneformer/detectron2/checkpoint/detection_checkpoint.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import pickle
|
| 5 |
+
from urllib.parse import parse_qs, urlparse
|
| 6 |
+
import torch
|
| 7 |
+
from fvcore.common.checkpoint import Checkpointer
|
| 8 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 9 |
+
|
| 10 |
+
import annotator.oneformer.detectron2.utils.comm as comm
|
| 11 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 12 |
+
|
| 13 |
+
from .c2_model_loading import align_and_update_state_dicts
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class DetectionCheckpointer(Checkpointer):
|
| 17 |
+
"""
|
| 18 |
+
Same as :class:`Checkpointer`, but is able to:
|
| 19 |
+
1. handle models in detectron & detectron2 model zoo, and apply conversions for legacy models.
|
| 20 |
+
2. correctly load checkpoints that are only available on the master worker
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, model, save_dir="", *, save_to_disk=None, **checkpointables):
|
| 24 |
+
is_main_process = comm.is_main_process()
|
| 25 |
+
super().__init__(
|
| 26 |
+
model,
|
| 27 |
+
save_dir,
|
| 28 |
+
save_to_disk=is_main_process if save_to_disk is None else save_to_disk,
|
| 29 |
+
**checkpointables,
|
| 30 |
+
)
|
| 31 |
+
self.path_manager = PathManager
|
| 32 |
+
self._parsed_url_during_load = None
|
| 33 |
+
|
| 34 |
+
def load(self, path, *args, **kwargs):
|
| 35 |
+
assert self._parsed_url_during_load is None
|
| 36 |
+
need_sync = False
|
| 37 |
+
logger = logging.getLogger(__name__)
|
| 38 |
+
logger.info("[DetectionCheckpointer] Loading from {} ...".format(path))
|
| 39 |
+
|
| 40 |
+
if path and isinstance(self.model, DistributedDataParallel):
|
| 41 |
+
path = self.path_manager.get_local_path(path)
|
| 42 |
+
has_file = os.path.isfile(path)
|
| 43 |
+
all_has_file = comm.all_gather(has_file)
|
| 44 |
+
if not all_has_file[0]:
|
| 45 |
+
raise OSError(f"File {path} not found on main worker.")
|
| 46 |
+
if not all(all_has_file):
|
| 47 |
+
logger.warning(
|
| 48 |
+
f"Not all workers can read checkpoint {path}. "
|
| 49 |
+
"Training may fail to fully resume."
|
| 50 |
+
)
|
| 51 |
+
# TODO: broadcast the checkpoint file contents from main
|
| 52 |
+
# worker, and load from it instead.
|
| 53 |
+
need_sync = True
|
| 54 |
+
if not has_file:
|
| 55 |
+
path = None # don't load if not readable
|
| 56 |
+
|
| 57 |
+
if path:
|
| 58 |
+
parsed_url = urlparse(path)
|
| 59 |
+
self._parsed_url_during_load = parsed_url
|
| 60 |
+
path = parsed_url._replace(query="").geturl() # remove query from filename
|
| 61 |
+
path = self.path_manager.get_local_path(path)
|
| 62 |
+
|
| 63 |
+
self.logger.setLevel('CRITICAL')
|
| 64 |
+
ret = super().load(path, *args, **kwargs)
|
| 65 |
+
|
| 66 |
+
if need_sync:
|
| 67 |
+
logger.info("Broadcasting model states from main worker ...")
|
| 68 |
+
self.model._sync_params_and_buffers()
|
| 69 |
+
self._parsed_url_during_load = None # reset to None
|
| 70 |
+
return ret
|
| 71 |
+
|
| 72 |
+
def _load_file(self, filename):
|
| 73 |
+
if filename.endswith(".pkl"):
|
| 74 |
+
with PathManager.open(filename, "rb") as f:
|
| 75 |
+
data = pickle.load(f, encoding="latin1")
|
| 76 |
+
if "model" in data and "__author__" in data:
|
| 77 |
+
# file is in Detectron2 model zoo format
|
| 78 |
+
self.logger.info("Reading a file from '{}'".format(data["__author__"]))
|
| 79 |
+
return data
|
| 80 |
+
else:
|
| 81 |
+
# assume file is from Caffe2 / Detectron1 model zoo
|
| 82 |
+
if "blobs" in data:
|
| 83 |
+
# Detection models have "blobs", but ImageNet models don't
|
| 84 |
+
data = data["blobs"]
|
| 85 |
+
data = {k: v for k, v in data.items() if not k.endswith("_momentum")}
|
| 86 |
+
return {"model": data, "__author__": "Caffe2", "matching_heuristics": True}
|
| 87 |
+
elif filename.endswith(".pyth"):
|
| 88 |
+
# assume file is from pycls; no one else seems to use the ".pyth" extension
|
| 89 |
+
with PathManager.open(filename, "rb") as f:
|
| 90 |
+
data = torch.load(f)
|
| 91 |
+
assert (
|
| 92 |
+
"model_state" in data
|
| 93 |
+
), f"Cannot load .pyth file {filename}; pycls checkpoints must contain 'model_state'."
|
| 94 |
+
model_state = {
|
| 95 |
+
k: v
|
| 96 |
+
for k, v in data["model_state"].items()
|
| 97 |
+
if not k.endswith("num_batches_tracked")
|
| 98 |
+
}
|
| 99 |
+
return {"model": model_state, "__author__": "pycls", "matching_heuristics": True}
|
| 100 |
+
|
| 101 |
+
loaded = self._torch_load(filename)
|
| 102 |
+
if "model" not in loaded:
|
| 103 |
+
loaded = {"model": loaded}
|
| 104 |
+
assert self._parsed_url_during_load is not None, "`_load_file` must be called inside `load`"
|
| 105 |
+
parsed_url = self._parsed_url_during_load
|
| 106 |
+
queries = parse_qs(parsed_url.query)
|
| 107 |
+
if queries.pop("matching_heuristics", "False") == ["True"]:
|
| 108 |
+
loaded["matching_heuristics"] = True
|
| 109 |
+
if len(queries) > 0:
|
| 110 |
+
raise ValueError(
|
| 111 |
+
f"Unsupported query remaining: f{queries}, orginal filename: {parsed_url.geturl()}"
|
| 112 |
+
)
|
| 113 |
+
return loaded
|
| 114 |
+
|
| 115 |
+
def _torch_load(self, f):
|
| 116 |
+
return super()._load_file(f)
|
| 117 |
+
|
| 118 |
+
def _load_model(self, checkpoint):
|
| 119 |
+
if checkpoint.get("matching_heuristics", False):
|
| 120 |
+
self._convert_ndarray_to_tensor(checkpoint["model"])
|
| 121 |
+
# convert weights by name-matching heuristics
|
| 122 |
+
checkpoint["model"] = align_and_update_state_dicts(
|
| 123 |
+
self.model.state_dict(),
|
| 124 |
+
checkpoint["model"],
|
| 125 |
+
c2_conversion=checkpoint.get("__author__", None) == "Caffe2",
|
| 126 |
+
)
|
| 127 |
+
# for non-caffe2 models, use standard ways to load it
|
| 128 |
+
incompatible = super()._load_model(checkpoint)
|
| 129 |
+
|
| 130 |
+
model_buffers = dict(self.model.named_buffers(recurse=False))
|
| 131 |
+
for k in ["pixel_mean", "pixel_std"]:
|
| 132 |
+
# Ignore missing key message about pixel_mean/std.
|
| 133 |
+
# Though they may be missing in old checkpoints, they will be correctly
|
| 134 |
+
# initialized from config anyway.
|
| 135 |
+
if k in model_buffers:
|
| 136 |
+
try:
|
| 137 |
+
incompatible.missing_keys.remove(k)
|
| 138 |
+
except ValueError:
|
| 139 |
+
pass
|
| 140 |
+
for k in incompatible.unexpected_keys[:]:
|
| 141 |
+
# Ignore unexpected keys about cell anchors. They exist in old checkpoints
|
| 142 |
+
# but now they are non-persistent buffers and will not be in new checkpoints.
|
| 143 |
+
if "anchor_generator.cell_anchors" in k:
|
| 144 |
+
incompatible.unexpected_keys.remove(k)
|
| 145 |
+
return incompatible
|
RAVE-main/annotator/oneformer/detectron2/config/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
from .compat import downgrade_config, upgrade_config
|
| 3 |
+
from .config import CfgNode, get_cfg, global_cfg, set_global_cfg, configurable
|
| 4 |
+
from .instantiate import instantiate
|
| 5 |
+
from .lazy import LazyCall, LazyConfig
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"CfgNode",
|
| 9 |
+
"get_cfg",
|
| 10 |
+
"global_cfg",
|
| 11 |
+
"set_global_cfg",
|
| 12 |
+
"downgrade_config",
|
| 13 |
+
"upgrade_config",
|
| 14 |
+
"configurable",
|
| 15 |
+
"instantiate",
|
| 16 |
+
"LazyCall",
|
| 17 |
+
"LazyConfig",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
from annotator.oneformer.detectron2.utils.env import fixup_module_metadata
|
| 22 |
+
|
| 23 |
+
fixup_module_metadata(__name__, globals(), __all__)
|
| 24 |
+
del fixup_module_metadata
|
RAVE-main/annotator/oneformer/detectron2/config/compat.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
|
| 4 |
+
|
| 5 |
+
Instructions to bump version:
|
| 6 |
+
+ It's not needed to bump version if new keys are added.
|
| 7 |
+
It's only needed when backward-incompatible changes happen
|
| 8 |
+
(i.e., some existing keys disappear, or the meaning of a key changes)
|
| 9 |
+
+ To bump version, do the following:
|
| 10 |
+
1. Increment _C.VERSION in defaults.py
|
| 11 |
+
2. Add a converter in this file.
|
| 12 |
+
|
| 13 |
+
Each ConverterVX has a function "upgrade" which in-place upgrades config from X-1 to X,
|
| 14 |
+
and a function "downgrade" which in-place downgrades config from X to X-1
|
| 15 |
+
|
| 16 |
+
In each function, VERSION is left unchanged.
|
| 17 |
+
|
| 18 |
+
Each converter assumes that its input has the relevant keys
|
| 19 |
+
(i.e., the input is not a partial config).
|
| 20 |
+
3. Run the tests (test_config.py) to make sure the upgrade & downgrade
|
| 21 |
+
functions are consistent.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import logging
|
| 25 |
+
from typing import List, Optional, Tuple
|
| 26 |
+
|
| 27 |
+
from .config import CfgNode as CN
|
| 28 |
+
from .defaults import _C
|
| 29 |
+
|
| 30 |
+
__all__ = ["upgrade_config", "downgrade_config"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def upgrade_config(cfg: CN, to_version: Optional[int] = None) -> CN:
|
| 34 |
+
"""
|
| 35 |
+
Upgrade a config from its current version to a newer version.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
cfg (CfgNode):
|
| 39 |
+
to_version (int): defaults to the latest version.
|
| 40 |
+
"""
|
| 41 |
+
cfg = cfg.clone()
|
| 42 |
+
if to_version is None:
|
| 43 |
+
to_version = _C.VERSION
|
| 44 |
+
|
| 45 |
+
assert cfg.VERSION <= to_version, "Cannot upgrade from v{} to v{}!".format(
|
| 46 |
+
cfg.VERSION, to_version
|
| 47 |
+
)
|
| 48 |
+
for k in range(cfg.VERSION, to_version):
|
| 49 |
+
converter = globals()["ConverterV" + str(k + 1)]
|
| 50 |
+
converter.upgrade(cfg)
|
| 51 |
+
cfg.VERSION = k + 1
|
| 52 |
+
return cfg
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def downgrade_config(cfg: CN, to_version: int) -> CN:
|
| 56 |
+
"""
|
| 57 |
+
Downgrade a config from its current version to an older version.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
cfg (CfgNode):
|
| 61 |
+
to_version (int):
|
| 62 |
+
|
| 63 |
+
Note:
|
| 64 |
+
A general downgrade of arbitrary configs is not always possible due to the
|
| 65 |
+
different functionalities in different versions.
|
| 66 |
+
The purpose of downgrade is only to recover the defaults in old versions,
|
| 67 |
+
allowing it to load an old partial yaml config.
|
| 68 |
+
Therefore, the implementation only needs to fill in the default values
|
| 69 |
+
in the old version when a general downgrade is not possible.
|
| 70 |
+
"""
|
| 71 |
+
cfg = cfg.clone()
|
| 72 |
+
assert cfg.VERSION >= to_version, "Cannot downgrade from v{} to v{}!".format(
|
| 73 |
+
cfg.VERSION, to_version
|
| 74 |
+
)
|
| 75 |
+
for k in range(cfg.VERSION, to_version, -1):
|
| 76 |
+
converter = globals()["ConverterV" + str(k)]
|
| 77 |
+
converter.downgrade(cfg)
|
| 78 |
+
cfg.VERSION = k - 1
|
| 79 |
+
return cfg
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def guess_version(cfg: CN, filename: str) -> int:
|
| 83 |
+
"""
|
| 84 |
+
Guess the version of a partial config where the VERSION field is not specified.
|
| 85 |
+
Returns the version, or the latest if cannot make a guess.
|
| 86 |
+
|
| 87 |
+
This makes it easier for users to migrate.
|
| 88 |
+
"""
|
| 89 |
+
logger = logging.getLogger(__name__)
|
| 90 |
+
|
| 91 |
+
def _has(name: str) -> bool:
|
| 92 |
+
cur = cfg
|
| 93 |
+
for n in name.split("."):
|
| 94 |
+
if n not in cur:
|
| 95 |
+
return False
|
| 96 |
+
cur = cur[n]
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
# Most users' partial configs have "MODEL.WEIGHT", so guess on it
|
| 100 |
+
ret = None
|
| 101 |
+
if _has("MODEL.WEIGHT") or _has("TEST.AUG_ON"):
|
| 102 |
+
ret = 1
|
| 103 |
+
|
| 104 |
+
if ret is not None:
|
| 105 |
+
logger.warning("Config '{}' has no VERSION. Assuming it to be v{}.".format(filename, ret))
|
| 106 |
+
else:
|
| 107 |
+
ret = _C.VERSION
|
| 108 |
+
logger.warning(
|
| 109 |
+
"Config '{}' has no VERSION. Assuming it to be compatible with latest v{}.".format(
|
| 110 |
+
filename, ret
|
| 111 |
+
)
|
| 112 |
+
)
|
| 113 |
+
return ret
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _rename(cfg: CN, old: str, new: str) -> None:
|
| 117 |
+
old_keys = old.split(".")
|
| 118 |
+
new_keys = new.split(".")
|
| 119 |
+
|
| 120 |
+
def _set(key_seq: List[str], val: str) -> None:
|
| 121 |
+
cur = cfg
|
| 122 |
+
for k in key_seq[:-1]:
|
| 123 |
+
if k not in cur:
|
| 124 |
+
cur[k] = CN()
|
| 125 |
+
cur = cur[k]
|
| 126 |
+
cur[key_seq[-1]] = val
|
| 127 |
+
|
| 128 |
+
def _get(key_seq: List[str]) -> CN:
|
| 129 |
+
cur = cfg
|
| 130 |
+
for k in key_seq:
|
| 131 |
+
cur = cur[k]
|
| 132 |
+
return cur
|
| 133 |
+
|
| 134 |
+
def _del(key_seq: List[str]) -> None:
|
| 135 |
+
cur = cfg
|
| 136 |
+
for k in key_seq[:-1]:
|
| 137 |
+
cur = cur[k]
|
| 138 |
+
del cur[key_seq[-1]]
|
| 139 |
+
if len(cur) == 0 and len(key_seq) > 1:
|
| 140 |
+
_del(key_seq[:-1])
|
| 141 |
+
|
| 142 |
+
_set(new_keys, _get(old_keys))
|
| 143 |
+
_del(old_keys)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class _RenameConverter:
|
| 147 |
+
"""
|
| 148 |
+
A converter that handles simple rename.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
RENAME: List[Tuple[str, str]] = [] # list of tuples of (old name, new name)
|
| 152 |
+
|
| 153 |
+
@classmethod
|
| 154 |
+
def upgrade(cls, cfg: CN) -> None:
|
| 155 |
+
for old, new in cls.RENAME:
|
| 156 |
+
_rename(cfg, old, new)
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def downgrade(cls, cfg: CN) -> None:
|
| 160 |
+
for old, new in cls.RENAME[::-1]:
|
| 161 |
+
_rename(cfg, new, old)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class ConverterV1(_RenameConverter):
|
| 165 |
+
RENAME = [("MODEL.RPN_HEAD.NAME", "MODEL.RPN.HEAD_NAME")]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class ConverterV2(_RenameConverter):
|
| 169 |
+
"""
|
| 170 |
+
A large bulk of rename, before public release.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
RENAME = [
|
| 174 |
+
("MODEL.WEIGHT", "MODEL.WEIGHTS"),
|
| 175 |
+
("MODEL.PANOPTIC_FPN.SEMANTIC_LOSS_SCALE", "MODEL.SEM_SEG_HEAD.LOSS_WEIGHT"),
|
| 176 |
+
("MODEL.PANOPTIC_FPN.RPN_LOSS_SCALE", "MODEL.RPN.LOSS_WEIGHT"),
|
| 177 |
+
("MODEL.PANOPTIC_FPN.INSTANCE_LOSS_SCALE", "MODEL.PANOPTIC_FPN.INSTANCE_LOSS_WEIGHT"),
|
| 178 |
+
("MODEL.PANOPTIC_FPN.COMBINE_ON", "MODEL.PANOPTIC_FPN.COMBINE.ENABLED"),
|
| 179 |
+
(
|
| 180 |
+
"MODEL.PANOPTIC_FPN.COMBINE_OVERLAP_THRESHOLD",
|
| 181 |
+
"MODEL.PANOPTIC_FPN.COMBINE.OVERLAP_THRESH",
|
| 182 |
+
),
|
| 183 |
+
(
|
| 184 |
+
"MODEL.PANOPTIC_FPN.COMBINE_STUFF_AREA_LIMIT",
|
| 185 |
+
"MODEL.PANOPTIC_FPN.COMBINE.STUFF_AREA_LIMIT",
|
| 186 |
+
),
|
| 187 |
+
(
|
| 188 |
+
"MODEL.PANOPTIC_FPN.COMBINE_INSTANCES_CONFIDENCE_THRESHOLD",
|
| 189 |
+
"MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH",
|
| 190 |
+
),
|
| 191 |
+
("MODEL.ROI_HEADS.SCORE_THRESH", "MODEL.ROI_HEADS.SCORE_THRESH_TEST"),
|
| 192 |
+
("MODEL.ROI_HEADS.NMS", "MODEL.ROI_HEADS.NMS_THRESH_TEST"),
|
| 193 |
+
("MODEL.RETINANET.INFERENCE_SCORE_THRESHOLD", "MODEL.RETINANET.SCORE_THRESH_TEST"),
|
| 194 |
+
("MODEL.RETINANET.INFERENCE_TOPK_CANDIDATES", "MODEL.RETINANET.TOPK_CANDIDATES_TEST"),
|
| 195 |
+
("MODEL.RETINANET.INFERENCE_NMS_THRESHOLD", "MODEL.RETINANET.NMS_THRESH_TEST"),
|
| 196 |
+
("TEST.DETECTIONS_PER_IMG", "TEST.DETECTIONS_PER_IMAGE"),
|
| 197 |
+
("TEST.AUG_ON", "TEST.AUG.ENABLED"),
|
| 198 |
+
("TEST.AUG_MIN_SIZES", "TEST.AUG.MIN_SIZES"),
|
| 199 |
+
("TEST.AUG_MAX_SIZE", "TEST.AUG.MAX_SIZE"),
|
| 200 |
+
("TEST.AUG_FLIP", "TEST.AUG.FLIP"),
|
| 201 |
+
]
|
| 202 |
+
|
| 203 |
+
@classmethod
|
| 204 |
+
def upgrade(cls, cfg: CN) -> None:
|
| 205 |
+
super().upgrade(cfg)
|
| 206 |
+
|
| 207 |
+
if cfg.MODEL.META_ARCHITECTURE == "RetinaNet":
|
| 208 |
+
_rename(
|
| 209 |
+
cfg, "MODEL.RETINANET.ANCHOR_ASPECT_RATIOS", "MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS"
|
| 210 |
+
)
|
| 211 |
+
_rename(cfg, "MODEL.RETINANET.ANCHOR_SIZES", "MODEL.ANCHOR_GENERATOR.SIZES")
|
| 212 |
+
del cfg["MODEL"]["RPN"]["ANCHOR_SIZES"]
|
| 213 |
+
del cfg["MODEL"]["RPN"]["ANCHOR_ASPECT_RATIOS"]
|
| 214 |
+
else:
|
| 215 |
+
_rename(cfg, "MODEL.RPN.ANCHOR_ASPECT_RATIOS", "MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS")
|
| 216 |
+
_rename(cfg, "MODEL.RPN.ANCHOR_SIZES", "MODEL.ANCHOR_GENERATOR.SIZES")
|
| 217 |
+
del cfg["MODEL"]["RETINANET"]["ANCHOR_SIZES"]
|
| 218 |
+
del cfg["MODEL"]["RETINANET"]["ANCHOR_ASPECT_RATIOS"]
|
| 219 |
+
del cfg["MODEL"]["RETINANET"]["ANCHOR_STRIDES"]
|
| 220 |
+
|
| 221 |
+
@classmethod
|
| 222 |
+
def downgrade(cls, cfg: CN) -> None:
|
| 223 |
+
super().downgrade(cfg)
|
| 224 |
+
|
| 225 |
+
_rename(cfg, "MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS", "MODEL.RPN.ANCHOR_ASPECT_RATIOS")
|
| 226 |
+
_rename(cfg, "MODEL.ANCHOR_GENERATOR.SIZES", "MODEL.RPN.ANCHOR_SIZES")
|
| 227 |
+
cfg.MODEL.RETINANET.ANCHOR_ASPECT_RATIOS = cfg.MODEL.RPN.ANCHOR_ASPECT_RATIOS
|
| 228 |
+
cfg.MODEL.RETINANET.ANCHOR_SIZES = cfg.MODEL.RPN.ANCHOR_SIZES
|
| 229 |
+
cfg.MODEL.RETINANET.ANCHOR_STRIDES = [] # this is not used anywhere in any version
|
RAVE-main/annotator/oneformer/detectron2/config/config.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
|
| 4 |
+
import functools
|
| 5 |
+
import inspect
|
| 6 |
+
import logging
|
| 7 |
+
from fvcore.common.config import CfgNode as _CfgNode
|
| 8 |
+
|
| 9 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CfgNode(_CfgNode):
|
| 13 |
+
"""
|
| 14 |
+
The same as `fvcore.common.config.CfgNode`, but different in:
|
| 15 |
+
|
| 16 |
+
1. Use unsafe yaml loading by default.
|
| 17 |
+
Note that this may lead to arbitrary code execution: you must not
|
| 18 |
+
load a config file from untrusted sources before manually inspecting
|
| 19 |
+
the content of the file.
|
| 20 |
+
2. Support config versioning.
|
| 21 |
+
When attempting to merge an old config, it will convert the old config automatically.
|
| 22 |
+
|
| 23 |
+
.. automethod:: clone
|
| 24 |
+
.. automethod:: freeze
|
| 25 |
+
.. automethod:: defrost
|
| 26 |
+
.. automethod:: is_frozen
|
| 27 |
+
.. automethod:: load_yaml_with_base
|
| 28 |
+
.. automethod:: merge_from_list
|
| 29 |
+
.. automethod:: merge_from_other_cfg
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
def _open_cfg(cls, filename):
|
| 34 |
+
return PathManager.open(filename, "r")
|
| 35 |
+
|
| 36 |
+
# Note that the default value of allow_unsafe is changed to True
|
| 37 |
+
def merge_from_file(self, cfg_filename: str, allow_unsafe: bool = True) -> None:
|
| 38 |
+
"""
|
| 39 |
+
Load content from the given config file and merge it into self.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
cfg_filename: config filename
|
| 43 |
+
allow_unsafe: allow unsafe yaml syntax
|
| 44 |
+
"""
|
| 45 |
+
assert PathManager.isfile(cfg_filename), f"Config file '{cfg_filename}' does not exist!"
|
| 46 |
+
loaded_cfg = self.load_yaml_with_base(cfg_filename, allow_unsafe=allow_unsafe)
|
| 47 |
+
loaded_cfg = type(self)(loaded_cfg)
|
| 48 |
+
|
| 49 |
+
# defaults.py needs to import CfgNode
|
| 50 |
+
from .defaults import _C
|
| 51 |
+
|
| 52 |
+
latest_ver = _C.VERSION
|
| 53 |
+
assert (
|
| 54 |
+
latest_ver == self.VERSION
|
| 55 |
+
), "CfgNode.merge_from_file is only allowed on a config object of latest version!"
|
| 56 |
+
|
| 57 |
+
logger = logging.getLogger(__name__)
|
| 58 |
+
|
| 59 |
+
loaded_ver = loaded_cfg.get("VERSION", None)
|
| 60 |
+
if loaded_ver is None:
|
| 61 |
+
from .compat import guess_version
|
| 62 |
+
|
| 63 |
+
loaded_ver = guess_version(loaded_cfg, cfg_filename)
|
| 64 |
+
assert loaded_ver <= self.VERSION, "Cannot merge a v{} config into a v{} config.".format(
|
| 65 |
+
loaded_ver, self.VERSION
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
if loaded_ver == self.VERSION:
|
| 69 |
+
self.merge_from_other_cfg(loaded_cfg)
|
| 70 |
+
else:
|
| 71 |
+
# compat.py needs to import CfgNode
|
| 72 |
+
from .compat import upgrade_config, downgrade_config
|
| 73 |
+
|
| 74 |
+
logger.warning(
|
| 75 |
+
"Loading an old v{} config file '{}' by automatically upgrading to v{}. "
|
| 76 |
+
"See docs/CHANGELOG.md for instructions to update your files.".format(
|
| 77 |
+
loaded_ver, cfg_filename, self.VERSION
|
| 78 |
+
)
|
| 79 |
+
)
|
| 80 |
+
# To convert, first obtain a full config at an old version
|
| 81 |
+
old_self = downgrade_config(self, to_version=loaded_ver)
|
| 82 |
+
old_self.merge_from_other_cfg(loaded_cfg)
|
| 83 |
+
new_config = upgrade_config(old_self)
|
| 84 |
+
self.clear()
|
| 85 |
+
self.update(new_config)
|
| 86 |
+
|
| 87 |
+
def dump(self, *args, **kwargs):
|
| 88 |
+
"""
|
| 89 |
+
Returns:
|
| 90 |
+
str: a yaml string representation of the config
|
| 91 |
+
"""
|
| 92 |
+
# to make it show up in docs
|
| 93 |
+
return super().dump(*args, **kwargs)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
global_cfg = CfgNode()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_cfg() -> CfgNode:
|
| 100 |
+
"""
|
| 101 |
+
Get a copy of the default config.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
a detectron2 CfgNode instance.
|
| 105 |
+
"""
|
| 106 |
+
from .defaults import _C
|
| 107 |
+
|
| 108 |
+
return _C.clone()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def set_global_cfg(cfg: CfgNode) -> None:
|
| 112 |
+
"""
|
| 113 |
+
Let the global config point to the given cfg.
|
| 114 |
+
|
| 115 |
+
Assume that the given "cfg" has the key "KEY", after calling
|
| 116 |
+
`set_global_cfg(cfg)`, the key can be accessed by:
|
| 117 |
+
::
|
| 118 |
+
from annotator.oneformer.detectron2.config import global_cfg
|
| 119 |
+
print(global_cfg.KEY)
|
| 120 |
+
|
| 121 |
+
By using a hacky global config, you can access these configs anywhere,
|
| 122 |
+
without having to pass the config object or the values deep into the code.
|
| 123 |
+
This is a hacky feature introduced for quick prototyping / research exploration.
|
| 124 |
+
"""
|
| 125 |
+
global global_cfg
|
| 126 |
+
global_cfg.clear()
|
| 127 |
+
global_cfg.update(cfg)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def configurable(init_func=None, *, from_config=None):
|
| 131 |
+
"""
|
| 132 |
+
Decorate a function or a class's __init__ method so that it can be called
|
| 133 |
+
with a :class:`CfgNode` object using a :func:`from_config` function that translates
|
| 134 |
+
:class:`CfgNode` to arguments.
|
| 135 |
+
|
| 136 |
+
Examples:
|
| 137 |
+
::
|
| 138 |
+
# Usage 1: Decorator on __init__:
|
| 139 |
+
class A:
|
| 140 |
+
@configurable
|
| 141 |
+
def __init__(self, a, b=2, c=3):
|
| 142 |
+
pass
|
| 143 |
+
|
| 144 |
+
@classmethod
|
| 145 |
+
def from_config(cls, cfg): # 'cfg' must be the first argument
|
| 146 |
+
# Returns kwargs to be passed to __init__
|
| 147 |
+
return {"a": cfg.A, "b": cfg.B}
|
| 148 |
+
|
| 149 |
+
a1 = A(a=1, b=2) # regular construction
|
| 150 |
+
a2 = A(cfg) # construct with a cfg
|
| 151 |
+
a3 = A(cfg, b=3, c=4) # construct with extra overwrite
|
| 152 |
+
|
| 153 |
+
# Usage 2: Decorator on any function. Needs an extra from_config argument:
|
| 154 |
+
@configurable(from_config=lambda cfg: {"a: cfg.A, "b": cfg.B})
|
| 155 |
+
def a_func(a, b=2, c=3):
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
a1 = a_func(a=1, b=2) # regular call
|
| 159 |
+
a2 = a_func(cfg) # call with a cfg
|
| 160 |
+
a3 = a_func(cfg, b=3, c=4) # call with extra overwrite
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
init_func (callable): a class's ``__init__`` method in usage 1. The
|
| 164 |
+
class must have a ``from_config`` classmethod which takes `cfg` as
|
| 165 |
+
the first argument.
|
| 166 |
+
from_config (callable): the from_config function in usage 2. It must take `cfg`
|
| 167 |
+
as its first argument.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
if init_func is not None:
|
| 171 |
+
assert (
|
| 172 |
+
inspect.isfunction(init_func)
|
| 173 |
+
and from_config is None
|
| 174 |
+
and init_func.__name__ == "__init__"
|
| 175 |
+
), "Incorrect use of @configurable. Check API documentation for examples."
|
| 176 |
+
|
| 177 |
+
@functools.wraps(init_func)
|
| 178 |
+
def wrapped(self, *args, **kwargs):
|
| 179 |
+
try:
|
| 180 |
+
from_config_func = type(self).from_config
|
| 181 |
+
except AttributeError as e:
|
| 182 |
+
raise AttributeError(
|
| 183 |
+
"Class with @configurable must have a 'from_config' classmethod."
|
| 184 |
+
) from e
|
| 185 |
+
if not inspect.ismethod(from_config_func):
|
| 186 |
+
raise TypeError("Class with @configurable must have a 'from_config' classmethod.")
|
| 187 |
+
|
| 188 |
+
if _called_with_cfg(*args, **kwargs):
|
| 189 |
+
explicit_args = _get_args_from_config(from_config_func, *args, **kwargs)
|
| 190 |
+
init_func(self, **explicit_args)
|
| 191 |
+
else:
|
| 192 |
+
init_func(self, *args, **kwargs)
|
| 193 |
+
|
| 194 |
+
return wrapped
|
| 195 |
+
|
| 196 |
+
else:
|
| 197 |
+
if from_config is None:
|
| 198 |
+
return configurable # @configurable() is made equivalent to @configurable
|
| 199 |
+
assert inspect.isfunction(
|
| 200 |
+
from_config
|
| 201 |
+
), "from_config argument of configurable must be a function!"
|
| 202 |
+
|
| 203 |
+
def wrapper(orig_func):
|
| 204 |
+
@functools.wraps(orig_func)
|
| 205 |
+
def wrapped(*args, **kwargs):
|
| 206 |
+
if _called_with_cfg(*args, **kwargs):
|
| 207 |
+
explicit_args = _get_args_from_config(from_config, *args, **kwargs)
|
| 208 |
+
return orig_func(**explicit_args)
|
| 209 |
+
else:
|
| 210 |
+
return orig_func(*args, **kwargs)
|
| 211 |
+
|
| 212 |
+
wrapped.from_config = from_config
|
| 213 |
+
return wrapped
|
| 214 |
+
|
| 215 |
+
return wrapper
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _get_args_from_config(from_config_func, *args, **kwargs):
|
| 219 |
+
"""
|
| 220 |
+
Use `from_config` to obtain explicit arguments.
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
dict: arguments to be used for cls.__init__
|
| 224 |
+
"""
|
| 225 |
+
signature = inspect.signature(from_config_func)
|
| 226 |
+
if list(signature.parameters.keys())[0] != "cfg":
|
| 227 |
+
if inspect.isfunction(from_config_func):
|
| 228 |
+
name = from_config_func.__name__
|
| 229 |
+
else:
|
| 230 |
+
name = f"{from_config_func.__self__}.from_config"
|
| 231 |
+
raise TypeError(f"{name} must take 'cfg' as the first argument!")
|
| 232 |
+
support_var_arg = any(
|
| 233 |
+
param.kind in [param.VAR_POSITIONAL, param.VAR_KEYWORD]
|
| 234 |
+
for param in signature.parameters.values()
|
| 235 |
+
)
|
| 236 |
+
if support_var_arg: # forward all arguments to from_config, if from_config accepts them
|
| 237 |
+
ret = from_config_func(*args, **kwargs)
|
| 238 |
+
else:
|
| 239 |
+
# forward supported arguments to from_config
|
| 240 |
+
supported_arg_names = set(signature.parameters.keys())
|
| 241 |
+
extra_kwargs = {}
|
| 242 |
+
for name in list(kwargs.keys()):
|
| 243 |
+
if name not in supported_arg_names:
|
| 244 |
+
extra_kwargs[name] = kwargs.pop(name)
|
| 245 |
+
ret = from_config_func(*args, **kwargs)
|
| 246 |
+
# forward the other arguments to __init__
|
| 247 |
+
ret.update(extra_kwargs)
|
| 248 |
+
return ret
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _called_with_cfg(*args, **kwargs):
|
| 252 |
+
"""
|
| 253 |
+
Returns:
|
| 254 |
+
bool: whether the arguments contain CfgNode and should be considered
|
| 255 |
+
forwarded to from_config.
|
| 256 |
+
"""
|
| 257 |
+
from omegaconf import DictConfig
|
| 258 |
+
|
| 259 |
+
if len(args) and isinstance(args[0], (_CfgNode, DictConfig)):
|
| 260 |
+
return True
|
| 261 |
+
if isinstance(kwargs.pop("cfg", None), (_CfgNode, DictConfig)):
|
| 262 |
+
return True
|
| 263 |
+
# `from_config`'s first argument is forced to be "cfg".
|
| 264 |
+
# So the above check covers all cases.
|
| 265 |
+
return False
|
RAVE-main/annotator/oneformer/detectron2/config/defaults.py
ADDED
|
@@ -0,0 +1,650 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.
|
| 2 |
+
from .config import CfgNode as CN
|
| 3 |
+
|
| 4 |
+
# NOTE: given the new config system
|
| 5 |
+
# (https://detectron2.readthedocs.io/en/latest/tutorials/lazyconfigs.html),
|
| 6 |
+
# we will stop adding new functionalities to default CfgNode.
|
| 7 |
+
|
| 8 |
+
# -----------------------------------------------------------------------------
|
| 9 |
+
# Convention about Training / Test specific parameters
|
| 10 |
+
# -----------------------------------------------------------------------------
|
| 11 |
+
# Whenever an argument can be either used for training or for testing, the
|
| 12 |
+
# corresponding name will be post-fixed by a _TRAIN for a training parameter,
|
| 13 |
+
# or _TEST for a test-specific parameter.
|
| 14 |
+
# For example, the number of images during training will be
|
| 15 |
+
# IMAGES_PER_BATCH_TRAIN, while the number of images for testing will be
|
| 16 |
+
# IMAGES_PER_BATCH_TEST
|
| 17 |
+
|
| 18 |
+
# -----------------------------------------------------------------------------
|
| 19 |
+
# Config definition
|
| 20 |
+
# -----------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
_C = CN()
|
| 23 |
+
|
| 24 |
+
# The version number, to upgrade from old configs to new ones if any
|
| 25 |
+
# changes happen. It's recommended to keep a VERSION in your config file.
|
| 26 |
+
_C.VERSION = 2
|
| 27 |
+
|
| 28 |
+
_C.MODEL = CN()
|
| 29 |
+
_C.MODEL.LOAD_PROPOSALS = False
|
| 30 |
+
_C.MODEL.MASK_ON = False
|
| 31 |
+
_C.MODEL.KEYPOINT_ON = False
|
| 32 |
+
_C.MODEL.DEVICE = "cuda"
|
| 33 |
+
_C.MODEL.META_ARCHITECTURE = "GeneralizedRCNN"
|
| 34 |
+
|
| 35 |
+
# Path (a file path, or URL like detectron2://.., https://..) to a checkpoint file
|
| 36 |
+
# to be loaded to the model. You can find available models in the model zoo.
|
| 37 |
+
_C.MODEL.WEIGHTS = ""
|
| 38 |
+
|
| 39 |
+
# Values to be used for image normalization (BGR order, since INPUT.FORMAT defaults to BGR).
|
| 40 |
+
# To train on images of different number of channels, just set different mean & std.
|
| 41 |
+
# Default values are the mean pixel value from ImageNet: [103.53, 116.28, 123.675]
|
| 42 |
+
_C.MODEL.PIXEL_MEAN = [103.530, 116.280, 123.675]
|
| 43 |
+
# When using pre-trained models in Detectron1 or any MSRA models,
|
| 44 |
+
# std has been absorbed into its conv1 weights, so the std needs to be set 1.
|
| 45 |
+
# Otherwise, you can use [57.375, 57.120, 58.395] (ImageNet std)
|
| 46 |
+
_C.MODEL.PIXEL_STD = [1.0, 1.0, 1.0]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# -----------------------------------------------------------------------------
|
| 50 |
+
# INPUT
|
| 51 |
+
# -----------------------------------------------------------------------------
|
| 52 |
+
_C.INPUT = CN()
|
| 53 |
+
# By default, {MIN,MAX}_SIZE options are used in transforms.ResizeShortestEdge.
|
| 54 |
+
# Please refer to ResizeShortestEdge for detailed definition.
|
| 55 |
+
# Size of the smallest side of the image during training
|
| 56 |
+
_C.INPUT.MIN_SIZE_TRAIN = (800,)
|
| 57 |
+
# Sample size of smallest side by choice or random selection from range give by
|
| 58 |
+
# INPUT.MIN_SIZE_TRAIN
|
| 59 |
+
_C.INPUT.MIN_SIZE_TRAIN_SAMPLING = "choice"
|
| 60 |
+
# Maximum size of the side of the image during training
|
| 61 |
+
_C.INPUT.MAX_SIZE_TRAIN = 1333
|
| 62 |
+
# Size of the smallest side of the image during testing. Set to zero to disable resize in testing.
|
| 63 |
+
_C.INPUT.MIN_SIZE_TEST = 800
|
| 64 |
+
# Maximum size of the side of the image during testing
|
| 65 |
+
_C.INPUT.MAX_SIZE_TEST = 1333
|
| 66 |
+
# Mode for flipping images used in data augmentation during training
|
| 67 |
+
# choose one of ["horizontal, "vertical", "none"]
|
| 68 |
+
_C.INPUT.RANDOM_FLIP = "horizontal"
|
| 69 |
+
|
| 70 |
+
# `True` if cropping is used for data augmentation during training
|
| 71 |
+
_C.INPUT.CROP = CN({"ENABLED": False})
|
| 72 |
+
# Cropping type. See documentation of `detectron2.data.transforms.RandomCrop` for explanation.
|
| 73 |
+
_C.INPUT.CROP.TYPE = "relative_range"
|
| 74 |
+
# Size of crop in range (0, 1] if CROP.TYPE is "relative" or "relative_range" and in number of
|
| 75 |
+
# pixels if CROP.TYPE is "absolute"
|
| 76 |
+
_C.INPUT.CROP.SIZE = [0.9, 0.9]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Whether the model needs RGB, YUV, HSV etc.
|
| 80 |
+
# Should be one of the modes defined here, as we use PIL to read the image:
|
| 81 |
+
# https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
|
| 82 |
+
# with BGR being the one exception. One can set image format to BGR, we will
|
| 83 |
+
# internally use RGB for conversion and flip the channels over
|
| 84 |
+
_C.INPUT.FORMAT = "BGR"
|
| 85 |
+
# The ground truth mask format that the model will use.
|
| 86 |
+
# Mask R-CNN supports either "polygon" or "bitmask" as ground truth.
|
| 87 |
+
_C.INPUT.MASK_FORMAT = "polygon" # alternative: "bitmask"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# -----------------------------------------------------------------------------
|
| 91 |
+
# Dataset
|
| 92 |
+
# -----------------------------------------------------------------------------
|
| 93 |
+
_C.DATASETS = CN()
|
| 94 |
+
# List of the dataset names for training. Must be registered in DatasetCatalog
|
| 95 |
+
# Samples from these datasets will be merged and used as one dataset.
|
| 96 |
+
_C.DATASETS.TRAIN = ()
|
| 97 |
+
# List of the pre-computed proposal files for training, which must be consistent
|
| 98 |
+
# with datasets listed in DATASETS.TRAIN.
|
| 99 |
+
_C.DATASETS.PROPOSAL_FILES_TRAIN = ()
|
| 100 |
+
# Number of top scoring precomputed proposals to keep for training
|
| 101 |
+
_C.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TRAIN = 2000
|
| 102 |
+
# List of the dataset names for testing. Must be registered in DatasetCatalog
|
| 103 |
+
_C.DATASETS.TEST = ()
|
| 104 |
+
# List of the pre-computed proposal files for test, which must be consistent
|
| 105 |
+
# with datasets listed in DATASETS.TEST.
|
| 106 |
+
_C.DATASETS.PROPOSAL_FILES_TEST = ()
|
| 107 |
+
# Number of top scoring precomputed proposals to keep for test
|
| 108 |
+
_C.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TEST = 1000
|
| 109 |
+
|
| 110 |
+
# -----------------------------------------------------------------------------
|
| 111 |
+
# DataLoader
|
| 112 |
+
# -----------------------------------------------------------------------------
|
| 113 |
+
_C.DATALOADER = CN()
|
| 114 |
+
# Number of data loading threads
|
| 115 |
+
_C.DATALOADER.NUM_WORKERS = 4
|
| 116 |
+
# If True, each batch should contain only images for which the aspect ratio
|
| 117 |
+
# is compatible. This groups portrait images together, and landscape images
|
| 118 |
+
# are not batched with portrait images.
|
| 119 |
+
_C.DATALOADER.ASPECT_RATIO_GROUPING = True
|
| 120 |
+
# Options: TrainingSampler, RepeatFactorTrainingSampler
|
| 121 |
+
_C.DATALOADER.SAMPLER_TRAIN = "TrainingSampler"
|
| 122 |
+
# Repeat threshold for RepeatFactorTrainingSampler
|
| 123 |
+
_C.DATALOADER.REPEAT_THRESHOLD = 0.0
|
| 124 |
+
# Tf True, when working on datasets that have instance annotations, the
|
| 125 |
+
# training dataloader will filter out images without associated annotations
|
| 126 |
+
_C.DATALOADER.FILTER_EMPTY_ANNOTATIONS = True
|
| 127 |
+
|
| 128 |
+
# ---------------------------------------------------------------------------- #
|
| 129 |
+
# Backbone options
|
| 130 |
+
# ---------------------------------------------------------------------------- #
|
| 131 |
+
_C.MODEL.BACKBONE = CN()
|
| 132 |
+
|
| 133 |
+
_C.MODEL.BACKBONE.NAME = "build_resnet_backbone"
|
| 134 |
+
# Freeze the first several stages so they are not trained.
|
| 135 |
+
# There are 5 stages in ResNet. The first is a convolution, and the following
|
| 136 |
+
# stages are each group of residual blocks.
|
| 137 |
+
_C.MODEL.BACKBONE.FREEZE_AT = 2
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ---------------------------------------------------------------------------- #
|
| 141 |
+
# FPN options
|
| 142 |
+
# ---------------------------------------------------------------------------- #
|
| 143 |
+
_C.MODEL.FPN = CN()
|
| 144 |
+
# Names of the input feature maps to be used by FPN
|
| 145 |
+
# They must have contiguous power of 2 strides
|
| 146 |
+
# e.g., ["res2", "res3", "res4", "res5"]
|
| 147 |
+
_C.MODEL.FPN.IN_FEATURES = []
|
| 148 |
+
_C.MODEL.FPN.OUT_CHANNELS = 256
|
| 149 |
+
|
| 150 |
+
# Options: "" (no norm), "GN"
|
| 151 |
+
_C.MODEL.FPN.NORM = ""
|
| 152 |
+
|
| 153 |
+
# Types for fusing the FPN top-down and lateral features. Can be either "sum" or "avg"
|
| 154 |
+
_C.MODEL.FPN.FUSE_TYPE = "sum"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# ---------------------------------------------------------------------------- #
|
| 158 |
+
# Proposal generator options
|
| 159 |
+
# ---------------------------------------------------------------------------- #
|
| 160 |
+
_C.MODEL.PROPOSAL_GENERATOR = CN()
|
| 161 |
+
# Current proposal generators include "RPN", "RRPN" and "PrecomputedProposals"
|
| 162 |
+
_C.MODEL.PROPOSAL_GENERATOR.NAME = "RPN"
|
| 163 |
+
# Proposal height and width both need to be greater than MIN_SIZE
|
| 164 |
+
# (a the scale used during training or inference)
|
| 165 |
+
_C.MODEL.PROPOSAL_GENERATOR.MIN_SIZE = 0
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ---------------------------------------------------------------------------- #
|
| 169 |
+
# Anchor generator options
|
| 170 |
+
# ---------------------------------------------------------------------------- #
|
| 171 |
+
_C.MODEL.ANCHOR_GENERATOR = CN()
|
| 172 |
+
# The generator can be any name in the ANCHOR_GENERATOR registry
|
| 173 |
+
_C.MODEL.ANCHOR_GENERATOR.NAME = "DefaultAnchorGenerator"
|
| 174 |
+
# Anchor sizes (i.e. sqrt of area) in absolute pixels w.r.t. the network input.
|
| 175 |
+
# Format: list[list[float]]. SIZES[i] specifies the list of sizes to use for
|
| 176 |
+
# IN_FEATURES[i]; len(SIZES) must be equal to len(IN_FEATURES) or 1.
|
| 177 |
+
# When len(SIZES) == 1, SIZES[0] is used for all IN_FEATURES.
|
| 178 |
+
_C.MODEL.ANCHOR_GENERATOR.SIZES = [[32, 64, 128, 256, 512]]
|
| 179 |
+
# Anchor aspect ratios. For each area given in `SIZES`, anchors with different aspect
|
| 180 |
+
# ratios are generated by an anchor generator.
|
| 181 |
+
# Format: list[list[float]]. ASPECT_RATIOS[i] specifies the list of aspect ratios (H/W)
|
| 182 |
+
# to use for IN_FEATURES[i]; len(ASPECT_RATIOS) == len(IN_FEATURES) must be true,
|
| 183 |
+
# or len(ASPECT_RATIOS) == 1 is true and aspect ratio list ASPECT_RATIOS[0] is used
|
| 184 |
+
# for all IN_FEATURES.
|
| 185 |
+
_C.MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS = [[0.5, 1.0, 2.0]]
|
| 186 |
+
# Anchor angles.
|
| 187 |
+
# list[list[float]], the angle in degrees, for each input feature map.
|
| 188 |
+
# ANGLES[i] specifies the list of angles for IN_FEATURES[i].
|
| 189 |
+
_C.MODEL.ANCHOR_GENERATOR.ANGLES = [[-90, 0, 90]]
|
| 190 |
+
# Relative offset between the center of the first anchor and the top-left corner of the image
|
| 191 |
+
# Value has to be in [0, 1). Recommend to use 0.5, which means half stride.
|
| 192 |
+
# The value is not expected to affect model accuracy.
|
| 193 |
+
_C.MODEL.ANCHOR_GENERATOR.OFFSET = 0.0
|
| 194 |
+
|
| 195 |
+
# ---------------------------------------------------------------------------- #
|
| 196 |
+
# RPN options
|
| 197 |
+
# ---------------------------------------------------------------------------- #
|
| 198 |
+
_C.MODEL.RPN = CN()
|
| 199 |
+
_C.MODEL.RPN.HEAD_NAME = "StandardRPNHead" # used by RPN_HEAD_REGISTRY
|
| 200 |
+
|
| 201 |
+
# Names of the input feature maps to be used by RPN
|
| 202 |
+
# e.g., ["p2", "p3", "p4", "p5", "p6"] for FPN
|
| 203 |
+
_C.MODEL.RPN.IN_FEATURES = ["res4"]
|
| 204 |
+
# Remove RPN anchors that go outside the image by BOUNDARY_THRESH pixels
|
| 205 |
+
# Set to -1 or a large value, e.g. 100000, to disable pruning anchors
|
| 206 |
+
_C.MODEL.RPN.BOUNDARY_THRESH = -1
|
| 207 |
+
# IOU overlap ratios [BG_IOU_THRESHOLD, FG_IOU_THRESHOLD]
|
| 208 |
+
# Minimum overlap required between an anchor and ground-truth box for the
|
| 209 |
+
# (anchor, gt box) pair to be a positive example (IoU >= FG_IOU_THRESHOLD
|
| 210 |
+
# ==> positive RPN example: 1)
|
| 211 |
+
# Maximum overlap allowed between an anchor and ground-truth box for the
|
| 212 |
+
# (anchor, gt box) pair to be a negative examples (IoU < BG_IOU_THRESHOLD
|
| 213 |
+
# ==> negative RPN example: 0)
|
| 214 |
+
# Anchors with overlap in between (BG_IOU_THRESHOLD <= IoU < FG_IOU_THRESHOLD)
|
| 215 |
+
# are ignored (-1)
|
| 216 |
+
_C.MODEL.RPN.IOU_THRESHOLDS = [0.3, 0.7]
|
| 217 |
+
_C.MODEL.RPN.IOU_LABELS = [0, -1, 1]
|
| 218 |
+
# Number of regions per image used to train RPN
|
| 219 |
+
_C.MODEL.RPN.BATCH_SIZE_PER_IMAGE = 256
|
| 220 |
+
# Target fraction of foreground (positive) examples per RPN minibatch
|
| 221 |
+
_C.MODEL.RPN.POSITIVE_FRACTION = 0.5
|
| 222 |
+
# Options are: "smooth_l1", "giou", "diou", "ciou"
|
| 223 |
+
_C.MODEL.RPN.BBOX_REG_LOSS_TYPE = "smooth_l1"
|
| 224 |
+
_C.MODEL.RPN.BBOX_REG_LOSS_WEIGHT = 1.0
|
| 225 |
+
# Weights on (dx, dy, dw, dh) for normalizing RPN anchor regression targets
|
| 226 |
+
_C.MODEL.RPN.BBOX_REG_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
|
| 227 |
+
# The transition point from L1 to L2 loss. Set to 0.0 to make the loss simply L1.
|
| 228 |
+
_C.MODEL.RPN.SMOOTH_L1_BETA = 0.0
|
| 229 |
+
_C.MODEL.RPN.LOSS_WEIGHT = 1.0
|
| 230 |
+
# Number of top scoring RPN proposals to keep before applying NMS
|
| 231 |
+
# When FPN is used, this is *per FPN level* (not total)
|
| 232 |
+
_C.MODEL.RPN.PRE_NMS_TOPK_TRAIN = 12000
|
| 233 |
+
_C.MODEL.RPN.PRE_NMS_TOPK_TEST = 6000
|
| 234 |
+
# Number of top scoring RPN proposals to keep after applying NMS
|
| 235 |
+
# When FPN is used, this limit is applied per level and then again to the union
|
| 236 |
+
# of proposals from all levels
|
| 237 |
+
# NOTE: When FPN is used, the meaning of this config is different from Detectron1.
|
| 238 |
+
# It means per-batch topk in Detectron1, but per-image topk here.
|
| 239 |
+
# See the "find_top_rpn_proposals" function for details.
|
| 240 |
+
_C.MODEL.RPN.POST_NMS_TOPK_TRAIN = 2000
|
| 241 |
+
_C.MODEL.RPN.POST_NMS_TOPK_TEST = 1000
|
| 242 |
+
# NMS threshold used on RPN proposals
|
| 243 |
+
_C.MODEL.RPN.NMS_THRESH = 0.7
|
| 244 |
+
# Set this to -1 to use the same number of output channels as input channels.
|
| 245 |
+
_C.MODEL.RPN.CONV_DIMS = [-1]
|
| 246 |
+
|
| 247 |
+
# ---------------------------------------------------------------------------- #
|
| 248 |
+
# ROI HEADS options
|
| 249 |
+
# ---------------------------------------------------------------------------- #
|
| 250 |
+
_C.MODEL.ROI_HEADS = CN()
|
| 251 |
+
_C.MODEL.ROI_HEADS.NAME = "Res5ROIHeads"
|
| 252 |
+
# Number of foreground classes
|
| 253 |
+
_C.MODEL.ROI_HEADS.NUM_CLASSES = 80
|
| 254 |
+
# Names of the input feature maps to be used by ROI heads
|
| 255 |
+
# Currently all heads (box, mask, ...) use the same input feature map list
|
| 256 |
+
# e.g., ["p2", "p3", "p4", "p5"] is commonly used for FPN
|
| 257 |
+
_C.MODEL.ROI_HEADS.IN_FEATURES = ["res4"]
|
| 258 |
+
# IOU overlap ratios [IOU_THRESHOLD]
|
| 259 |
+
# Overlap threshold for an RoI to be considered background (if < IOU_THRESHOLD)
|
| 260 |
+
# Overlap threshold for an RoI to be considered foreground (if >= IOU_THRESHOLD)
|
| 261 |
+
_C.MODEL.ROI_HEADS.IOU_THRESHOLDS = [0.5]
|
| 262 |
+
_C.MODEL.ROI_HEADS.IOU_LABELS = [0, 1]
|
| 263 |
+
# RoI minibatch size *per image* (number of regions of interest [ROIs]) during training
|
| 264 |
+
# Total number of RoIs per training minibatch =
|
| 265 |
+
# ROI_HEADS.BATCH_SIZE_PER_IMAGE * SOLVER.IMS_PER_BATCH
|
| 266 |
+
# E.g., a common configuration is: 512 * 16 = 8192
|
| 267 |
+
_C.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 512
|
| 268 |
+
# Target fraction of RoI minibatch that is labeled foreground (i.e. class > 0)
|
| 269 |
+
_C.MODEL.ROI_HEADS.POSITIVE_FRACTION = 0.25
|
| 270 |
+
|
| 271 |
+
# Only used on test mode
|
| 272 |
+
|
| 273 |
+
# Minimum score threshold (assuming scores in a [0, 1] range); a value chosen to
|
| 274 |
+
# balance obtaining high recall with not having too many low precision
|
| 275 |
+
# detections that will slow down inference post processing steps (like NMS)
|
| 276 |
+
# A default threshold of 0.0 increases AP by ~0.2-0.3 but significantly slows down
|
| 277 |
+
# inference.
|
| 278 |
+
_C.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.05
|
| 279 |
+
# Overlap threshold used for non-maximum suppression (suppress boxes with
|
| 280 |
+
# IoU >= this threshold)
|
| 281 |
+
_C.MODEL.ROI_HEADS.NMS_THRESH_TEST = 0.5
|
| 282 |
+
# If True, augment proposals with ground-truth boxes before sampling proposals to
|
| 283 |
+
# train ROI heads.
|
| 284 |
+
_C.MODEL.ROI_HEADS.PROPOSAL_APPEND_GT = True
|
| 285 |
+
|
| 286 |
+
# ---------------------------------------------------------------------------- #
|
| 287 |
+
# Box Head
|
| 288 |
+
# ---------------------------------------------------------------------------- #
|
| 289 |
+
_C.MODEL.ROI_BOX_HEAD = CN()
|
| 290 |
+
# C4 don't use head name option
|
| 291 |
+
# Options for non-C4 models: FastRCNNConvFCHead,
|
| 292 |
+
_C.MODEL.ROI_BOX_HEAD.NAME = ""
|
| 293 |
+
# Options are: "smooth_l1", "giou", "diou", "ciou"
|
| 294 |
+
_C.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_TYPE = "smooth_l1"
|
| 295 |
+
# The final scaling coefficient on the box regression loss, used to balance the magnitude of its
|
| 296 |
+
# gradients with other losses in the model. See also `MODEL.ROI_KEYPOINT_HEAD.LOSS_WEIGHT`.
|
| 297 |
+
_C.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_WEIGHT = 1.0
|
| 298 |
+
# Default weights on (dx, dy, dw, dh) for normalizing bbox regression targets
|
| 299 |
+
# These are empirically chosen to approximately lead to unit variance targets
|
| 300 |
+
_C.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS = (10.0, 10.0, 5.0, 5.0)
|
| 301 |
+
# The transition point from L1 to L2 loss. Set to 0.0 to make the loss simply L1.
|
| 302 |
+
_C.MODEL.ROI_BOX_HEAD.SMOOTH_L1_BETA = 0.0
|
| 303 |
+
_C.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION = 14
|
| 304 |
+
_C.MODEL.ROI_BOX_HEAD.POOLER_SAMPLING_RATIO = 0
|
| 305 |
+
# Type of pooling operation applied to the incoming feature map for each RoI
|
| 306 |
+
_C.MODEL.ROI_BOX_HEAD.POOLER_TYPE = "ROIAlignV2"
|
| 307 |
+
|
| 308 |
+
_C.MODEL.ROI_BOX_HEAD.NUM_FC = 0
|
| 309 |
+
# Hidden layer dimension for FC layers in the RoI box head
|
| 310 |
+
_C.MODEL.ROI_BOX_HEAD.FC_DIM = 1024
|
| 311 |
+
_C.MODEL.ROI_BOX_HEAD.NUM_CONV = 0
|
| 312 |
+
# Channel dimension for Conv layers in the RoI box head
|
| 313 |
+
_C.MODEL.ROI_BOX_HEAD.CONV_DIM = 256
|
| 314 |
+
# Normalization method for the convolution layers.
|
| 315 |
+
# Options: "" (no norm), "GN", "SyncBN".
|
| 316 |
+
_C.MODEL.ROI_BOX_HEAD.NORM = ""
|
| 317 |
+
# Whether to use class agnostic for bbox regression
|
| 318 |
+
_C.MODEL.ROI_BOX_HEAD.CLS_AGNOSTIC_BBOX_REG = False
|
| 319 |
+
# If true, RoI heads use bounding boxes predicted by the box head rather than proposal boxes.
|
| 320 |
+
_C.MODEL.ROI_BOX_HEAD.TRAIN_ON_PRED_BOXES = False
|
| 321 |
+
|
| 322 |
+
# Federated loss can be used to improve the training of LVIS
|
| 323 |
+
_C.MODEL.ROI_BOX_HEAD.USE_FED_LOSS = False
|
| 324 |
+
# Sigmoid cross entrophy is used with federated loss
|
| 325 |
+
_C.MODEL.ROI_BOX_HEAD.USE_SIGMOID_CE = False
|
| 326 |
+
# The power value applied to image_count when calcualting frequency weight
|
| 327 |
+
_C.MODEL.ROI_BOX_HEAD.FED_LOSS_FREQ_WEIGHT_POWER = 0.5
|
| 328 |
+
# Number of classes to keep in total
|
| 329 |
+
_C.MODEL.ROI_BOX_HEAD.FED_LOSS_NUM_CLASSES = 50
|
| 330 |
+
|
| 331 |
+
# ---------------------------------------------------------------------------- #
|
| 332 |
+
# Cascaded Box Head
|
| 333 |
+
# ---------------------------------------------------------------------------- #
|
| 334 |
+
_C.MODEL.ROI_BOX_CASCADE_HEAD = CN()
|
| 335 |
+
# The number of cascade stages is implicitly defined by the length of the following two configs.
|
| 336 |
+
_C.MODEL.ROI_BOX_CASCADE_HEAD.BBOX_REG_WEIGHTS = (
|
| 337 |
+
(10.0, 10.0, 5.0, 5.0),
|
| 338 |
+
(20.0, 20.0, 10.0, 10.0),
|
| 339 |
+
(30.0, 30.0, 15.0, 15.0),
|
| 340 |
+
)
|
| 341 |
+
_C.MODEL.ROI_BOX_CASCADE_HEAD.IOUS = (0.5, 0.6, 0.7)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
# ---------------------------------------------------------------------------- #
|
| 345 |
+
# Mask Head
|
| 346 |
+
# ---------------------------------------------------------------------------- #
|
| 347 |
+
_C.MODEL.ROI_MASK_HEAD = CN()
|
| 348 |
+
_C.MODEL.ROI_MASK_HEAD.NAME = "MaskRCNNConvUpsampleHead"
|
| 349 |
+
_C.MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION = 14
|
| 350 |
+
_C.MODEL.ROI_MASK_HEAD.POOLER_SAMPLING_RATIO = 0
|
| 351 |
+
_C.MODEL.ROI_MASK_HEAD.NUM_CONV = 0 # The number of convs in the mask head
|
| 352 |
+
_C.MODEL.ROI_MASK_HEAD.CONV_DIM = 256
|
| 353 |
+
# Normalization method for the convolution layers.
|
| 354 |
+
# Options: "" (no norm), "GN", "SyncBN".
|
| 355 |
+
_C.MODEL.ROI_MASK_HEAD.NORM = ""
|
| 356 |
+
# Whether to use class agnostic for mask prediction
|
| 357 |
+
_C.MODEL.ROI_MASK_HEAD.CLS_AGNOSTIC_MASK = False
|
| 358 |
+
# Type of pooling operation applied to the incoming feature map for each RoI
|
| 359 |
+
_C.MODEL.ROI_MASK_HEAD.POOLER_TYPE = "ROIAlignV2"
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------- #
|
| 363 |
+
# Keypoint Head
|
| 364 |
+
# ---------------------------------------------------------------------------- #
|
| 365 |
+
_C.MODEL.ROI_KEYPOINT_HEAD = CN()
|
| 366 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.NAME = "KRCNNConvDeconvUpsampleHead"
|
| 367 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.POOLER_RESOLUTION = 14
|
| 368 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.POOLER_SAMPLING_RATIO = 0
|
| 369 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.CONV_DIMS = tuple(512 for _ in range(8))
|
| 370 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.NUM_KEYPOINTS = 17 # 17 is the number of keypoints in COCO.
|
| 371 |
+
|
| 372 |
+
# Images with too few (or no) keypoints are excluded from training.
|
| 373 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAGE = 1
|
| 374 |
+
# Normalize by the total number of visible keypoints in the minibatch if True.
|
| 375 |
+
# Otherwise, normalize by the total number of keypoints that could ever exist
|
| 376 |
+
# in the minibatch.
|
| 377 |
+
# The keypoint softmax loss is only calculated on visible keypoints.
|
| 378 |
+
# Since the number of visible keypoints can vary significantly between
|
| 379 |
+
# minibatches, this has the effect of up-weighting the importance of
|
| 380 |
+
# minibatches with few visible keypoints. (Imagine the extreme case of
|
| 381 |
+
# only one visible keypoint versus N: in the case of N, each one
|
| 382 |
+
# contributes 1/N to the gradient compared to the single keypoint
|
| 383 |
+
# determining the gradient direction). Instead, we can normalize the
|
| 384 |
+
# loss by the total number of keypoints, if it were the case that all
|
| 385 |
+
# keypoints were visible in a full minibatch. (Returning to the example,
|
| 386 |
+
# this means that the one visible keypoint contributes as much as each
|
| 387 |
+
# of the N keypoints.)
|
| 388 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.NORMALIZE_LOSS_BY_VISIBLE_KEYPOINTS = True
|
| 389 |
+
# Multi-task loss weight to use for keypoints
|
| 390 |
+
# Recommended values:
|
| 391 |
+
# - use 1.0 if NORMALIZE_LOSS_BY_VISIBLE_KEYPOINTS is True
|
| 392 |
+
# - use 4.0 if NORMALIZE_LOSS_BY_VISIBLE_KEYPOINTS is False
|
| 393 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.LOSS_WEIGHT = 1.0
|
| 394 |
+
# Type of pooling operation applied to the incoming feature map for each RoI
|
| 395 |
+
_C.MODEL.ROI_KEYPOINT_HEAD.POOLER_TYPE = "ROIAlignV2"
|
| 396 |
+
|
| 397 |
+
# ---------------------------------------------------------------------------- #
|
| 398 |
+
# Semantic Segmentation Head
|
| 399 |
+
# ---------------------------------------------------------------------------- #
|
| 400 |
+
_C.MODEL.SEM_SEG_HEAD = CN()
|
| 401 |
+
_C.MODEL.SEM_SEG_HEAD.NAME = "SemSegFPNHead"
|
| 402 |
+
_C.MODEL.SEM_SEG_HEAD.IN_FEATURES = ["p2", "p3", "p4", "p5"]
|
| 403 |
+
# Label in the semantic segmentation ground truth that is ignored, i.e., no loss is calculated for
|
| 404 |
+
# the correposnding pixel.
|
| 405 |
+
_C.MODEL.SEM_SEG_HEAD.IGNORE_VALUE = 255
|
| 406 |
+
# Number of classes in the semantic segmentation head
|
| 407 |
+
_C.MODEL.SEM_SEG_HEAD.NUM_CLASSES = 54
|
| 408 |
+
# Number of channels in the 3x3 convs inside semantic-FPN heads.
|
| 409 |
+
_C.MODEL.SEM_SEG_HEAD.CONVS_DIM = 128
|
| 410 |
+
# Outputs from semantic-FPN heads are up-scaled to the COMMON_STRIDE stride.
|
| 411 |
+
_C.MODEL.SEM_SEG_HEAD.COMMON_STRIDE = 4
|
| 412 |
+
# Normalization method for the convolution layers. Options: "" (no norm), "GN".
|
| 413 |
+
_C.MODEL.SEM_SEG_HEAD.NORM = "GN"
|
| 414 |
+
_C.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT = 1.0
|
| 415 |
+
|
| 416 |
+
_C.MODEL.PANOPTIC_FPN = CN()
|
| 417 |
+
# Scaling of all losses from instance detection / segmentation head.
|
| 418 |
+
_C.MODEL.PANOPTIC_FPN.INSTANCE_LOSS_WEIGHT = 1.0
|
| 419 |
+
|
| 420 |
+
# options when combining instance & semantic segmentation outputs
|
| 421 |
+
_C.MODEL.PANOPTIC_FPN.COMBINE = CN({"ENABLED": True}) # "COMBINE.ENABLED" is deprecated & not used
|
| 422 |
+
_C.MODEL.PANOPTIC_FPN.COMBINE.OVERLAP_THRESH = 0.5
|
| 423 |
+
_C.MODEL.PANOPTIC_FPN.COMBINE.STUFF_AREA_LIMIT = 4096
|
| 424 |
+
_C.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = 0.5
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
# ---------------------------------------------------------------------------- #
|
| 428 |
+
# RetinaNet Head
|
| 429 |
+
# ---------------------------------------------------------------------------- #
|
| 430 |
+
_C.MODEL.RETINANET = CN()
|
| 431 |
+
|
| 432 |
+
# This is the number of foreground classes.
|
| 433 |
+
_C.MODEL.RETINANET.NUM_CLASSES = 80
|
| 434 |
+
|
| 435 |
+
_C.MODEL.RETINANET.IN_FEATURES = ["p3", "p4", "p5", "p6", "p7"]
|
| 436 |
+
|
| 437 |
+
# Convolutions to use in the cls and bbox tower
|
| 438 |
+
# NOTE: this doesn't include the last conv for logits
|
| 439 |
+
_C.MODEL.RETINANET.NUM_CONVS = 4
|
| 440 |
+
|
| 441 |
+
# IoU overlap ratio [bg, fg] for labeling anchors.
|
| 442 |
+
# Anchors with < bg are labeled negative (0)
|
| 443 |
+
# Anchors with >= bg and < fg are ignored (-1)
|
| 444 |
+
# Anchors with >= fg are labeled positive (1)
|
| 445 |
+
_C.MODEL.RETINANET.IOU_THRESHOLDS = [0.4, 0.5]
|
| 446 |
+
_C.MODEL.RETINANET.IOU_LABELS = [0, -1, 1]
|
| 447 |
+
|
| 448 |
+
# Prior prob for rare case (i.e. foreground) at the beginning of training.
|
| 449 |
+
# This is used to set the bias for the logits layer of the classifier subnet.
|
| 450 |
+
# This improves training stability in the case of heavy class imbalance.
|
| 451 |
+
_C.MODEL.RETINANET.PRIOR_PROB = 0.01
|
| 452 |
+
|
| 453 |
+
# Inference cls score threshold, only anchors with score > INFERENCE_TH are
|
| 454 |
+
# considered for inference (to improve speed)
|
| 455 |
+
_C.MODEL.RETINANET.SCORE_THRESH_TEST = 0.05
|
| 456 |
+
# Select topk candidates before NMS
|
| 457 |
+
_C.MODEL.RETINANET.TOPK_CANDIDATES_TEST = 1000
|
| 458 |
+
_C.MODEL.RETINANET.NMS_THRESH_TEST = 0.5
|
| 459 |
+
|
| 460 |
+
# Weights on (dx, dy, dw, dh) for normalizing Retinanet anchor regression targets
|
| 461 |
+
_C.MODEL.RETINANET.BBOX_REG_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
|
| 462 |
+
|
| 463 |
+
# Loss parameters
|
| 464 |
+
_C.MODEL.RETINANET.FOCAL_LOSS_GAMMA = 2.0
|
| 465 |
+
_C.MODEL.RETINANET.FOCAL_LOSS_ALPHA = 0.25
|
| 466 |
+
_C.MODEL.RETINANET.SMOOTH_L1_LOSS_BETA = 0.1
|
| 467 |
+
# Options are: "smooth_l1", "giou", "diou", "ciou"
|
| 468 |
+
_C.MODEL.RETINANET.BBOX_REG_LOSS_TYPE = "smooth_l1"
|
| 469 |
+
|
| 470 |
+
# One of BN, SyncBN, FrozenBN, GN
|
| 471 |
+
# Only supports GN until unshared norm is implemented
|
| 472 |
+
_C.MODEL.RETINANET.NORM = ""
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
# ---------------------------------------------------------------------------- #
|
| 476 |
+
# ResNe[X]t options (ResNets = {ResNet, ResNeXt}
|
| 477 |
+
# Note that parts of a resnet may be used for both the backbone and the head
|
| 478 |
+
# These options apply to both
|
| 479 |
+
# ---------------------------------------------------------------------------- #
|
| 480 |
+
_C.MODEL.RESNETS = CN()
|
| 481 |
+
|
| 482 |
+
_C.MODEL.RESNETS.DEPTH = 50
|
| 483 |
+
_C.MODEL.RESNETS.OUT_FEATURES = ["res4"] # res4 for C4 backbone, res2..5 for FPN backbone
|
| 484 |
+
|
| 485 |
+
# Number of groups to use; 1 ==> ResNet; > 1 ==> ResNeXt
|
| 486 |
+
_C.MODEL.RESNETS.NUM_GROUPS = 1
|
| 487 |
+
|
| 488 |
+
# Options: FrozenBN, GN, "SyncBN", "BN"
|
| 489 |
+
_C.MODEL.RESNETS.NORM = "FrozenBN"
|
| 490 |
+
|
| 491 |
+
# Baseline width of each group.
|
| 492 |
+
# Scaling this parameters will scale the width of all bottleneck layers.
|
| 493 |
+
_C.MODEL.RESNETS.WIDTH_PER_GROUP = 64
|
| 494 |
+
|
| 495 |
+
# Place the stride 2 conv on the 1x1 filter
|
| 496 |
+
# Use True only for the original MSRA ResNet; use False for C2 and Torch models
|
| 497 |
+
_C.MODEL.RESNETS.STRIDE_IN_1X1 = True
|
| 498 |
+
|
| 499 |
+
# Apply dilation in stage "res5"
|
| 500 |
+
_C.MODEL.RESNETS.RES5_DILATION = 1
|
| 501 |
+
|
| 502 |
+
# Output width of res2. Scaling this parameters will scale the width of all 1x1 convs in ResNet
|
| 503 |
+
# For R18 and R34, this needs to be set to 64
|
| 504 |
+
_C.MODEL.RESNETS.RES2_OUT_CHANNELS = 256
|
| 505 |
+
_C.MODEL.RESNETS.STEM_OUT_CHANNELS = 64
|
| 506 |
+
|
| 507 |
+
# Apply Deformable Convolution in stages
|
| 508 |
+
# Specify if apply deform_conv on Res2, Res3, Res4, Res5
|
| 509 |
+
_C.MODEL.RESNETS.DEFORM_ON_PER_STAGE = [False, False, False, False]
|
| 510 |
+
# Use True to use modulated deform_conv (DeformableV2, https://arxiv.org/abs/1811.11168);
|
| 511 |
+
# Use False for DeformableV1.
|
| 512 |
+
_C.MODEL.RESNETS.DEFORM_MODULATED = False
|
| 513 |
+
# Number of groups in deformable conv.
|
| 514 |
+
_C.MODEL.RESNETS.DEFORM_NUM_GROUPS = 1
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
# ---------------------------------------------------------------------------- #
|
| 518 |
+
# Solver
|
| 519 |
+
# ---------------------------------------------------------------------------- #
|
| 520 |
+
_C.SOLVER = CN()
|
| 521 |
+
|
| 522 |
+
# Options: WarmupMultiStepLR, WarmupCosineLR.
|
| 523 |
+
# See detectron2/solver/build.py for definition.
|
| 524 |
+
_C.SOLVER.LR_SCHEDULER_NAME = "WarmupMultiStepLR"
|
| 525 |
+
|
| 526 |
+
_C.SOLVER.MAX_ITER = 40000
|
| 527 |
+
|
| 528 |
+
_C.SOLVER.BASE_LR = 0.001
|
| 529 |
+
# The end lr, only used by WarmupCosineLR
|
| 530 |
+
_C.SOLVER.BASE_LR_END = 0.0
|
| 531 |
+
|
| 532 |
+
_C.SOLVER.MOMENTUM = 0.9
|
| 533 |
+
|
| 534 |
+
_C.SOLVER.NESTEROV = False
|
| 535 |
+
|
| 536 |
+
_C.SOLVER.WEIGHT_DECAY = 0.0001
|
| 537 |
+
# The weight decay that's applied to parameters of normalization layers
|
| 538 |
+
# (typically the affine transformation)
|
| 539 |
+
_C.SOLVER.WEIGHT_DECAY_NORM = 0.0
|
| 540 |
+
|
| 541 |
+
_C.SOLVER.GAMMA = 0.1
|
| 542 |
+
# The iteration number to decrease learning rate by GAMMA.
|
| 543 |
+
_C.SOLVER.STEPS = (30000,)
|
| 544 |
+
# Number of decays in WarmupStepWithFixedGammaLR schedule
|
| 545 |
+
_C.SOLVER.NUM_DECAYS = 3
|
| 546 |
+
|
| 547 |
+
_C.SOLVER.WARMUP_FACTOR = 1.0 / 1000
|
| 548 |
+
_C.SOLVER.WARMUP_ITERS = 1000
|
| 549 |
+
_C.SOLVER.WARMUP_METHOD = "linear"
|
| 550 |
+
# Whether to rescale the interval for the learning schedule after warmup
|
| 551 |
+
_C.SOLVER.RESCALE_INTERVAL = False
|
| 552 |
+
|
| 553 |
+
# Save a checkpoint after every this number of iterations
|
| 554 |
+
_C.SOLVER.CHECKPOINT_PERIOD = 5000
|
| 555 |
+
|
| 556 |
+
# Number of images per batch across all machines. This is also the number
|
| 557 |
+
# of training images per step (i.e. per iteration). If we use 16 GPUs
|
| 558 |
+
# and IMS_PER_BATCH = 32, each GPU will see 2 images per batch.
|
| 559 |
+
# May be adjusted automatically if REFERENCE_WORLD_SIZE is set.
|
| 560 |
+
_C.SOLVER.IMS_PER_BATCH = 16
|
| 561 |
+
|
| 562 |
+
# The reference number of workers (GPUs) this config is meant to train with.
|
| 563 |
+
# It takes no effect when set to 0.
|
| 564 |
+
# With a non-zero value, it will be used by DefaultTrainer to compute a desired
|
| 565 |
+
# per-worker batch size, and then scale the other related configs (total batch size,
|
| 566 |
+
# learning rate, etc) to match the per-worker batch size.
|
| 567 |
+
# See documentation of `DefaultTrainer.auto_scale_workers` for details:
|
| 568 |
+
_C.SOLVER.REFERENCE_WORLD_SIZE = 0
|
| 569 |
+
|
| 570 |
+
# Detectron v1 (and previous detection code) used a 2x higher LR and 0 WD for
|
| 571 |
+
# biases. This is not useful (at least for recent models). You should avoid
|
| 572 |
+
# changing these and they exist only to reproduce Detectron v1 training if
|
| 573 |
+
# desired.
|
| 574 |
+
_C.SOLVER.BIAS_LR_FACTOR = 1.0
|
| 575 |
+
_C.SOLVER.WEIGHT_DECAY_BIAS = None # None means following WEIGHT_DECAY
|
| 576 |
+
|
| 577 |
+
# Gradient clipping
|
| 578 |
+
_C.SOLVER.CLIP_GRADIENTS = CN({"ENABLED": False})
|
| 579 |
+
# Type of gradient clipping, currently 2 values are supported:
|
| 580 |
+
# - "value": the absolute values of elements of each gradients are clipped
|
| 581 |
+
# - "norm": the norm of the gradient for each parameter is clipped thus
|
| 582 |
+
# affecting all elements in the parameter
|
| 583 |
+
_C.SOLVER.CLIP_GRADIENTS.CLIP_TYPE = "value"
|
| 584 |
+
# Maximum absolute value used for clipping gradients
|
| 585 |
+
_C.SOLVER.CLIP_GRADIENTS.CLIP_VALUE = 1.0
|
| 586 |
+
# Floating point number p for L-p norm to be used with the "norm"
|
| 587 |
+
# gradient clipping type; for L-inf, please specify .inf
|
| 588 |
+
_C.SOLVER.CLIP_GRADIENTS.NORM_TYPE = 2.0
|
| 589 |
+
|
| 590 |
+
# Enable automatic mixed precision for training
|
| 591 |
+
# Note that this does not change model's inference behavior.
|
| 592 |
+
# To use AMP in inference, run inference under autocast()
|
| 593 |
+
_C.SOLVER.AMP = CN({"ENABLED": False})
|
| 594 |
+
|
| 595 |
+
# ---------------------------------------------------------------------------- #
|
| 596 |
+
# Specific test options
|
| 597 |
+
# ---------------------------------------------------------------------------- #
|
| 598 |
+
_C.TEST = CN()
|
| 599 |
+
# For end-to-end tests to verify the expected accuracy.
|
| 600 |
+
# Each item is [task, metric, value, tolerance]
|
| 601 |
+
# e.g.: [['bbox', 'AP', 38.5, 0.2]]
|
| 602 |
+
_C.TEST.EXPECTED_RESULTS = []
|
| 603 |
+
# The period (in terms of steps) to evaluate the model during training.
|
| 604 |
+
# Set to 0 to disable.
|
| 605 |
+
_C.TEST.EVAL_PERIOD = 0
|
| 606 |
+
# The sigmas used to calculate keypoint OKS. See http://cocodataset.org/#keypoints-eval
|
| 607 |
+
# When empty, it will use the defaults in COCO.
|
| 608 |
+
# Otherwise it should be a list[float] with the same length as ROI_KEYPOINT_HEAD.NUM_KEYPOINTS.
|
| 609 |
+
_C.TEST.KEYPOINT_OKS_SIGMAS = []
|
| 610 |
+
# Maximum number of detections to return per image during inference (100 is
|
| 611 |
+
# based on the limit established for the COCO dataset).
|
| 612 |
+
_C.TEST.DETECTIONS_PER_IMAGE = 100
|
| 613 |
+
|
| 614 |
+
_C.TEST.AUG = CN({"ENABLED": False})
|
| 615 |
+
_C.TEST.AUG.MIN_SIZES = (400, 500, 600, 700, 800, 900, 1000, 1100, 1200)
|
| 616 |
+
_C.TEST.AUG.MAX_SIZE = 4000
|
| 617 |
+
_C.TEST.AUG.FLIP = True
|
| 618 |
+
|
| 619 |
+
_C.TEST.PRECISE_BN = CN({"ENABLED": False})
|
| 620 |
+
_C.TEST.PRECISE_BN.NUM_ITER = 200
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------- #
|
| 623 |
+
# Misc options
|
| 624 |
+
# ---------------------------------------------------------------------------- #
|
| 625 |
+
# Directory where output files are written
|
| 626 |
+
_C.OUTPUT_DIR = "./output"
|
| 627 |
+
# Set seed to negative to fully randomize everything.
|
| 628 |
+
# Set seed to positive to use a fixed seed. Note that a fixed seed increases
|
| 629 |
+
# reproducibility but does not guarantee fully deterministic behavior.
|
| 630 |
+
# Disabling all parallelism further increases reproducibility.
|
| 631 |
+
_C.SEED = -1
|
| 632 |
+
# Benchmark different cudnn algorithms.
|
| 633 |
+
# If input images have very different sizes, this option will have large overhead
|
| 634 |
+
# for about 10k iterations. It usually hurts total time, but can benefit for certain models.
|
| 635 |
+
# If input images have the same or similar sizes, benchmark is often helpful.
|
| 636 |
+
_C.CUDNN_BENCHMARK = False
|
| 637 |
+
# The period (in terms of steps) for minibatch visualization at train time.
|
| 638 |
+
# Set to 0 to disable.
|
| 639 |
+
_C.VIS_PERIOD = 0
|
| 640 |
+
|
| 641 |
+
# global config is for quick hack purposes.
|
| 642 |
+
# You can set them in command line or config files,
|
| 643 |
+
# and access it with:
|
| 644 |
+
#
|
| 645 |
+
# from annotator.oneformer.detectron2.config import global_cfg
|
| 646 |
+
# print(global_cfg.HACK)
|
| 647 |
+
#
|
| 648 |
+
# Do not commit any configs into it.
|
| 649 |
+
_C.GLOBAL = CN()
|
| 650 |
+
_C.GLOBAL.HACK = 1.0
|
RAVE-main/annotator/oneformer/detectron2/config/instantiate.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
|
| 3 |
+
import collections.abc as abc
|
| 4 |
+
import dataclasses
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from annotator.oneformer.detectron2.utils.registry import _convert_target_to_string, locate
|
| 9 |
+
|
| 10 |
+
__all__ = ["dump_dataclass", "instantiate"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def dump_dataclass(obj: Any):
|
| 14 |
+
"""
|
| 15 |
+
Dump a dataclass recursively into a dict that can be later instantiated.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
obj: a dataclass object
|
| 19 |
+
|
| 20 |
+
Returns:
|
| 21 |
+
dict
|
| 22 |
+
"""
|
| 23 |
+
assert dataclasses.is_dataclass(obj) and not isinstance(
|
| 24 |
+
obj, type
|
| 25 |
+
), "dump_dataclass() requires an instance of a dataclass."
|
| 26 |
+
ret = {"_target_": _convert_target_to_string(type(obj))}
|
| 27 |
+
for f in dataclasses.fields(obj):
|
| 28 |
+
v = getattr(obj, f.name)
|
| 29 |
+
if dataclasses.is_dataclass(v):
|
| 30 |
+
v = dump_dataclass(v)
|
| 31 |
+
if isinstance(v, (list, tuple)):
|
| 32 |
+
v = [dump_dataclass(x) if dataclasses.is_dataclass(x) else x for x in v]
|
| 33 |
+
ret[f.name] = v
|
| 34 |
+
return ret
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def instantiate(cfg):
|
| 38 |
+
"""
|
| 39 |
+
Recursively instantiate objects defined in dictionaries by
|
| 40 |
+
"_target_" and arguments.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
cfg: a dict-like object with "_target_" that defines the caller, and
|
| 44 |
+
other keys that define the arguments
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
object instantiated by cfg
|
| 48 |
+
"""
|
| 49 |
+
from omegaconf import ListConfig, DictConfig, OmegaConf
|
| 50 |
+
|
| 51 |
+
if isinstance(cfg, ListConfig):
|
| 52 |
+
lst = [instantiate(x) for x in cfg]
|
| 53 |
+
return ListConfig(lst, flags={"allow_objects": True})
|
| 54 |
+
if isinstance(cfg, list):
|
| 55 |
+
# Specialize for list, because many classes take
|
| 56 |
+
# list[objects] as arguments, such as ResNet, DatasetMapper
|
| 57 |
+
return [instantiate(x) for x in cfg]
|
| 58 |
+
|
| 59 |
+
# If input is a DictConfig backed by dataclasses (i.e. omegaconf's structured config),
|
| 60 |
+
# instantiate it to the actual dataclass.
|
| 61 |
+
if isinstance(cfg, DictConfig) and dataclasses.is_dataclass(cfg._metadata.object_type):
|
| 62 |
+
return OmegaConf.to_object(cfg)
|
| 63 |
+
|
| 64 |
+
if isinstance(cfg, abc.Mapping) and "_target_" in cfg:
|
| 65 |
+
# conceptually equivalent to hydra.utils.instantiate(cfg) with _convert_=all,
|
| 66 |
+
# but faster: https://github.com/facebookresearch/hydra/issues/1200
|
| 67 |
+
cfg = {k: instantiate(v) for k, v in cfg.items()}
|
| 68 |
+
cls = cfg.pop("_target_")
|
| 69 |
+
cls = instantiate(cls)
|
| 70 |
+
|
| 71 |
+
if isinstance(cls, str):
|
| 72 |
+
cls_name = cls
|
| 73 |
+
cls = locate(cls_name)
|
| 74 |
+
assert cls is not None, cls_name
|
| 75 |
+
else:
|
| 76 |
+
try:
|
| 77 |
+
cls_name = cls.__module__ + "." + cls.__qualname__
|
| 78 |
+
except Exception:
|
| 79 |
+
# target could be anything, so the above could fail
|
| 80 |
+
cls_name = str(cls)
|
| 81 |
+
assert callable(cls), f"_target_ {cls} does not define a callable object"
|
| 82 |
+
try:
|
| 83 |
+
return cls(**cfg)
|
| 84 |
+
except TypeError:
|
| 85 |
+
logger = logging.getLogger(__name__)
|
| 86 |
+
logger.error(f"Error when instantiating {cls_name}!")
|
| 87 |
+
raise
|
| 88 |
+
return cfg # return as-is if don't know what to do
|
RAVE-main/annotator/oneformer/detectron2/config/lazy.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
|
| 3 |
+
import ast
|
| 4 |
+
import builtins
|
| 5 |
+
import collections.abc as abc
|
| 6 |
+
import importlib
|
| 7 |
+
import inspect
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import uuid
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from copy import deepcopy
|
| 13 |
+
from dataclasses import is_dataclass
|
| 14 |
+
from typing import List, Tuple, Union
|
| 15 |
+
import yaml
|
| 16 |
+
from omegaconf import DictConfig, ListConfig, OmegaConf, SCMode
|
| 17 |
+
|
| 18 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 19 |
+
from annotator.oneformer.detectron2.utils.registry import _convert_target_to_string
|
| 20 |
+
|
| 21 |
+
__all__ = ["LazyCall", "LazyConfig"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class LazyCall:
|
| 25 |
+
"""
|
| 26 |
+
Wrap a callable so that when it's called, the call will not be executed,
|
| 27 |
+
but returns a dict that describes the call.
|
| 28 |
+
|
| 29 |
+
LazyCall object has to be called with only keyword arguments. Positional
|
| 30 |
+
arguments are not yet supported.
|
| 31 |
+
|
| 32 |
+
Examples:
|
| 33 |
+
::
|
| 34 |
+
from annotator.oneformer.detectron2.config import instantiate, LazyCall
|
| 35 |
+
|
| 36 |
+
layer_cfg = LazyCall(nn.Conv2d)(in_channels=32, out_channels=32)
|
| 37 |
+
layer_cfg.out_channels = 64 # can edit it afterwards
|
| 38 |
+
layer = instantiate(layer_cfg)
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, target):
|
| 42 |
+
if not (callable(target) or isinstance(target, (str, abc.Mapping))):
|
| 43 |
+
raise TypeError(
|
| 44 |
+
f"target of LazyCall must be a callable or defines a callable! Got {target}"
|
| 45 |
+
)
|
| 46 |
+
self._target = target
|
| 47 |
+
|
| 48 |
+
def __call__(self, **kwargs):
|
| 49 |
+
if is_dataclass(self._target):
|
| 50 |
+
# omegaconf object cannot hold dataclass type
|
| 51 |
+
# https://github.com/omry/omegaconf/issues/784
|
| 52 |
+
target = _convert_target_to_string(self._target)
|
| 53 |
+
else:
|
| 54 |
+
target = self._target
|
| 55 |
+
kwargs["_target_"] = target
|
| 56 |
+
|
| 57 |
+
return DictConfig(content=kwargs, flags={"allow_objects": True})
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _visit_dict_config(cfg, func):
|
| 61 |
+
"""
|
| 62 |
+
Apply func recursively to all DictConfig in cfg.
|
| 63 |
+
"""
|
| 64 |
+
if isinstance(cfg, DictConfig):
|
| 65 |
+
func(cfg)
|
| 66 |
+
for v in cfg.values():
|
| 67 |
+
_visit_dict_config(v, func)
|
| 68 |
+
elif isinstance(cfg, ListConfig):
|
| 69 |
+
for v in cfg:
|
| 70 |
+
_visit_dict_config(v, func)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _validate_py_syntax(filename):
|
| 74 |
+
# see also https://github.com/open-mmlab/mmcv/blob/master/mmcv/utils/config.py
|
| 75 |
+
with PathManager.open(filename, "r") as f:
|
| 76 |
+
content = f.read()
|
| 77 |
+
try:
|
| 78 |
+
ast.parse(content)
|
| 79 |
+
except SyntaxError as e:
|
| 80 |
+
raise SyntaxError(f"Config file {filename} has syntax error!") from e
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _cast_to_config(obj):
|
| 84 |
+
# if given a dict, return DictConfig instead
|
| 85 |
+
if isinstance(obj, dict):
|
| 86 |
+
return DictConfig(obj, flags={"allow_objects": True})
|
| 87 |
+
return obj
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
_CFG_PACKAGE_NAME = "detectron2._cfg_loader"
|
| 91 |
+
"""
|
| 92 |
+
A namespace to put all imported config into.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _random_package_name(filename):
|
| 97 |
+
# generate a random package name when loading config files
|
| 98 |
+
return _CFG_PACKAGE_NAME + str(uuid.uuid4())[:4] + "." + os.path.basename(filename)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@contextmanager
|
| 102 |
+
def _patch_import():
|
| 103 |
+
"""
|
| 104 |
+
Enhance relative import statements in config files, so that they:
|
| 105 |
+
1. locate files purely based on relative location, regardless of packages.
|
| 106 |
+
e.g. you can import file without having __init__
|
| 107 |
+
2. do not cache modules globally; modifications of module states has no side effect
|
| 108 |
+
3. support other storage system through PathManager, so config files can be in the cloud
|
| 109 |
+
4. imported dict are turned into omegaconf.DictConfig automatically
|
| 110 |
+
"""
|
| 111 |
+
old_import = builtins.__import__
|
| 112 |
+
|
| 113 |
+
def find_relative_file(original_file, relative_import_path, level):
|
| 114 |
+
# NOTE: "from . import x" is not handled. Because then it's unclear
|
| 115 |
+
# if such import should produce `x` as a python module or DictConfig.
|
| 116 |
+
# This can be discussed further if needed.
|
| 117 |
+
relative_import_err = """
|
| 118 |
+
Relative import of directories is not allowed within config files.
|
| 119 |
+
Within a config file, relative import can only import other config files.
|
| 120 |
+
""".replace(
|
| 121 |
+
"\n", " "
|
| 122 |
+
)
|
| 123 |
+
if not len(relative_import_path):
|
| 124 |
+
raise ImportError(relative_import_err)
|
| 125 |
+
|
| 126 |
+
cur_file = os.path.dirname(original_file)
|
| 127 |
+
for _ in range(level - 1):
|
| 128 |
+
cur_file = os.path.dirname(cur_file)
|
| 129 |
+
cur_name = relative_import_path.lstrip(".")
|
| 130 |
+
for part in cur_name.split("."):
|
| 131 |
+
cur_file = os.path.join(cur_file, part)
|
| 132 |
+
if not cur_file.endswith(".py"):
|
| 133 |
+
cur_file += ".py"
|
| 134 |
+
if not PathManager.isfile(cur_file):
|
| 135 |
+
cur_file_no_suffix = cur_file[: -len(".py")]
|
| 136 |
+
if PathManager.isdir(cur_file_no_suffix):
|
| 137 |
+
raise ImportError(f"Cannot import from {cur_file_no_suffix}." + relative_import_err)
|
| 138 |
+
else:
|
| 139 |
+
raise ImportError(
|
| 140 |
+
f"Cannot import name {relative_import_path} from "
|
| 141 |
+
f"{original_file}: {cur_file} does not exist."
|
| 142 |
+
)
|
| 143 |
+
return cur_file
|
| 144 |
+
|
| 145 |
+
def new_import(name, globals=None, locals=None, fromlist=(), level=0):
|
| 146 |
+
if (
|
| 147 |
+
# Only deal with relative imports inside config files
|
| 148 |
+
level != 0
|
| 149 |
+
and globals is not None
|
| 150 |
+
and (globals.get("__package__", "") or "").startswith(_CFG_PACKAGE_NAME)
|
| 151 |
+
):
|
| 152 |
+
cur_file = find_relative_file(globals["__file__"], name, level)
|
| 153 |
+
_validate_py_syntax(cur_file)
|
| 154 |
+
spec = importlib.machinery.ModuleSpec(
|
| 155 |
+
_random_package_name(cur_file), None, origin=cur_file
|
| 156 |
+
)
|
| 157 |
+
module = importlib.util.module_from_spec(spec)
|
| 158 |
+
module.__file__ = cur_file
|
| 159 |
+
with PathManager.open(cur_file) as f:
|
| 160 |
+
content = f.read()
|
| 161 |
+
exec(compile(content, cur_file, "exec"), module.__dict__)
|
| 162 |
+
for name in fromlist: # turn imported dict into DictConfig automatically
|
| 163 |
+
val = _cast_to_config(module.__dict__[name])
|
| 164 |
+
module.__dict__[name] = val
|
| 165 |
+
return module
|
| 166 |
+
return old_import(name, globals, locals, fromlist=fromlist, level=level)
|
| 167 |
+
|
| 168 |
+
builtins.__import__ = new_import
|
| 169 |
+
yield new_import
|
| 170 |
+
builtins.__import__ = old_import
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class LazyConfig:
|
| 174 |
+
"""
|
| 175 |
+
Provide methods to save, load, and overrides an omegaconf config object
|
| 176 |
+
which may contain definition of lazily-constructed objects.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def load_rel(filename: str, keys: Union[None, str, Tuple[str, ...]] = None):
|
| 181 |
+
"""
|
| 182 |
+
Similar to :meth:`load()`, but load path relative to the caller's
|
| 183 |
+
source file.
|
| 184 |
+
|
| 185 |
+
This has the same functionality as a relative import, except that this method
|
| 186 |
+
accepts filename as a string, so more characters are allowed in the filename.
|
| 187 |
+
"""
|
| 188 |
+
caller_frame = inspect.stack()[1]
|
| 189 |
+
caller_fname = caller_frame[0].f_code.co_filename
|
| 190 |
+
assert caller_fname != "<string>", "load_rel Unable to find caller"
|
| 191 |
+
caller_dir = os.path.dirname(caller_fname)
|
| 192 |
+
filename = os.path.join(caller_dir, filename)
|
| 193 |
+
return LazyConfig.load(filename, keys)
|
| 194 |
+
|
| 195 |
+
@staticmethod
|
| 196 |
+
def load(filename: str, keys: Union[None, str, Tuple[str, ...]] = None):
|
| 197 |
+
"""
|
| 198 |
+
Load a config file.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
filename: absolute path or relative path w.r.t. the current working directory
|
| 202 |
+
keys: keys to load and return. If not given, return all keys
|
| 203 |
+
(whose values are config objects) in a dict.
|
| 204 |
+
"""
|
| 205 |
+
has_keys = keys is not None
|
| 206 |
+
filename = filename.replace("/./", "/") # redundant
|
| 207 |
+
if os.path.splitext(filename)[1] not in [".py", ".yaml", ".yml"]:
|
| 208 |
+
raise ValueError(f"Config file {filename} has to be a python or yaml file.")
|
| 209 |
+
if filename.endswith(".py"):
|
| 210 |
+
_validate_py_syntax(filename)
|
| 211 |
+
|
| 212 |
+
with _patch_import():
|
| 213 |
+
# Record the filename
|
| 214 |
+
module_namespace = {
|
| 215 |
+
"__file__": filename,
|
| 216 |
+
"__package__": _random_package_name(filename),
|
| 217 |
+
}
|
| 218 |
+
with PathManager.open(filename) as f:
|
| 219 |
+
content = f.read()
|
| 220 |
+
# Compile first with filename to:
|
| 221 |
+
# 1. make filename appears in stacktrace
|
| 222 |
+
# 2. make load_rel able to find its parent's (possibly remote) location
|
| 223 |
+
exec(compile(content, filename, "exec"), module_namespace)
|
| 224 |
+
|
| 225 |
+
ret = module_namespace
|
| 226 |
+
else:
|
| 227 |
+
with PathManager.open(filename) as f:
|
| 228 |
+
obj = yaml.unsafe_load(f)
|
| 229 |
+
ret = OmegaConf.create(obj, flags={"allow_objects": True})
|
| 230 |
+
|
| 231 |
+
if has_keys:
|
| 232 |
+
if isinstance(keys, str):
|
| 233 |
+
return _cast_to_config(ret[keys])
|
| 234 |
+
else:
|
| 235 |
+
return tuple(_cast_to_config(ret[a]) for a in keys)
|
| 236 |
+
else:
|
| 237 |
+
if filename.endswith(".py"):
|
| 238 |
+
# when not specified, only load those that are config objects
|
| 239 |
+
ret = DictConfig(
|
| 240 |
+
{
|
| 241 |
+
name: _cast_to_config(value)
|
| 242 |
+
for name, value in ret.items()
|
| 243 |
+
if isinstance(value, (DictConfig, ListConfig, dict))
|
| 244 |
+
and not name.startswith("_")
|
| 245 |
+
},
|
| 246 |
+
flags={"allow_objects": True},
|
| 247 |
+
)
|
| 248 |
+
return ret
|
| 249 |
+
|
| 250 |
+
@staticmethod
|
| 251 |
+
def save(cfg, filename: str):
|
| 252 |
+
"""
|
| 253 |
+
Save a config object to a yaml file.
|
| 254 |
+
Note that when the config dictionary contains complex objects (e.g. lambda),
|
| 255 |
+
it can't be saved to yaml. In that case we will print an error and
|
| 256 |
+
attempt to save to a pkl file instead.
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
cfg: an omegaconf config object
|
| 260 |
+
filename: yaml file name to save the config file
|
| 261 |
+
"""
|
| 262 |
+
logger = logging.getLogger(__name__)
|
| 263 |
+
try:
|
| 264 |
+
cfg = deepcopy(cfg)
|
| 265 |
+
except Exception:
|
| 266 |
+
pass
|
| 267 |
+
else:
|
| 268 |
+
# if it's deep-copyable, then...
|
| 269 |
+
def _replace_type_by_name(x):
|
| 270 |
+
if "_target_" in x and callable(x._target_):
|
| 271 |
+
try:
|
| 272 |
+
x._target_ = _convert_target_to_string(x._target_)
|
| 273 |
+
except AttributeError:
|
| 274 |
+
pass
|
| 275 |
+
|
| 276 |
+
# not necessary, but makes yaml looks nicer
|
| 277 |
+
_visit_dict_config(cfg, _replace_type_by_name)
|
| 278 |
+
|
| 279 |
+
save_pkl = False
|
| 280 |
+
try:
|
| 281 |
+
dict = OmegaConf.to_container(
|
| 282 |
+
cfg,
|
| 283 |
+
# Do not resolve interpolation when saving, i.e. do not turn ${a} into
|
| 284 |
+
# actual values when saving.
|
| 285 |
+
resolve=False,
|
| 286 |
+
# Save structures (dataclasses) in a format that can be instantiated later.
|
| 287 |
+
# Without this option, the type information of the dataclass will be erased.
|
| 288 |
+
structured_config_mode=SCMode.INSTANTIATE,
|
| 289 |
+
)
|
| 290 |
+
dumped = yaml.dump(dict, default_flow_style=None, allow_unicode=True, width=9999)
|
| 291 |
+
with PathManager.open(filename, "w") as f:
|
| 292 |
+
f.write(dumped)
|
| 293 |
+
|
| 294 |
+
try:
|
| 295 |
+
_ = yaml.unsafe_load(dumped) # test that it is loadable
|
| 296 |
+
except Exception:
|
| 297 |
+
logger.warning(
|
| 298 |
+
"The config contains objects that cannot serialize to a valid yaml. "
|
| 299 |
+
f"{filename} is human-readable but cannot be loaded."
|
| 300 |
+
)
|
| 301 |
+
save_pkl = True
|
| 302 |
+
except Exception:
|
| 303 |
+
logger.exception("Unable to serialize the config to yaml. Error:")
|
| 304 |
+
save_pkl = True
|
| 305 |
+
|
| 306 |
+
if save_pkl:
|
| 307 |
+
new_filename = filename + ".pkl"
|
| 308 |
+
# try:
|
| 309 |
+
# # retry by pickle
|
| 310 |
+
# with PathManager.open(new_filename, "wb") as f:
|
| 311 |
+
# cloudpickle.dump(cfg, f)
|
| 312 |
+
# logger.warning(f"Config is saved using cloudpickle at {new_filename}.")
|
| 313 |
+
# except Exception:
|
| 314 |
+
# pass
|
| 315 |
+
|
| 316 |
+
@staticmethod
|
| 317 |
+
def apply_overrides(cfg, overrides: List[str]):
|
| 318 |
+
"""
|
| 319 |
+
In-place override contents of cfg.
|
| 320 |
+
|
| 321 |
+
Args:
|
| 322 |
+
cfg: an omegaconf config object
|
| 323 |
+
overrides: list of strings in the format of "a=b" to override configs.
|
| 324 |
+
See https://hydra.cc/docs/next/advanced/override_grammar/basic/
|
| 325 |
+
for syntax.
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
the cfg object
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
def safe_update(cfg, key, value):
|
| 332 |
+
parts = key.split(".")
|
| 333 |
+
for idx in range(1, len(parts)):
|
| 334 |
+
prefix = ".".join(parts[:idx])
|
| 335 |
+
v = OmegaConf.select(cfg, prefix, default=None)
|
| 336 |
+
if v is None:
|
| 337 |
+
break
|
| 338 |
+
if not OmegaConf.is_config(v):
|
| 339 |
+
raise KeyError(
|
| 340 |
+
f"Trying to update key {key}, but {prefix} "
|
| 341 |
+
f"is not a config, but has type {type(v)}."
|
| 342 |
+
)
|
| 343 |
+
OmegaConf.update(cfg, key, value, merge=True)
|
| 344 |
+
|
| 345 |
+
try:
|
| 346 |
+
from hydra.core.override_parser.overrides_parser import OverridesParser
|
| 347 |
+
|
| 348 |
+
has_hydra = True
|
| 349 |
+
except ImportError:
|
| 350 |
+
has_hydra = False
|
| 351 |
+
|
| 352 |
+
if has_hydra:
|
| 353 |
+
parser = OverridesParser.create()
|
| 354 |
+
overrides = parser.parse_overrides(overrides)
|
| 355 |
+
for o in overrides:
|
| 356 |
+
key = o.key_or_group
|
| 357 |
+
value = o.value()
|
| 358 |
+
if o.is_delete():
|
| 359 |
+
# TODO support this
|
| 360 |
+
raise NotImplementedError("deletion is not yet a supported override")
|
| 361 |
+
safe_update(cfg, key, value)
|
| 362 |
+
else:
|
| 363 |
+
# Fallback. Does not support all the features and error checking like hydra.
|
| 364 |
+
for o in overrides:
|
| 365 |
+
key, value = o.split("=")
|
| 366 |
+
try:
|
| 367 |
+
value = eval(value, {})
|
| 368 |
+
except NameError:
|
| 369 |
+
pass
|
| 370 |
+
safe_update(cfg, key, value)
|
| 371 |
+
return cfg
|
| 372 |
+
|
| 373 |
+
# @staticmethod
|
| 374 |
+
# def to_py(cfg, prefix: str = "cfg."):
|
| 375 |
+
# """
|
| 376 |
+
# Try to convert a config object into Python-like psuedo code.
|
| 377 |
+
#
|
| 378 |
+
# Note that perfect conversion is not always possible. So the returned
|
| 379 |
+
# results are mainly meant to be human-readable, and not meant to be executed.
|
| 380 |
+
#
|
| 381 |
+
# Args:
|
| 382 |
+
# cfg: an omegaconf config object
|
| 383 |
+
# prefix: root name for the resulting code (default: "cfg.")
|
| 384 |
+
#
|
| 385 |
+
#
|
| 386 |
+
# Returns:
|
| 387 |
+
# str of formatted Python code
|
| 388 |
+
# """
|
| 389 |
+
# import black
|
| 390 |
+
#
|
| 391 |
+
# cfg = OmegaConf.to_container(cfg, resolve=True)
|
| 392 |
+
#
|
| 393 |
+
# def _to_str(obj, prefix=None, inside_call=False):
|
| 394 |
+
# if prefix is None:
|
| 395 |
+
# prefix = []
|
| 396 |
+
# if isinstance(obj, abc.Mapping) and "_target_" in obj:
|
| 397 |
+
# # Dict representing a function call
|
| 398 |
+
# target = _convert_target_to_string(obj.pop("_target_"))
|
| 399 |
+
# args = []
|
| 400 |
+
# for k, v in sorted(obj.items()):
|
| 401 |
+
# args.append(f"{k}={_to_str(v, inside_call=True)}")
|
| 402 |
+
# args = ", ".join(args)
|
| 403 |
+
# call = f"{target}({args})"
|
| 404 |
+
# return "".join(prefix) + call
|
| 405 |
+
# elif isinstance(obj, abc.Mapping) and not inside_call:
|
| 406 |
+
# # Dict that is not inside a call is a list of top-level config objects that we
|
| 407 |
+
# # render as one object per line with dot separated prefixes
|
| 408 |
+
# key_list = []
|
| 409 |
+
# for k, v in sorted(obj.items()):
|
| 410 |
+
# if isinstance(v, abc.Mapping) and "_target_" not in v:
|
| 411 |
+
# key_list.append(_to_str(v, prefix=prefix + [k + "."]))
|
| 412 |
+
# else:
|
| 413 |
+
# key = "".join(prefix) + k
|
| 414 |
+
# key_list.append(f"{key}={_to_str(v)}")
|
| 415 |
+
# return "\n".join(key_list)
|
| 416 |
+
# elif isinstance(obj, abc.Mapping):
|
| 417 |
+
# # Dict that is inside a call is rendered as a regular dict
|
| 418 |
+
# return (
|
| 419 |
+
# "{"
|
| 420 |
+
# + ",".join(
|
| 421 |
+
# f"{repr(k)}: {_to_str(v, inside_call=inside_call)}"
|
| 422 |
+
# for k, v in sorted(obj.items())
|
| 423 |
+
# )
|
| 424 |
+
# + "}"
|
| 425 |
+
# )
|
| 426 |
+
# elif isinstance(obj, list):
|
| 427 |
+
# return "[" + ",".join(_to_str(x, inside_call=inside_call) for x in obj) + "]"
|
| 428 |
+
# else:
|
| 429 |
+
# return repr(obj)
|
| 430 |
+
#
|
| 431 |
+
# py_str = _to_str(cfg, prefix=[prefix])
|
| 432 |
+
# try:
|
| 433 |
+
# return black.format_str(py_str, mode=black.Mode())
|
| 434 |
+
# except black.InvalidInput:
|
| 435 |
+
# return py_str
|
RAVE-main/annotator/oneformer/detectron2/engine/defaults.py
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
This file contains components with some default boilerplate logic user may need
|
| 6 |
+
in training / testing. They will not work for everyone, but many users may find them useful.
|
| 7 |
+
|
| 8 |
+
The behavior of functions/classes in this file is subject to change,
|
| 9 |
+
since they are meant to represent the "common default behavior" people need in their projects.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import logging
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import weakref
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Optional
|
| 19 |
+
import torch
|
| 20 |
+
from fvcore.nn.precise_bn import get_bn_modules
|
| 21 |
+
from omegaconf import OmegaConf
|
| 22 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 23 |
+
|
| 24 |
+
import annotator.oneformer.detectron2.data.transforms as T
|
| 25 |
+
from annotator.oneformer.detectron2.checkpoint import DetectionCheckpointer
|
| 26 |
+
from annotator.oneformer.detectron2.config import CfgNode, LazyConfig
|
| 27 |
+
from annotator.oneformer.detectron2.data import (
|
| 28 |
+
MetadataCatalog,
|
| 29 |
+
build_detection_test_loader,
|
| 30 |
+
build_detection_train_loader,
|
| 31 |
+
)
|
| 32 |
+
from annotator.oneformer.detectron2.evaluation import (
|
| 33 |
+
DatasetEvaluator,
|
| 34 |
+
inference_on_dataset,
|
| 35 |
+
print_csv_format,
|
| 36 |
+
verify_results,
|
| 37 |
+
)
|
| 38 |
+
from annotator.oneformer.detectron2.modeling import build_model
|
| 39 |
+
from annotator.oneformer.detectron2.solver import build_lr_scheduler, build_optimizer
|
| 40 |
+
from annotator.oneformer.detectron2.utils import comm
|
| 41 |
+
from annotator.oneformer.detectron2.utils.collect_env import collect_env_info
|
| 42 |
+
from annotator.oneformer.detectron2.utils.env import seed_all_rng
|
| 43 |
+
from annotator.oneformer.detectron2.utils.events import CommonMetricPrinter, JSONWriter, TensorboardXWriter
|
| 44 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 45 |
+
from annotator.oneformer.detectron2.utils.logger import setup_logger
|
| 46 |
+
|
| 47 |
+
from . import hooks
|
| 48 |
+
from .train_loop import AMPTrainer, SimpleTrainer, TrainerBase
|
| 49 |
+
|
| 50 |
+
__all__ = [
|
| 51 |
+
"create_ddp_model",
|
| 52 |
+
"default_argument_parser",
|
| 53 |
+
"default_setup",
|
| 54 |
+
"default_writers",
|
| 55 |
+
"DefaultPredictor",
|
| 56 |
+
"DefaultTrainer",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def create_ddp_model(model, *, fp16_compression=False, **kwargs):
|
| 61 |
+
"""
|
| 62 |
+
Create a DistributedDataParallel model if there are >1 processes.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
model: a torch.nn.Module
|
| 66 |
+
fp16_compression: add fp16 compression hooks to the ddp object.
|
| 67 |
+
See more at https://pytorch.org/docs/stable/ddp_comm_hooks.html#torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook
|
| 68 |
+
kwargs: other arguments of :module:`torch.nn.parallel.DistributedDataParallel`.
|
| 69 |
+
""" # noqa
|
| 70 |
+
if comm.get_world_size() == 1:
|
| 71 |
+
return model
|
| 72 |
+
if "device_ids" not in kwargs:
|
| 73 |
+
kwargs["device_ids"] = [comm.get_local_rank()]
|
| 74 |
+
ddp = DistributedDataParallel(model, **kwargs)
|
| 75 |
+
if fp16_compression:
|
| 76 |
+
from torch.distributed.algorithms.ddp_comm_hooks import default as comm_hooks
|
| 77 |
+
|
| 78 |
+
ddp.register_comm_hook(state=None, hook=comm_hooks.fp16_compress_hook)
|
| 79 |
+
return ddp
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def default_argument_parser(epilog=None):
|
| 83 |
+
"""
|
| 84 |
+
Create a parser with some common arguments used by detectron2 users.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
epilog (str): epilog passed to ArgumentParser describing the usage.
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
argparse.ArgumentParser:
|
| 91 |
+
"""
|
| 92 |
+
parser = argparse.ArgumentParser(
|
| 93 |
+
epilog=epilog
|
| 94 |
+
or f"""
|
| 95 |
+
Examples:
|
| 96 |
+
|
| 97 |
+
Run on single machine:
|
| 98 |
+
$ {sys.argv[0]} --num-gpus 8 --config-file cfg.yaml
|
| 99 |
+
|
| 100 |
+
Change some config options:
|
| 101 |
+
$ {sys.argv[0]} --config-file cfg.yaml MODEL.WEIGHTS /path/to/weight.pth SOLVER.BASE_LR 0.001
|
| 102 |
+
|
| 103 |
+
Run on multiple machines:
|
| 104 |
+
(machine0)$ {sys.argv[0]} --machine-rank 0 --num-machines 2 --dist-url <URL> [--other-flags]
|
| 105 |
+
(machine1)$ {sys.argv[0]} --machine-rank 1 --num-machines 2 --dist-url <URL> [--other-flags]
|
| 106 |
+
""",
|
| 107 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument("--config-file", default="", metavar="FILE", help="path to config file")
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--resume",
|
| 112 |
+
action="store_true",
|
| 113 |
+
help="Whether to attempt to resume from the checkpoint directory. "
|
| 114 |
+
"See documentation of `DefaultTrainer.resume_or_load()` for what it means.",
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument("--eval-only", action="store_true", help="perform evaluation only")
|
| 117 |
+
parser.add_argument("--num-gpus", type=int, default=1, help="number of gpus *per machine*")
|
| 118 |
+
parser.add_argument("--num-machines", type=int, default=1, help="total number of machines")
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--machine-rank", type=int, default=0, help="the rank of this machine (unique per machine)"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# PyTorch still may leave orphan processes in multi-gpu training.
|
| 124 |
+
# Therefore we use a deterministic way to obtain port,
|
| 125 |
+
# so that users are aware of orphan processes by seeing the port occupied.
|
| 126 |
+
port = 2**15 + 2**14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2**14
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--dist-url",
|
| 129 |
+
default="tcp://127.0.0.1:{}".format(port),
|
| 130 |
+
help="initialization URL for pytorch distributed backend. See "
|
| 131 |
+
"https://pytorch.org/docs/stable/distributed.html for details.",
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"opts",
|
| 135 |
+
help="""
|
| 136 |
+
Modify config options at the end of the command. For Yacs configs, use
|
| 137 |
+
space-separated "PATH.KEY VALUE" pairs.
|
| 138 |
+
For python-based LazyConfig, use "path.key=value".
|
| 139 |
+
""".strip(),
|
| 140 |
+
default=None,
|
| 141 |
+
nargs=argparse.REMAINDER,
|
| 142 |
+
)
|
| 143 |
+
return parser
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _try_get_key(cfg, *keys, default=None):
|
| 147 |
+
"""
|
| 148 |
+
Try select keys from cfg until the first key that exists. Otherwise return default.
|
| 149 |
+
"""
|
| 150 |
+
if isinstance(cfg, CfgNode):
|
| 151 |
+
cfg = OmegaConf.create(cfg.dump())
|
| 152 |
+
for k in keys:
|
| 153 |
+
none = object()
|
| 154 |
+
p = OmegaConf.select(cfg, k, default=none)
|
| 155 |
+
if p is not none:
|
| 156 |
+
return p
|
| 157 |
+
return default
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _highlight(code, filename):
|
| 161 |
+
try:
|
| 162 |
+
import pygments
|
| 163 |
+
except ImportError:
|
| 164 |
+
return code
|
| 165 |
+
|
| 166 |
+
from pygments.lexers import Python3Lexer, YamlLexer
|
| 167 |
+
from pygments.formatters import Terminal256Formatter
|
| 168 |
+
|
| 169 |
+
lexer = Python3Lexer() if filename.endswith(".py") else YamlLexer()
|
| 170 |
+
code = pygments.highlight(code, lexer, Terminal256Formatter(style="monokai"))
|
| 171 |
+
return code
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def default_setup(cfg, args):
|
| 175 |
+
"""
|
| 176 |
+
Perform some basic common setups at the beginning of a job, including:
|
| 177 |
+
|
| 178 |
+
1. Set up the detectron2 logger
|
| 179 |
+
2. Log basic information about environment, cmdline arguments, and config
|
| 180 |
+
3. Backup the config to the output directory
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
cfg (CfgNode or omegaconf.DictConfig): the full config to be used
|
| 184 |
+
args (argparse.NameSpace): the command line arguments to be logged
|
| 185 |
+
"""
|
| 186 |
+
output_dir = _try_get_key(cfg, "OUTPUT_DIR", "output_dir", "train.output_dir")
|
| 187 |
+
if comm.is_main_process() and output_dir:
|
| 188 |
+
PathManager.mkdirs(output_dir)
|
| 189 |
+
|
| 190 |
+
rank = comm.get_rank()
|
| 191 |
+
setup_logger(output_dir, distributed_rank=rank, name="fvcore")
|
| 192 |
+
logger = setup_logger(output_dir, distributed_rank=rank)
|
| 193 |
+
|
| 194 |
+
logger.info("Rank of current process: {}. World size: {}".format(rank, comm.get_world_size()))
|
| 195 |
+
logger.info("Environment info:\n" + collect_env_info())
|
| 196 |
+
|
| 197 |
+
logger.info("Command line arguments: " + str(args))
|
| 198 |
+
if hasattr(args, "config_file") and args.config_file != "":
|
| 199 |
+
logger.info(
|
| 200 |
+
"Contents of args.config_file={}:\n{}".format(
|
| 201 |
+
args.config_file,
|
| 202 |
+
_highlight(PathManager.open(args.config_file, "r").read(), args.config_file),
|
| 203 |
+
)
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if comm.is_main_process() and output_dir:
|
| 207 |
+
# Note: some of our scripts may expect the existence of
|
| 208 |
+
# config.yaml in output directory
|
| 209 |
+
path = os.path.join(output_dir, "config.yaml")
|
| 210 |
+
if isinstance(cfg, CfgNode):
|
| 211 |
+
logger.info("Running with full config:\n{}".format(_highlight(cfg.dump(), ".yaml")))
|
| 212 |
+
with PathManager.open(path, "w") as f:
|
| 213 |
+
f.write(cfg.dump())
|
| 214 |
+
else:
|
| 215 |
+
LazyConfig.save(cfg, path)
|
| 216 |
+
logger.info("Full config saved to {}".format(path))
|
| 217 |
+
|
| 218 |
+
# make sure each worker has a different, yet deterministic seed if specified
|
| 219 |
+
seed = _try_get_key(cfg, "SEED", "train.seed", default=-1)
|
| 220 |
+
seed_all_rng(None if seed < 0 else seed + rank)
|
| 221 |
+
|
| 222 |
+
# cudnn benchmark has large overhead. It shouldn't be used considering the small size of
|
| 223 |
+
# typical validation set.
|
| 224 |
+
if not (hasattr(args, "eval_only") and args.eval_only):
|
| 225 |
+
torch.backends.cudnn.benchmark = _try_get_key(
|
| 226 |
+
cfg, "CUDNN_BENCHMARK", "train.cudnn_benchmark", default=False
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def default_writers(output_dir: str, max_iter: Optional[int] = None):
|
| 231 |
+
"""
|
| 232 |
+
Build a list of :class:`EventWriter` to be used.
|
| 233 |
+
It now consists of a :class:`CommonMetricPrinter`,
|
| 234 |
+
:class:`TensorboardXWriter` and :class:`JSONWriter`.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
output_dir: directory to store JSON metrics and tensorboard events
|
| 238 |
+
max_iter: the total number of iterations
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
list[EventWriter]: a list of :class:`EventWriter` objects.
|
| 242 |
+
"""
|
| 243 |
+
PathManager.mkdirs(output_dir)
|
| 244 |
+
return [
|
| 245 |
+
# It may not always print what you want to see, since it prints "common" metrics only.
|
| 246 |
+
CommonMetricPrinter(max_iter),
|
| 247 |
+
JSONWriter(os.path.join(output_dir, "metrics.json")),
|
| 248 |
+
TensorboardXWriter(output_dir),
|
| 249 |
+
]
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class DefaultPredictor:
|
| 253 |
+
"""
|
| 254 |
+
Create a simple end-to-end predictor with the given config that runs on
|
| 255 |
+
single device for a single input image.
|
| 256 |
+
|
| 257 |
+
Compared to using the model directly, this class does the following additions:
|
| 258 |
+
|
| 259 |
+
1. Load checkpoint from `cfg.MODEL.WEIGHTS`.
|
| 260 |
+
2. Always take BGR image as the input and apply conversion defined by `cfg.INPUT.FORMAT`.
|
| 261 |
+
3. Apply resizing defined by `cfg.INPUT.{MIN,MAX}_SIZE_TEST`.
|
| 262 |
+
4. Take one input image and produce a single output, instead of a batch.
|
| 263 |
+
|
| 264 |
+
This is meant for simple demo purposes, so it does the above steps automatically.
|
| 265 |
+
This is not meant for benchmarks or running complicated inference logic.
|
| 266 |
+
If you'd like to do anything more complicated, please refer to its source code as
|
| 267 |
+
examples to build and use the model manually.
|
| 268 |
+
|
| 269 |
+
Attributes:
|
| 270 |
+
metadata (Metadata): the metadata of the underlying dataset, obtained from
|
| 271 |
+
cfg.DATASETS.TEST.
|
| 272 |
+
|
| 273 |
+
Examples:
|
| 274 |
+
::
|
| 275 |
+
pred = DefaultPredictor(cfg)
|
| 276 |
+
inputs = cv2.imread("input.jpg")
|
| 277 |
+
outputs = pred(inputs)
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
def __init__(self, cfg):
|
| 281 |
+
self.cfg = cfg.clone() # cfg can be modified by model
|
| 282 |
+
self.model = build_model(self.cfg)
|
| 283 |
+
self.model.eval()
|
| 284 |
+
if len(cfg.DATASETS.TEST):
|
| 285 |
+
self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0])
|
| 286 |
+
|
| 287 |
+
checkpointer = DetectionCheckpointer(self.model)
|
| 288 |
+
checkpointer.load(cfg.MODEL.WEIGHTS)
|
| 289 |
+
|
| 290 |
+
self.aug = T.ResizeShortestEdge(
|
| 291 |
+
[cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST], cfg.INPUT.MAX_SIZE_TEST
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
self.input_format = cfg.INPUT.FORMAT
|
| 295 |
+
assert self.input_format in ["RGB", "BGR"], self.input_format
|
| 296 |
+
|
| 297 |
+
def __call__(self, original_image):
|
| 298 |
+
"""
|
| 299 |
+
Args:
|
| 300 |
+
original_image (np.ndarray): an image of shape (H, W, C) (in BGR order).
|
| 301 |
+
|
| 302 |
+
Returns:
|
| 303 |
+
predictions (dict):
|
| 304 |
+
the output of the model for one image only.
|
| 305 |
+
See :doc:`/tutorials/models` for details about the format.
|
| 306 |
+
"""
|
| 307 |
+
with torch.no_grad(): # https://github.com/sphinx-doc/sphinx/issues/4258
|
| 308 |
+
# Apply pre-processing to image.
|
| 309 |
+
if self.input_format == "RGB":
|
| 310 |
+
# whether the model expects BGR inputs or RGB
|
| 311 |
+
original_image = original_image[:, :, ::-1]
|
| 312 |
+
height, width = original_image.shape[:2]
|
| 313 |
+
image = self.aug.get_transform(original_image).apply_image(original_image)
|
| 314 |
+
image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
|
| 315 |
+
|
| 316 |
+
inputs = {"image": image, "height": height, "width": width}
|
| 317 |
+
predictions = self.model([inputs])[0]
|
| 318 |
+
return predictions
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class DefaultTrainer(TrainerBase):
|
| 322 |
+
"""
|
| 323 |
+
A trainer with default training logic. It does the following:
|
| 324 |
+
|
| 325 |
+
1. Create a :class:`SimpleTrainer` using model, optimizer, dataloader
|
| 326 |
+
defined by the given config. Create a LR scheduler defined by the config.
|
| 327 |
+
2. Load the last checkpoint or `cfg.MODEL.WEIGHTS`, if exists, when
|
| 328 |
+
`resume_or_load` is called.
|
| 329 |
+
3. Register a few common hooks defined by the config.
|
| 330 |
+
|
| 331 |
+
It is created to simplify the **standard model training workflow** and reduce code boilerplate
|
| 332 |
+
for users who only need the standard training workflow, with standard features.
|
| 333 |
+
It means this class makes *many assumptions* about your training logic that
|
| 334 |
+
may easily become invalid in a new research. In fact, any assumptions beyond those made in the
|
| 335 |
+
:class:`SimpleTrainer` are too much for research.
|
| 336 |
+
|
| 337 |
+
The code of this class has been annotated about restrictive assumptions it makes.
|
| 338 |
+
When they do not work for you, you're encouraged to:
|
| 339 |
+
|
| 340 |
+
1. Overwrite methods of this class, OR:
|
| 341 |
+
2. Use :class:`SimpleTrainer`, which only does minimal SGD training and
|
| 342 |
+
nothing else. You can then add your own hooks if needed. OR:
|
| 343 |
+
3. Write your own training loop similar to `tools/plain_train_net.py`.
|
| 344 |
+
|
| 345 |
+
See the :doc:`/tutorials/training` tutorials for more details.
|
| 346 |
+
|
| 347 |
+
Note that the behavior of this class, like other functions/classes in
|
| 348 |
+
this file, is not stable, since it is meant to represent the "common default behavior".
|
| 349 |
+
It is only guaranteed to work well with the standard models and training workflow in detectron2.
|
| 350 |
+
To obtain more stable behavior, write your own training logic with other public APIs.
|
| 351 |
+
|
| 352 |
+
Examples:
|
| 353 |
+
::
|
| 354 |
+
trainer = DefaultTrainer(cfg)
|
| 355 |
+
trainer.resume_or_load() # load last checkpoint or MODEL.WEIGHTS
|
| 356 |
+
trainer.train()
|
| 357 |
+
|
| 358 |
+
Attributes:
|
| 359 |
+
scheduler:
|
| 360 |
+
checkpointer (DetectionCheckpointer):
|
| 361 |
+
cfg (CfgNode):
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
def __init__(self, cfg):
|
| 365 |
+
"""
|
| 366 |
+
Args:
|
| 367 |
+
cfg (CfgNode):
|
| 368 |
+
"""
|
| 369 |
+
super().__init__()
|
| 370 |
+
logger = logging.getLogger("detectron2")
|
| 371 |
+
if not logger.isEnabledFor(logging.INFO): # setup_logger is not called for d2
|
| 372 |
+
setup_logger()
|
| 373 |
+
cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size())
|
| 374 |
+
|
| 375 |
+
# Assume these objects must be constructed in this order.
|
| 376 |
+
model = self.build_model(cfg)
|
| 377 |
+
optimizer = self.build_optimizer(cfg, model)
|
| 378 |
+
data_loader = self.build_train_loader(cfg)
|
| 379 |
+
|
| 380 |
+
model = create_ddp_model(model, broadcast_buffers=False)
|
| 381 |
+
self._trainer = (AMPTrainer if cfg.SOLVER.AMP.ENABLED else SimpleTrainer)(
|
| 382 |
+
model, data_loader, optimizer
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
self.scheduler = self.build_lr_scheduler(cfg, optimizer)
|
| 386 |
+
self.checkpointer = DetectionCheckpointer(
|
| 387 |
+
# Assume you want to save checkpoints together with logs/statistics
|
| 388 |
+
model,
|
| 389 |
+
cfg.OUTPUT_DIR,
|
| 390 |
+
trainer=weakref.proxy(self),
|
| 391 |
+
)
|
| 392 |
+
self.start_iter = 0
|
| 393 |
+
self.max_iter = cfg.SOLVER.MAX_ITER
|
| 394 |
+
self.cfg = cfg
|
| 395 |
+
|
| 396 |
+
self.register_hooks(self.build_hooks())
|
| 397 |
+
|
| 398 |
+
def resume_or_load(self, resume=True):
|
| 399 |
+
"""
|
| 400 |
+
If `resume==True` and `cfg.OUTPUT_DIR` contains the last checkpoint (defined by
|
| 401 |
+
a `last_checkpoint` file), resume from the file. Resuming means loading all
|
| 402 |
+
available states (eg. optimizer and scheduler) and update iteration counter
|
| 403 |
+
from the checkpoint. ``cfg.MODEL.WEIGHTS`` will not be used.
|
| 404 |
+
|
| 405 |
+
Otherwise, this is considered as an independent training. The method will load model
|
| 406 |
+
weights from the file `cfg.MODEL.WEIGHTS` (but will not load other states) and start
|
| 407 |
+
from iteration 0.
|
| 408 |
+
|
| 409 |
+
Args:
|
| 410 |
+
resume (bool): whether to do resume or not
|
| 411 |
+
"""
|
| 412 |
+
self.checkpointer.resume_or_load(self.cfg.MODEL.WEIGHTS, resume=resume)
|
| 413 |
+
if resume and self.checkpointer.has_checkpoint():
|
| 414 |
+
# The checkpoint stores the training iteration that just finished, thus we start
|
| 415 |
+
# at the next iteration
|
| 416 |
+
self.start_iter = self.iter + 1
|
| 417 |
+
|
| 418 |
+
def build_hooks(self):
|
| 419 |
+
"""
|
| 420 |
+
Build a list of default hooks, including timing, evaluation,
|
| 421 |
+
checkpointing, lr scheduling, precise BN, writing events.
|
| 422 |
+
|
| 423 |
+
Returns:
|
| 424 |
+
list[HookBase]:
|
| 425 |
+
"""
|
| 426 |
+
cfg = self.cfg.clone()
|
| 427 |
+
cfg.defrost()
|
| 428 |
+
cfg.DATALOADER.NUM_WORKERS = 0 # save some memory and time for PreciseBN
|
| 429 |
+
|
| 430 |
+
ret = [
|
| 431 |
+
hooks.IterationTimer(),
|
| 432 |
+
hooks.LRScheduler(),
|
| 433 |
+
hooks.PreciseBN(
|
| 434 |
+
# Run at the same freq as (but before) evaluation.
|
| 435 |
+
cfg.TEST.EVAL_PERIOD,
|
| 436 |
+
self.model,
|
| 437 |
+
# Build a new data loader to not affect training
|
| 438 |
+
self.build_train_loader(cfg),
|
| 439 |
+
cfg.TEST.PRECISE_BN.NUM_ITER,
|
| 440 |
+
)
|
| 441 |
+
if cfg.TEST.PRECISE_BN.ENABLED and get_bn_modules(self.model)
|
| 442 |
+
else None,
|
| 443 |
+
]
|
| 444 |
+
|
| 445 |
+
# Do PreciseBN before checkpointer, because it updates the model and need to
|
| 446 |
+
# be saved by checkpointer.
|
| 447 |
+
# This is not always the best: if checkpointing has a different frequency,
|
| 448 |
+
# some checkpoints may have more precise statistics than others.
|
| 449 |
+
if comm.is_main_process():
|
| 450 |
+
ret.append(hooks.PeriodicCheckpointer(self.checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD))
|
| 451 |
+
|
| 452 |
+
def test_and_save_results():
|
| 453 |
+
self._last_eval_results = self.test(self.cfg, self.model)
|
| 454 |
+
return self._last_eval_results
|
| 455 |
+
|
| 456 |
+
# Do evaluation after checkpointer, because then if it fails,
|
| 457 |
+
# we can use the saved checkpoint to debug.
|
| 458 |
+
ret.append(hooks.EvalHook(cfg.TEST.EVAL_PERIOD, test_and_save_results))
|
| 459 |
+
|
| 460 |
+
if comm.is_main_process():
|
| 461 |
+
# Here the default print/log frequency of each writer is used.
|
| 462 |
+
# run writers in the end, so that evaluation metrics are written
|
| 463 |
+
ret.append(hooks.PeriodicWriter(self.build_writers(), period=20))
|
| 464 |
+
return ret
|
| 465 |
+
|
| 466 |
+
def build_writers(self):
|
| 467 |
+
"""
|
| 468 |
+
Build a list of writers to be used using :func:`default_writers()`.
|
| 469 |
+
If you'd like a different list of writers, you can overwrite it in
|
| 470 |
+
your trainer.
|
| 471 |
+
|
| 472 |
+
Returns:
|
| 473 |
+
list[EventWriter]: a list of :class:`EventWriter` objects.
|
| 474 |
+
"""
|
| 475 |
+
return default_writers(self.cfg.OUTPUT_DIR, self.max_iter)
|
| 476 |
+
|
| 477 |
+
def train(self):
|
| 478 |
+
"""
|
| 479 |
+
Run training.
|
| 480 |
+
|
| 481 |
+
Returns:
|
| 482 |
+
OrderedDict of results, if evaluation is enabled. Otherwise None.
|
| 483 |
+
"""
|
| 484 |
+
super().train(self.start_iter, self.max_iter)
|
| 485 |
+
if len(self.cfg.TEST.EXPECTED_RESULTS) and comm.is_main_process():
|
| 486 |
+
assert hasattr(
|
| 487 |
+
self, "_last_eval_results"
|
| 488 |
+
), "No evaluation results obtained during training!"
|
| 489 |
+
verify_results(self.cfg, self._last_eval_results)
|
| 490 |
+
return self._last_eval_results
|
| 491 |
+
|
| 492 |
+
def run_step(self):
|
| 493 |
+
self._trainer.iter = self.iter
|
| 494 |
+
self._trainer.run_step()
|
| 495 |
+
|
| 496 |
+
def state_dict(self):
|
| 497 |
+
ret = super().state_dict()
|
| 498 |
+
ret["_trainer"] = self._trainer.state_dict()
|
| 499 |
+
return ret
|
| 500 |
+
|
| 501 |
+
def load_state_dict(self, state_dict):
|
| 502 |
+
super().load_state_dict(state_dict)
|
| 503 |
+
self._trainer.load_state_dict(state_dict["_trainer"])
|
| 504 |
+
|
| 505 |
+
@classmethod
|
| 506 |
+
def build_model(cls, cfg):
|
| 507 |
+
"""
|
| 508 |
+
Returns:
|
| 509 |
+
torch.nn.Module:
|
| 510 |
+
|
| 511 |
+
It now calls :func:`detectron2.modeling.build_model`.
|
| 512 |
+
Overwrite it if you'd like a different model.
|
| 513 |
+
"""
|
| 514 |
+
model = build_model(cfg)
|
| 515 |
+
logger = logging.getLogger(__name__)
|
| 516 |
+
logger.info("Model:\n{}".format(model))
|
| 517 |
+
return model
|
| 518 |
+
|
| 519 |
+
@classmethod
|
| 520 |
+
def build_optimizer(cls, cfg, model):
|
| 521 |
+
"""
|
| 522 |
+
Returns:
|
| 523 |
+
torch.optim.Optimizer:
|
| 524 |
+
|
| 525 |
+
It now calls :func:`detectron2.solver.build_optimizer`.
|
| 526 |
+
Overwrite it if you'd like a different optimizer.
|
| 527 |
+
"""
|
| 528 |
+
return build_optimizer(cfg, model)
|
| 529 |
+
|
| 530 |
+
@classmethod
|
| 531 |
+
def build_lr_scheduler(cls, cfg, optimizer):
|
| 532 |
+
"""
|
| 533 |
+
It now calls :func:`detectron2.solver.build_lr_scheduler`.
|
| 534 |
+
Overwrite it if you'd like a different scheduler.
|
| 535 |
+
"""
|
| 536 |
+
return build_lr_scheduler(cfg, optimizer)
|
| 537 |
+
|
| 538 |
+
@classmethod
|
| 539 |
+
def build_train_loader(cls, cfg):
|
| 540 |
+
"""
|
| 541 |
+
Returns:
|
| 542 |
+
iterable
|
| 543 |
+
|
| 544 |
+
It now calls :func:`detectron2.data.build_detection_train_loader`.
|
| 545 |
+
Overwrite it if you'd like a different data loader.
|
| 546 |
+
"""
|
| 547 |
+
return build_detection_train_loader(cfg)
|
| 548 |
+
|
| 549 |
+
@classmethod
|
| 550 |
+
def build_test_loader(cls, cfg, dataset_name):
|
| 551 |
+
"""
|
| 552 |
+
Returns:
|
| 553 |
+
iterable
|
| 554 |
+
|
| 555 |
+
It now calls :func:`detectron2.data.build_detection_test_loader`.
|
| 556 |
+
Overwrite it if you'd like a different data loader.
|
| 557 |
+
"""
|
| 558 |
+
return build_detection_test_loader(cfg, dataset_name)
|
| 559 |
+
|
| 560 |
+
@classmethod
|
| 561 |
+
def build_evaluator(cls, cfg, dataset_name):
|
| 562 |
+
"""
|
| 563 |
+
Returns:
|
| 564 |
+
DatasetEvaluator or None
|
| 565 |
+
|
| 566 |
+
It is not implemented by default.
|
| 567 |
+
"""
|
| 568 |
+
raise NotImplementedError(
|
| 569 |
+
"""
|
| 570 |
+
If you want DefaultTrainer to automatically run evaluation,
|
| 571 |
+
please implement `build_evaluator()` in subclasses (see train_net.py for example).
|
| 572 |
+
Alternatively, you can call evaluation functions yourself (see Colab balloon tutorial for example).
|
| 573 |
+
"""
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
@classmethod
|
| 577 |
+
def test(cls, cfg, model, evaluators=None):
|
| 578 |
+
"""
|
| 579 |
+
Evaluate the given model. The given model is expected to already contain
|
| 580 |
+
weights to evaluate.
|
| 581 |
+
|
| 582 |
+
Args:
|
| 583 |
+
cfg (CfgNode):
|
| 584 |
+
model (nn.Module):
|
| 585 |
+
evaluators (list[DatasetEvaluator] or None): if None, will call
|
| 586 |
+
:meth:`build_evaluator`. Otherwise, must have the same length as
|
| 587 |
+
``cfg.DATASETS.TEST``.
|
| 588 |
+
|
| 589 |
+
Returns:
|
| 590 |
+
dict: a dict of result metrics
|
| 591 |
+
"""
|
| 592 |
+
logger = logging.getLogger(__name__)
|
| 593 |
+
if isinstance(evaluators, DatasetEvaluator):
|
| 594 |
+
evaluators = [evaluators]
|
| 595 |
+
if evaluators is not None:
|
| 596 |
+
assert len(cfg.DATASETS.TEST) == len(evaluators), "{} != {}".format(
|
| 597 |
+
len(cfg.DATASETS.TEST), len(evaluators)
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
results = OrderedDict()
|
| 601 |
+
for idx, dataset_name in enumerate(cfg.DATASETS.TEST):
|
| 602 |
+
data_loader = cls.build_test_loader(cfg, dataset_name)
|
| 603 |
+
# When evaluators are passed in as arguments,
|
| 604 |
+
# implicitly assume that evaluators can be created before data_loader.
|
| 605 |
+
if evaluators is not None:
|
| 606 |
+
evaluator = evaluators[idx]
|
| 607 |
+
else:
|
| 608 |
+
try:
|
| 609 |
+
evaluator = cls.build_evaluator(cfg, dataset_name)
|
| 610 |
+
except NotImplementedError:
|
| 611 |
+
logger.warn(
|
| 612 |
+
"No evaluator found. Use `DefaultTrainer.test(evaluators=)`, "
|
| 613 |
+
"or implement its `build_evaluator` method."
|
| 614 |
+
)
|
| 615 |
+
results[dataset_name] = {}
|
| 616 |
+
continue
|
| 617 |
+
results_i = inference_on_dataset(model, data_loader, evaluator)
|
| 618 |
+
results[dataset_name] = results_i
|
| 619 |
+
if comm.is_main_process():
|
| 620 |
+
assert isinstance(
|
| 621 |
+
results_i, dict
|
| 622 |
+
), "Evaluator must return a dict on the main process. Got {} instead.".format(
|
| 623 |
+
results_i
|
| 624 |
+
)
|
| 625 |
+
logger.info("Evaluation results for {} in csv format:".format(dataset_name))
|
| 626 |
+
print_csv_format(results_i)
|
| 627 |
+
|
| 628 |
+
if len(results) == 1:
|
| 629 |
+
results = list(results.values())[0]
|
| 630 |
+
return results
|
| 631 |
+
|
| 632 |
+
@staticmethod
|
| 633 |
+
def auto_scale_workers(cfg, num_workers: int):
|
| 634 |
+
"""
|
| 635 |
+
When the config is defined for certain number of workers (according to
|
| 636 |
+
``cfg.SOLVER.REFERENCE_WORLD_SIZE``) that's different from the number of
|
| 637 |
+
workers currently in use, returns a new cfg where the total batch size
|
| 638 |
+
is scaled so that the per-GPU batch size stays the same as the
|
| 639 |
+
original ``IMS_PER_BATCH // REFERENCE_WORLD_SIZE``.
|
| 640 |
+
|
| 641 |
+
Other config options are also scaled accordingly:
|
| 642 |
+
* training steps and warmup steps are scaled inverse proportionally.
|
| 643 |
+
* learning rate are scaled proportionally, following :paper:`ImageNet in 1h`.
|
| 644 |
+
|
| 645 |
+
For example, with the original config like the following:
|
| 646 |
+
|
| 647 |
+
.. code-block:: yaml
|
| 648 |
+
|
| 649 |
+
IMS_PER_BATCH: 16
|
| 650 |
+
BASE_LR: 0.1
|
| 651 |
+
REFERENCE_WORLD_SIZE: 8
|
| 652 |
+
MAX_ITER: 5000
|
| 653 |
+
STEPS: (4000,)
|
| 654 |
+
CHECKPOINT_PERIOD: 1000
|
| 655 |
+
|
| 656 |
+
When this config is used on 16 GPUs instead of the reference number 8,
|
| 657 |
+
calling this method will return a new config with:
|
| 658 |
+
|
| 659 |
+
.. code-block:: yaml
|
| 660 |
+
|
| 661 |
+
IMS_PER_BATCH: 32
|
| 662 |
+
BASE_LR: 0.2
|
| 663 |
+
REFERENCE_WORLD_SIZE: 16
|
| 664 |
+
MAX_ITER: 2500
|
| 665 |
+
STEPS: (2000,)
|
| 666 |
+
CHECKPOINT_PERIOD: 500
|
| 667 |
+
|
| 668 |
+
Note that both the original config and this new config can be trained on 16 GPUs.
|
| 669 |
+
It's up to user whether to enable this feature (by setting ``REFERENCE_WORLD_SIZE``).
|
| 670 |
+
|
| 671 |
+
Returns:
|
| 672 |
+
CfgNode: a new config. Same as original if ``cfg.SOLVER.REFERENCE_WORLD_SIZE==0``.
|
| 673 |
+
"""
|
| 674 |
+
old_world_size = cfg.SOLVER.REFERENCE_WORLD_SIZE
|
| 675 |
+
if old_world_size == 0 or old_world_size == num_workers:
|
| 676 |
+
return cfg
|
| 677 |
+
cfg = cfg.clone()
|
| 678 |
+
frozen = cfg.is_frozen()
|
| 679 |
+
cfg.defrost()
|
| 680 |
+
|
| 681 |
+
assert (
|
| 682 |
+
cfg.SOLVER.IMS_PER_BATCH % old_world_size == 0
|
| 683 |
+
), "Invalid REFERENCE_WORLD_SIZE in config!"
|
| 684 |
+
scale = num_workers / old_world_size
|
| 685 |
+
bs = cfg.SOLVER.IMS_PER_BATCH = int(round(cfg.SOLVER.IMS_PER_BATCH * scale))
|
| 686 |
+
lr = cfg.SOLVER.BASE_LR = cfg.SOLVER.BASE_LR * scale
|
| 687 |
+
max_iter = cfg.SOLVER.MAX_ITER = int(round(cfg.SOLVER.MAX_ITER / scale))
|
| 688 |
+
warmup_iter = cfg.SOLVER.WARMUP_ITERS = int(round(cfg.SOLVER.WARMUP_ITERS / scale))
|
| 689 |
+
cfg.SOLVER.STEPS = tuple(int(round(s / scale)) for s in cfg.SOLVER.STEPS)
|
| 690 |
+
cfg.TEST.EVAL_PERIOD = int(round(cfg.TEST.EVAL_PERIOD / scale))
|
| 691 |
+
cfg.SOLVER.CHECKPOINT_PERIOD = int(round(cfg.SOLVER.CHECKPOINT_PERIOD / scale))
|
| 692 |
+
cfg.SOLVER.REFERENCE_WORLD_SIZE = num_workers # maintain invariant
|
| 693 |
+
logger = logging.getLogger(__name__)
|
| 694 |
+
logger.info(
|
| 695 |
+
f"Auto-scaling the config to batch_size={bs}, learning_rate={lr}, "
|
| 696 |
+
f"max_iter={max_iter}, warmup={warmup_iter}."
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
if frozen:
|
| 700 |
+
cfg.freeze()
|
| 701 |
+
return cfg
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
# Access basic attributes from the underlying trainer
|
| 705 |
+
for _attr in ["model", "data_loader", "optimizer"]:
|
| 706 |
+
setattr(
|
| 707 |
+
DefaultTrainer,
|
| 708 |
+
_attr,
|
| 709 |
+
property(
|
| 710 |
+
# getter
|
| 711 |
+
lambda self, x=_attr: getattr(self._trainer, x),
|
| 712 |
+
# setter
|
| 713 |
+
lambda self, value, x=_attr: setattr(self._trainer, x, value),
|
| 714 |
+
),
|
| 715 |
+
)
|
RAVE-main/annotator/oneformer/detectron2/engine/hooks.py
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
|
| 4 |
+
import datetime
|
| 5 |
+
import itertools
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
import operator
|
| 9 |
+
import os
|
| 10 |
+
import tempfile
|
| 11 |
+
import time
|
| 12 |
+
import warnings
|
| 13 |
+
from collections import Counter
|
| 14 |
+
import torch
|
| 15 |
+
from fvcore.common.checkpoint import Checkpointer
|
| 16 |
+
from fvcore.common.checkpoint import PeriodicCheckpointer as _PeriodicCheckpointer
|
| 17 |
+
from fvcore.common.param_scheduler import ParamScheduler
|
| 18 |
+
from fvcore.common.timer import Timer
|
| 19 |
+
from fvcore.nn.precise_bn import get_bn_modules, update_bn_stats
|
| 20 |
+
|
| 21 |
+
import annotator.oneformer.detectron2.utils.comm as comm
|
| 22 |
+
from annotator.oneformer.detectron2.evaluation.testing import flatten_results_dict
|
| 23 |
+
from annotator.oneformer.detectron2.solver import LRMultiplier
|
| 24 |
+
from annotator.oneformer.detectron2.solver import LRScheduler as _LRScheduler
|
| 25 |
+
from annotator.oneformer.detectron2.utils.events import EventStorage, EventWriter
|
| 26 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 27 |
+
|
| 28 |
+
from .train_loop import HookBase
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
"CallbackHook",
|
| 32 |
+
"IterationTimer",
|
| 33 |
+
"PeriodicWriter",
|
| 34 |
+
"PeriodicCheckpointer",
|
| 35 |
+
"BestCheckpointer",
|
| 36 |
+
"LRScheduler",
|
| 37 |
+
"AutogradProfiler",
|
| 38 |
+
"EvalHook",
|
| 39 |
+
"PreciseBN",
|
| 40 |
+
"TorchProfiler",
|
| 41 |
+
"TorchMemoryStats",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
Implement some common hooks.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class CallbackHook(HookBase):
|
| 51 |
+
"""
|
| 52 |
+
Create a hook using callback functions provided by the user.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(self, *, before_train=None, after_train=None, before_step=None, after_step=None):
|
| 56 |
+
"""
|
| 57 |
+
Each argument is a function that takes one argument: the trainer.
|
| 58 |
+
"""
|
| 59 |
+
self._before_train = before_train
|
| 60 |
+
self._before_step = before_step
|
| 61 |
+
self._after_step = after_step
|
| 62 |
+
self._after_train = after_train
|
| 63 |
+
|
| 64 |
+
def before_train(self):
|
| 65 |
+
if self._before_train:
|
| 66 |
+
self._before_train(self.trainer)
|
| 67 |
+
|
| 68 |
+
def after_train(self):
|
| 69 |
+
if self._after_train:
|
| 70 |
+
self._after_train(self.trainer)
|
| 71 |
+
# The functions may be closures that hold reference to the trainer
|
| 72 |
+
# Therefore, delete them to avoid circular reference.
|
| 73 |
+
del self._before_train, self._after_train
|
| 74 |
+
del self._before_step, self._after_step
|
| 75 |
+
|
| 76 |
+
def before_step(self):
|
| 77 |
+
if self._before_step:
|
| 78 |
+
self._before_step(self.trainer)
|
| 79 |
+
|
| 80 |
+
def after_step(self):
|
| 81 |
+
if self._after_step:
|
| 82 |
+
self._after_step(self.trainer)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class IterationTimer(HookBase):
|
| 86 |
+
"""
|
| 87 |
+
Track the time spent for each iteration (each run_step call in the trainer).
|
| 88 |
+
Print a summary in the end of training.
|
| 89 |
+
|
| 90 |
+
This hook uses the time between the call to its :meth:`before_step`
|
| 91 |
+
and :meth:`after_step` methods.
|
| 92 |
+
Under the convention that :meth:`before_step` of all hooks should only
|
| 93 |
+
take negligible amount of time, the :class:`IterationTimer` hook should be
|
| 94 |
+
placed at the beginning of the list of hooks to obtain accurate timing.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def __init__(self, warmup_iter=3):
|
| 98 |
+
"""
|
| 99 |
+
Args:
|
| 100 |
+
warmup_iter (int): the number of iterations at the beginning to exclude
|
| 101 |
+
from timing.
|
| 102 |
+
"""
|
| 103 |
+
self._warmup_iter = warmup_iter
|
| 104 |
+
self._step_timer = Timer()
|
| 105 |
+
self._start_time = time.perf_counter()
|
| 106 |
+
self._total_timer = Timer()
|
| 107 |
+
|
| 108 |
+
def before_train(self):
|
| 109 |
+
self._start_time = time.perf_counter()
|
| 110 |
+
self._total_timer.reset()
|
| 111 |
+
self._total_timer.pause()
|
| 112 |
+
|
| 113 |
+
def after_train(self):
|
| 114 |
+
logger = logging.getLogger(__name__)
|
| 115 |
+
total_time = time.perf_counter() - self._start_time
|
| 116 |
+
total_time_minus_hooks = self._total_timer.seconds()
|
| 117 |
+
hook_time = total_time - total_time_minus_hooks
|
| 118 |
+
|
| 119 |
+
num_iter = self.trainer.storage.iter + 1 - self.trainer.start_iter - self._warmup_iter
|
| 120 |
+
|
| 121 |
+
if num_iter > 0 and total_time_minus_hooks > 0:
|
| 122 |
+
# Speed is meaningful only after warmup
|
| 123 |
+
# NOTE this format is parsed by grep in some scripts
|
| 124 |
+
logger.info(
|
| 125 |
+
"Overall training speed: {} iterations in {} ({:.4f} s / it)".format(
|
| 126 |
+
num_iter,
|
| 127 |
+
str(datetime.timedelta(seconds=int(total_time_minus_hooks))),
|
| 128 |
+
total_time_minus_hooks / num_iter,
|
| 129 |
+
)
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
logger.info(
|
| 133 |
+
"Total training time: {} ({} on hooks)".format(
|
| 134 |
+
str(datetime.timedelta(seconds=int(total_time))),
|
| 135 |
+
str(datetime.timedelta(seconds=int(hook_time))),
|
| 136 |
+
)
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def before_step(self):
|
| 140 |
+
self._step_timer.reset()
|
| 141 |
+
self._total_timer.resume()
|
| 142 |
+
|
| 143 |
+
def after_step(self):
|
| 144 |
+
# +1 because we're in after_step, the current step is done
|
| 145 |
+
# but not yet counted
|
| 146 |
+
iter_done = self.trainer.storage.iter - self.trainer.start_iter + 1
|
| 147 |
+
if iter_done >= self._warmup_iter:
|
| 148 |
+
sec = self._step_timer.seconds()
|
| 149 |
+
self.trainer.storage.put_scalars(time=sec)
|
| 150 |
+
else:
|
| 151 |
+
self._start_time = time.perf_counter()
|
| 152 |
+
self._total_timer.reset()
|
| 153 |
+
|
| 154 |
+
self._total_timer.pause()
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class PeriodicWriter(HookBase):
|
| 158 |
+
"""
|
| 159 |
+
Write events to EventStorage (by calling ``writer.write()``) periodically.
|
| 160 |
+
|
| 161 |
+
It is executed every ``period`` iterations and after the last iteration.
|
| 162 |
+
Note that ``period`` does not affect how data is smoothed by each writer.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
def __init__(self, writers, period=20):
|
| 166 |
+
"""
|
| 167 |
+
Args:
|
| 168 |
+
writers (list[EventWriter]): a list of EventWriter objects
|
| 169 |
+
period (int):
|
| 170 |
+
"""
|
| 171 |
+
self._writers = writers
|
| 172 |
+
for w in writers:
|
| 173 |
+
assert isinstance(w, EventWriter), w
|
| 174 |
+
self._period = period
|
| 175 |
+
|
| 176 |
+
def after_step(self):
|
| 177 |
+
if (self.trainer.iter + 1) % self._period == 0 or (
|
| 178 |
+
self.trainer.iter == self.trainer.max_iter - 1
|
| 179 |
+
):
|
| 180 |
+
for writer in self._writers:
|
| 181 |
+
writer.write()
|
| 182 |
+
|
| 183 |
+
def after_train(self):
|
| 184 |
+
for writer in self._writers:
|
| 185 |
+
# If any new data is found (e.g. produced by other after_train),
|
| 186 |
+
# write them before closing
|
| 187 |
+
writer.write()
|
| 188 |
+
writer.close()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class PeriodicCheckpointer(_PeriodicCheckpointer, HookBase):
|
| 192 |
+
"""
|
| 193 |
+
Same as :class:`detectron2.checkpoint.PeriodicCheckpointer`, but as a hook.
|
| 194 |
+
|
| 195 |
+
Note that when used as a hook,
|
| 196 |
+
it is unable to save additional data other than what's defined
|
| 197 |
+
by the given `checkpointer`.
|
| 198 |
+
|
| 199 |
+
It is executed every ``period`` iterations and after the last iteration.
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
def before_train(self):
|
| 203 |
+
self.max_iter = self.trainer.max_iter
|
| 204 |
+
|
| 205 |
+
def after_step(self):
|
| 206 |
+
# No way to use **kwargs
|
| 207 |
+
self.step(self.trainer.iter)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class BestCheckpointer(HookBase):
|
| 211 |
+
"""
|
| 212 |
+
Checkpoints best weights based off given metric.
|
| 213 |
+
|
| 214 |
+
This hook should be used in conjunction to and executed after the hook
|
| 215 |
+
that produces the metric, e.g. `EvalHook`.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
def __init__(
|
| 219 |
+
self,
|
| 220 |
+
eval_period: int,
|
| 221 |
+
checkpointer: Checkpointer,
|
| 222 |
+
val_metric: str,
|
| 223 |
+
mode: str = "max",
|
| 224 |
+
file_prefix: str = "model_best",
|
| 225 |
+
) -> None:
|
| 226 |
+
"""
|
| 227 |
+
Args:
|
| 228 |
+
eval_period (int): the period `EvalHook` is set to run.
|
| 229 |
+
checkpointer: the checkpointer object used to save checkpoints.
|
| 230 |
+
val_metric (str): validation metric to track for best checkpoint, e.g. "bbox/AP50"
|
| 231 |
+
mode (str): one of {'max', 'min'}. controls whether the chosen val metric should be
|
| 232 |
+
maximized or minimized, e.g. for "bbox/AP50" it should be "max"
|
| 233 |
+
file_prefix (str): the prefix of checkpoint's filename, defaults to "model_best"
|
| 234 |
+
"""
|
| 235 |
+
self._logger = logging.getLogger(__name__)
|
| 236 |
+
self._period = eval_period
|
| 237 |
+
self._val_metric = val_metric
|
| 238 |
+
assert mode in [
|
| 239 |
+
"max",
|
| 240 |
+
"min",
|
| 241 |
+
], f'Mode "{mode}" to `BestCheckpointer` is unknown. It should be one of {"max", "min"}.'
|
| 242 |
+
if mode == "max":
|
| 243 |
+
self._compare = operator.gt
|
| 244 |
+
else:
|
| 245 |
+
self._compare = operator.lt
|
| 246 |
+
self._checkpointer = checkpointer
|
| 247 |
+
self._file_prefix = file_prefix
|
| 248 |
+
self.best_metric = None
|
| 249 |
+
self.best_iter = None
|
| 250 |
+
|
| 251 |
+
def _update_best(self, val, iteration):
|
| 252 |
+
if math.isnan(val) or math.isinf(val):
|
| 253 |
+
return False
|
| 254 |
+
self.best_metric = val
|
| 255 |
+
self.best_iter = iteration
|
| 256 |
+
return True
|
| 257 |
+
|
| 258 |
+
def _best_checking(self):
|
| 259 |
+
metric_tuple = self.trainer.storage.latest().get(self._val_metric)
|
| 260 |
+
if metric_tuple is None:
|
| 261 |
+
self._logger.warning(
|
| 262 |
+
f"Given val metric {self._val_metric} does not seem to be computed/stored."
|
| 263 |
+
"Will not be checkpointing based on it."
|
| 264 |
+
)
|
| 265 |
+
return
|
| 266 |
+
else:
|
| 267 |
+
latest_metric, metric_iter = metric_tuple
|
| 268 |
+
|
| 269 |
+
if self.best_metric is None:
|
| 270 |
+
if self._update_best(latest_metric, metric_iter):
|
| 271 |
+
additional_state = {"iteration": metric_iter}
|
| 272 |
+
self._checkpointer.save(f"{self._file_prefix}", **additional_state)
|
| 273 |
+
self._logger.info(
|
| 274 |
+
f"Saved first model at {self.best_metric:0.5f} @ {self.best_iter} steps"
|
| 275 |
+
)
|
| 276 |
+
elif self._compare(latest_metric, self.best_metric):
|
| 277 |
+
additional_state = {"iteration": metric_iter}
|
| 278 |
+
self._checkpointer.save(f"{self._file_prefix}", **additional_state)
|
| 279 |
+
self._logger.info(
|
| 280 |
+
f"Saved best model as latest eval score for {self._val_metric} is "
|
| 281 |
+
f"{latest_metric:0.5f}, better than last best score "
|
| 282 |
+
f"{self.best_metric:0.5f} @ iteration {self.best_iter}."
|
| 283 |
+
)
|
| 284 |
+
self._update_best(latest_metric, metric_iter)
|
| 285 |
+
else:
|
| 286 |
+
self._logger.info(
|
| 287 |
+
f"Not saving as latest eval score for {self._val_metric} is {latest_metric:0.5f}, "
|
| 288 |
+
f"not better than best score {self.best_metric:0.5f} @ iteration {self.best_iter}."
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
def after_step(self):
|
| 292 |
+
# same conditions as `EvalHook`
|
| 293 |
+
next_iter = self.trainer.iter + 1
|
| 294 |
+
if (
|
| 295 |
+
self._period > 0
|
| 296 |
+
and next_iter % self._period == 0
|
| 297 |
+
and next_iter != self.trainer.max_iter
|
| 298 |
+
):
|
| 299 |
+
self._best_checking()
|
| 300 |
+
|
| 301 |
+
def after_train(self):
|
| 302 |
+
# same conditions as `EvalHook`
|
| 303 |
+
if self.trainer.iter + 1 >= self.trainer.max_iter:
|
| 304 |
+
self._best_checking()
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class LRScheduler(HookBase):
|
| 308 |
+
"""
|
| 309 |
+
A hook which executes a torch builtin LR scheduler and summarizes the LR.
|
| 310 |
+
It is executed after every iteration.
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
def __init__(self, optimizer=None, scheduler=None):
|
| 314 |
+
"""
|
| 315 |
+
Args:
|
| 316 |
+
optimizer (torch.optim.Optimizer):
|
| 317 |
+
scheduler (torch.optim.LRScheduler or fvcore.common.param_scheduler.ParamScheduler):
|
| 318 |
+
if a :class:`ParamScheduler` object, it defines the multiplier over the base LR
|
| 319 |
+
in the optimizer.
|
| 320 |
+
|
| 321 |
+
If any argument is not given, will try to obtain it from the trainer.
|
| 322 |
+
"""
|
| 323 |
+
self._optimizer = optimizer
|
| 324 |
+
self._scheduler = scheduler
|
| 325 |
+
|
| 326 |
+
def before_train(self):
|
| 327 |
+
self._optimizer = self._optimizer or self.trainer.optimizer
|
| 328 |
+
if isinstance(self.scheduler, ParamScheduler):
|
| 329 |
+
self._scheduler = LRMultiplier(
|
| 330 |
+
self._optimizer,
|
| 331 |
+
self.scheduler,
|
| 332 |
+
self.trainer.max_iter,
|
| 333 |
+
last_iter=self.trainer.iter - 1,
|
| 334 |
+
)
|
| 335 |
+
self._best_param_group_id = LRScheduler.get_best_param_group_id(self._optimizer)
|
| 336 |
+
|
| 337 |
+
@staticmethod
|
| 338 |
+
def get_best_param_group_id(optimizer):
|
| 339 |
+
# NOTE: some heuristics on what LR to summarize
|
| 340 |
+
# summarize the param group with most parameters
|
| 341 |
+
largest_group = max(len(g["params"]) for g in optimizer.param_groups)
|
| 342 |
+
|
| 343 |
+
if largest_group == 1:
|
| 344 |
+
# If all groups have one parameter,
|
| 345 |
+
# then find the most common initial LR, and use it for summary
|
| 346 |
+
lr_count = Counter([g["lr"] for g in optimizer.param_groups])
|
| 347 |
+
lr = lr_count.most_common()[0][0]
|
| 348 |
+
for i, g in enumerate(optimizer.param_groups):
|
| 349 |
+
if g["lr"] == lr:
|
| 350 |
+
return i
|
| 351 |
+
else:
|
| 352 |
+
for i, g in enumerate(optimizer.param_groups):
|
| 353 |
+
if len(g["params"]) == largest_group:
|
| 354 |
+
return i
|
| 355 |
+
|
| 356 |
+
def after_step(self):
|
| 357 |
+
lr = self._optimizer.param_groups[self._best_param_group_id]["lr"]
|
| 358 |
+
self.trainer.storage.put_scalar("lr", lr, smoothing_hint=False)
|
| 359 |
+
self.scheduler.step()
|
| 360 |
+
|
| 361 |
+
@property
|
| 362 |
+
def scheduler(self):
|
| 363 |
+
return self._scheduler or self.trainer.scheduler
|
| 364 |
+
|
| 365 |
+
def state_dict(self):
|
| 366 |
+
if isinstance(self.scheduler, _LRScheduler):
|
| 367 |
+
return self.scheduler.state_dict()
|
| 368 |
+
return {}
|
| 369 |
+
|
| 370 |
+
def load_state_dict(self, state_dict):
|
| 371 |
+
if isinstance(self.scheduler, _LRScheduler):
|
| 372 |
+
logger = logging.getLogger(__name__)
|
| 373 |
+
logger.info("Loading scheduler from state_dict ...")
|
| 374 |
+
self.scheduler.load_state_dict(state_dict)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class TorchProfiler(HookBase):
|
| 378 |
+
"""
|
| 379 |
+
A hook which runs `torch.profiler.profile`.
|
| 380 |
+
|
| 381 |
+
Examples:
|
| 382 |
+
::
|
| 383 |
+
hooks.TorchProfiler(
|
| 384 |
+
lambda trainer: 10 < trainer.iter < 20, self.cfg.OUTPUT_DIR
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
The above example will run the profiler for iteration 10~20 and dump
|
| 388 |
+
results to ``OUTPUT_DIR``. We did not profile the first few iterations
|
| 389 |
+
because they are typically slower than the rest.
|
| 390 |
+
The result files can be loaded in the ``chrome://tracing`` page in chrome browser,
|
| 391 |
+
and the tensorboard visualizations can be visualized using
|
| 392 |
+
``tensorboard --logdir OUTPUT_DIR/log``
|
| 393 |
+
"""
|
| 394 |
+
|
| 395 |
+
def __init__(self, enable_predicate, output_dir, *, activities=None, save_tensorboard=True):
|
| 396 |
+
"""
|
| 397 |
+
Args:
|
| 398 |
+
enable_predicate (callable[trainer -> bool]): a function which takes a trainer,
|
| 399 |
+
and returns whether to enable the profiler.
|
| 400 |
+
It will be called once every step, and can be used to select which steps to profile.
|
| 401 |
+
output_dir (str): the output directory to dump tracing files.
|
| 402 |
+
activities (iterable): same as in `torch.profiler.profile`.
|
| 403 |
+
save_tensorboard (bool): whether to save tensorboard visualizations at (output_dir)/log/
|
| 404 |
+
"""
|
| 405 |
+
self._enable_predicate = enable_predicate
|
| 406 |
+
self._activities = activities
|
| 407 |
+
self._output_dir = output_dir
|
| 408 |
+
self._save_tensorboard = save_tensorboard
|
| 409 |
+
|
| 410 |
+
def before_step(self):
|
| 411 |
+
if self._enable_predicate(self.trainer):
|
| 412 |
+
if self._save_tensorboard:
|
| 413 |
+
on_trace_ready = torch.profiler.tensorboard_trace_handler(
|
| 414 |
+
os.path.join(
|
| 415 |
+
self._output_dir,
|
| 416 |
+
"log",
|
| 417 |
+
"profiler-tensorboard-iter{}".format(self.trainer.iter),
|
| 418 |
+
),
|
| 419 |
+
f"worker{comm.get_rank()}",
|
| 420 |
+
)
|
| 421 |
+
else:
|
| 422 |
+
on_trace_ready = None
|
| 423 |
+
self._profiler = torch.profiler.profile(
|
| 424 |
+
activities=self._activities,
|
| 425 |
+
on_trace_ready=on_trace_ready,
|
| 426 |
+
record_shapes=True,
|
| 427 |
+
profile_memory=True,
|
| 428 |
+
with_stack=True,
|
| 429 |
+
with_flops=True,
|
| 430 |
+
)
|
| 431 |
+
self._profiler.__enter__()
|
| 432 |
+
else:
|
| 433 |
+
self._profiler = None
|
| 434 |
+
|
| 435 |
+
def after_step(self):
|
| 436 |
+
if self._profiler is None:
|
| 437 |
+
return
|
| 438 |
+
self._profiler.__exit__(None, None, None)
|
| 439 |
+
if not self._save_tensorboard:
|
| 440 |
+
PathManager.mkdirs(self._output_dir)
|
| 441 |
+
out_file = os.path.join(
|
| 442 |
+
self._output_dir, "profiler-trace-iter{}.json".format(self.trainer.iter)
|
| 443 |
+
)
|
| 444 |
+
if "://" not in out_file:
|
| 445 |
+
self._profiler.export_chrome_trace(out_file)
|
| 446 |
+
else:
|
| 447 |
+
# Support non-posix filesystems
|
| 448 |
+
with tempfile.TemporaryDirectory(prefix="detectron2_profiler") as d:
|
| 449 |
+
tmp_file = os.path.join(d, "tmp.json")
|
| 450 |
+
self._profiler.export_chrome_trace(tmp_file)
|
| 451 |
+
with open(tmp_file) as f:
|
| 452 |
+
content = f.read()
|
| 453 |
+
with PathManager.open(out_file, "w") as f:
|
| 454 |
+
f.write(content)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
class AutogradProfiler(TorchProfiler):
|
| 458 |
+
"""
|
| 459 |
+
A hook which runs `torch.autograd.profiler.profile`.
|
| 460 |
+
|
| 461 |
+
Examples:
|
| 462 |
+
::
|
| 463 |
+
hooks.AutogradProfiler(
|
| 464 |
+
lambda trainer: 10 < trainer.iter < 20, self.cfg.OUTPUT_DIR
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
The above example will run the profiler for iteration 10~20 and dump
|
| 468 |
+
results to ``OUTPUT_DIR``. We did not profile the first few iterations
|
| 469 |
+
because they are typically slower than the rest.
|
| 470 |
+
The result files can be loaded in the ``chrome://tracing`` page in chrome browser.
|
| 471 |
+
|
| 472 |
+
Note:
|
| 473 |
+
When used together with NCCL on older version of GPUs,
|
| 474 |
+
autograd profiler may cause deadlock because it unnecessarily allocates
|
| 475 |
+
memory on every device it sees. The memory management calls, if
|
| 476 |
+
interleaved with NCCL calls, lead to deadlock on GPUs that do not
|
| 477 |
+
support ``cudaLaunchCooperativeKernelMultiDevice``.
|
| 478 |
+
"""
|
| 479 |
+
|
| 480 |
+
def __init__(self, enable_predicate, output_dir, *, use_cuda=True):
|
| 481 |
+
"""
|
| 482 |
+
Args:
|
| 483 |
+
enable_predicate (callable[trainer -> bool]): a function which takes a trainer,
|
| 484 |
+
and returns whether to enable the profiler.
|
| 485 |
+
It will be called once every step, and can be used to select which steps to profile.
|
| 486 |
+
output_dir (str): the output directory to dump tracing files.
|
| 487 |
+
use_cuda (bool): same as in `torch.autograd.profiler.profile`.
|
| 488 |
+
"""
|
| 489 |
+
warnings.warn("AutogradProfiler has been deprecated in favor of TorchProfiler.")
|
| 490 |
+
self._enable_predicate = enable_predicate
|
| 491 |
+
self._use_cuda = use_cuda
|
| 492 |
+
self._output_dir = output_dir
|
| 493 |
+
|
| 494 |
+
def before_step(self):
|
| 495 |
+
if self._enable_predicate(self.trainer):
|
| 496 |
+
self._profiler = torch.autograd.profiler.profile(use_cuda=self._use_cuda)
|
| 497 |
+
self._profiler.__enter__()
|
| 498 |
+
else:
|
| 499 |
+
self._profiler = None
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
class EvalHook(HookBase):
|
| 503 |
+
"""
|
| 504 |
+
Run an evaluation function periodically, and at the end of training.
|
| 505 |
+
|
| 506 |
+
It is executed every ``eval_period`` iterations and after the last iteration.
|
| 507 |
+
"""
|
| 508 |
+
|
| 509 |
+
def __init__(self, eval_period, eval_function, eval_after_train=True):
|
| 510 |
+
"""
|
| 511 |
+
Args:
|
| 512 |
+
eval_period (int): the period to run `eval_function`. Set to 0 to
|
| 513 |
+
not evaluate periodically (but still evaluate after the last iteration
|
| 514 |
+
if `eval_after_train` is True).
|
| 515 |
+
eval_function (callable): a function which takes no arguments, and
|
| 516 |
+
returns a nested dict of evaluation metrics.
|
| 517 |
+
eval_after_train (bool): whether to evaluate after the last iteration
|
| 518 |
+
|
| 519 |
+
Note:
|
| 520 |
+
This hook must be enabled in all or none workers.
|
| 521 |
+
If you would like only certain workers to perform evaluation,
|
| 522 |
+
give other workers a no-op function (`eval_function=lambda: None`).
|
| 523 |
+
"""
|
| 524 |
+
self._period = eval_period
|
| 525 |
+
self._func = eval_function
|
| 526 |
+
self._eval_after_train = eval_after_train
|
| 527 |
+
|
| 528 |
+
def _do_eval(self):
|
| 529 |
+
results = self._func()
|
| 530 |
+
|
| 531 |
+
if results:
|
| 532 |
+
assert isinstance(
|
| 533 |
+
results, dict
|
| 534 |
+
), "Eval function must return a dict. Got {} instead.".format(results)
|
| 535 |
+
|
| 536 |
+
flattened_results = flatten_results_dict(results)
|
| 537 |
+
for k, v in flattened_results.items():
|
| 538 |
+
try:
|
| 539 |
+
v = float(v)
|
| 540 |
+
except Exception as e:
|
| 541 |
+
raise ValueError(
|
| 542 |
+
"[EvalHook] eval_function should return a nested dict of float. "
|
| 543 |
+
"Got '{}: {}' instead.".format(k, v)
|
| 544 |
+
) from e
|
| 545 |
+
self.trainer.storage.put_scalars(**flattened_results, smoothing_hint=False)
|
| 546 |
+
|
| 547 |
+
# Evaluation may take different time among workers.
|
| 548 |
+
# A barrier make them start the next iteration together.
|
| 549 |
+
comm.synchronize()
|
| 550 |
+
|
| 551 |
+
def after_step(self):
|
| 552 |
+
next_iter = self.trainer.iter + 1
|
| 553 |
+
if self._period > 0 and next_iter % self._period == 0:
|
| 554 |
+
# do the last eval in after_train
|
| 555 |
+
if next_iter != self.trainer.max_iter:
|
| 556 |
+
self._do_eval()
|
| 557 |
+
|
| 558 |
+
def after_train(self):
|
| 559 |
+
# This condition is to prevent the eval from running after a failed training
|
| 560 |
+
if self._eval_after_train and self.trainer.iter + 1 >= self.trainer.max_iter:
|
| 561 |
+
self._do_eval()
|
| 562 |
+
# func is likely a closure that holds reference to the trainer
|
| 563 |
+
# therefore we clean it to avoid circular reference in the end
|
| 564 |
+
del self._func
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class PreciseBN(HookBase):
|
| 568 |
+
"""
|
| 569 |
+
The standard implementation of BatchNorm uses EMA in inference, which is
|
| 570 |
+
sometimes suboptimal.
|
| 571 |
+
This class computes the true average of statistics rather than the moving average,
|
| 572 |
+
and put true averages to every BN layer in the given model.
|
| 573 |
+
|
| 574 |
+
It is executed every ``period`` iterations and after the last iteration.
|
| 575 |
+
"""
|
| 576 |
+
|
| 577 |
+
def __init__(self, period, model, data_loader, num_iter):
|
| 578 |
+
"""
|
| 579 |
+
Args:
|
| 580 |
+
period (int): the period this hook is run, or 0 to not run during training.
|
| 581 |
+
The hook will always run in the end of training.
|
| 582 |
+
model (nn.Module): a module whose all BN layers in training mode will be
|
| 583 |
+
updated by precise BN.
|
| 584 |
+
Note that user is responsible for ensuring the BN layers to be
|
| 585 |
+
updated are in training mode when this hook is triggered.
|
| 586 |
+
data_loader (iterable): it will produce data to be run by `model(data)`.
|
| 587 |
+
num_iter (int): number of iterations used to compute the precise
|
| 588 |
+
statistics.
|
| 589 |
+
"""
|
| 590 |
+
self._logger = logging.getLogger(__name__)
|
| 591 |
+
if len(get_bn_modules(model)) == 0:
|
| 592 |
+
self._logger.info(
|
| 593 |
+
"PreciseBN is disabled because model does not contain BN layers in training mode."
|
| 594 |
+
)
|
| 595 |
+
self._disabled = True
|
| 596 |
+
return
|
| 597 |
+
|
| 598 |
+
self._model = model
|
| 599 |
+
self._data_loader = data_loader
|
| 600 |
+
self._num_iter = num_iter
|
| 601 |
+
self._period = period
|
| 602 |
+
self._disabled = False
|
| 603 |
+
|
| 604 |
+
self._data_iter = None
|
| 605 |
+
|
| 606 |
+
def after_step(self):
|
| 607 |
+
next_iter = self.trainer.iter + 1
|
| 608 |
+
is_final = next_iter == self.trainer.max_iter
|
| 609 |
+
if is_final or (self._period > 0 and next_iter % self._period == 0):
|
| 610 |
+
self.update_stats()
|
| 611 |
+
|
| 612 |
+
def update_stats(self):
|
| 613 |
+
"""
|
| 614 |
+
Update the model with precise statistics. Users can manually call this method.
|
| 615 |
+
"""
|
| 616 |
+
if self._disabled:
|
| 617 |
+
return
|
| 618 |
+
|
| 619 |
+
if self._data_iter is None:
|
| 620 |
+
self._data_iter = iter(self._data_loader)
|
| 621 |
+
|
| 622 |
+
def data_loader():
|
| 623 |
+
for num_iter in itertools.count(1):
|
| 624 |
+
if num_iter % 100 == 0:
|
| 625 |
+
self._logger.info(
|
| 626 |
+
"Running precise-BN ... {}/{} iterations.".format(num_iter, self._num_iter)
|
| 627 |
+
)
|
| 628 |
+
# This way we can reuse the same iterator
|
| 629 |
+
yield next(self._data_iter)
|
| 630 |
+
|
| 631 |
+
with EventStorage(): # capture events in a new storage to discard them
|
| 632 |
+
self._logger.info(
|
| 633 |
+
"Running precise-BN for {} iterations... ".format(self._num_iter)
|
| 634 |
+
+ "Note that this could produce different statistics every time."
|
| 635 |
+
)
|
| 636 |
+
update_bn_stats(self._model, data_loader(), self._num_iter)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
class TorchMemoryStats(HookBase):
|
| 640 |
+
"""
|
| 641 |
+
Writes pytorch's cuda memory statistics periodically.
|
| 642 |
+
"""
|
| 643 |
+
|
| 644 |
+
def __init__(self, period=20, max_runs=10):
|
| 645 |
+
"""
|
| 646 |
+
Args:
|
| 647 |
+
period (int): Output stats each 'period' iterations
|
| 648 |
+
max_runs (int): Stop the logging after 'max_runs'
|
| 649 |
+
"""
|
| 650 |
+
|
| 651 |
+
self._logger = logging.getLogger(__name__)
|
| 652 |
+
self._period = period
|
| 653 |
+
self._max_runs = max_runs
|
| 654 |
+
self._runs = 0
|
| 655 |
+
|
| 656 |
+
def after_step(self):
|
| 657 |
+
if self._runs > self._max_runs:
|
| 658 |
+
return
|
| 659 |
+
|
| 660 |
+
if (self.trainer.iter + 1) % self._period == 0 or (
|
| 661 |
+
self.trainer.iter == self.trainer.max_iter - 1
|
| 662 |
+
):
|
| 663 |
+
if torch.cuda.is_available():
|
| 664 |
+
max_reserved_mb = torch.cuda.max_memory_reserved() / 1024.0 / 1024.0
|
| 665 |
+
reserved_mb = torch.cuda.memory_reserved() / 1024.0 / 1024.0
|
| 666 |
+
max_allocated_mb = torch.cuda.max_memory_allocated() / 1024.0 / 1024.0
|
| 667 |
+
allocated_mb = torch.cuda.memory_allocated() / 1024.0 / 1024.0
|
| 668 |
+
|
| 669 |
+
self._logger.info(
|
| 670 |
+
(
|
| 671 |
+
" iter: {} "
|
| 672 |
+
" max_reserved_mem: {:.0f}MB "
|
| 673 |
+
" reserved_mem: {:.0f}MB "
|
| 674 |
+
" max_allocated_mem: {:.0f}MB "
|
| 675 |
+
" allocated_mem: {:.0f}MB "
|
| 676 |
+
).format(
|
| 677 |
+
self.trainer.iter,
|
| 678 |
+
max_reserved_mb,
|
| 679 |
+
reserved_mb,
|
| 680 |
+
max_allocated_mb,
|
| 681 |
+
allocated_mb,
|
| 682 |
+
)
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
self._runs += 1
|
| 686 |
+
if self._runs == self._max_runs:
|
| 687 |
+
mem_summary = torch.cuda.memory_summary()
|
| 688 |
+
self._logger.info("\n" + mem_summary)
|
| 689 |
+
|
| 690 |
+
torch.cuda.reset_peak_memory_stats()
|
RAVE-main/annotator/oneformer/detectron2/engine/launch.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import logging
|
| 3 |
+
from datetime import timedelta
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
import torch.multiprocessing as mp
|
| 7 |
+
|
| 8 |
+
from annotator.oneformer.detectron2.utils import comm
|
| 9 |
+
|
| 10 |
+
__all__ = ["DEFAULT_TIMEOUT", "launch"]
|
| 11 |
+
|
| 12 |
+
DEFAULT_TIMEOUT = timedelta(minutes=30)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _find_free_port():
|
| 16 |
+
import socket
|
| 17 |
+
|
| 18 |
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 19 |
+
# Binding to port 0 will cause the OS to find an available port for us
|
| 20 |
+
sock.bind(("", 0))
|
| 21 |
+
port = sock.getsockname()[1]
|
| 22 |
+
sock.close()
|
| 23 |
+
# NOTE: there is still a chance the port could be taken by other processes.
|
| 24 |
+
return port
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def launch(
|
| 28 |
+
main_func,
|
| 29 |
+
# Should be num_processes_per_machine, but kept for compatibility.
|
| 30 |
+
num_gpus_per_machine,
|
| 31 |
+
num_machines=1,
|
| 32 |
+
machine_rank=0,
|
| 33 |
+
dist_url=None,
|
| 34 |
+
args=(),
|
| 35 |
+
timeout=DEFAULT_TIMEOUT,
|
| 36 |
+
):
|
| 37 |
+
"""
|
| 38 |
+
Launch multi-process or distributed training.
|
| 39 |
+
This function must be called on all machines involved in the training.
|
| 40 |
+
It will spawn child processes (defined by ``num_gpus_per_machine``) on each machine.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
main_func: a function that will be called by `main_func(*args)`
|
| 44 |
+
num_gpus_per_machine (int): number of processes per machine. When
|
| 45 |
+
using GPUs, this should be the number of GPUs.
|
| 46 |
+
num_machines (int): the total number of machines
|
| 47 |
+
machine_rank (int): the rank of this machine
|
| 48 |
+
dist_url (str): url to connect to for distributed jobs, including protocol
|
| 49 |
+
e.g. "tcp://127.0.0.1:8686".
|
| 50 |
+
Can be set to "auto" to automatically select a free port on localhost
|
| 51 |
+
timeout (timedelta): timeout of the distributed workers
|
| 52 |
+
args (tuple): arguments passed to main_func
|
| 53 |
+
"""
|
| 54 |
+
world_size = num_machines * num_gpus_per_machine
|
| 55 |
+
if world_size > 1:
|
| 56 |
+
# https://github.com/pytorch/pytorch/pull/14391
|
| 57 |
+
# TODO prctl in spawned processes
|
| 58 |
+
|
| 59 |
+
if dist_url == "auto":
|
| 60 |
+
assert num_machines == 1, "dist_url=auto not supported in multi-machine jobs."
|
| 61 |
+
port = _find_free_port()
|
| 62 |
+
dist_url = f"tcp://127.0.0.1:{port}"
|
| 63 |
+
if num_machines > 1 and dist_url.startswith("file://"):
|
| 64 |
+
logger = logging.getLogger(__name__)
|
| 65 |
+
logger.warning(
|
| 66 |
+
"file:// is not a reliable init_method in multi-machine jobs. Prefer tcp://"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
mp.start_processes(
|
| 70 |
+
_distributed_worker,
|
| 71 |
+
nprocs=num_gpus_per_machine,
|
| 72 |
+
args=(
|
| 73 |
+
main_func,
|
| 74 |
+
world_size,
|
| 75 |
+
num_gpus_per_machine,
|
| 76 |
+
machine_rank,
|
| 77 |
+
dist_url,
|
| 78 |
+
args,
|
| 79 |
+
timeout,
|
| 80 |
+
),
|
| 81 |
+
daemon=False,
|
| 82 |
+
)
|
| 83 |
+
else:
|
| 84 |
+
main_func(*args)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _distributed_worker(
|
| 88 |
+
local_rank,
|
| 89 |
+
main_func,
|
| 90 |
+
world_size,
|
| 91 |
+
num_gpus_per_machine,
|
| 92 |
+
machine_rank,
|
| 93 |
+
dist_url,
|
| 94 |
+
args,
|
| 95 |
+
timeout=DEFAULT_TIMEOUT,
|
| 96 |
+
):
|
| 97 |
+
has_gpu = torch.cuda.is_available()
|
| 98 |
+
if has_gpu:
|
| 99 |
+
assert num_gpus_per_machine <= torch.cuda.device_count()
|
| 100 |
+
global_rank = machine_rank * num_gpus_per_machine + local_rank
|
| 101 |
+
try:
|
| 102 |
+
dist.init_process_group(
|
| 103 |
+
backend="NCCL" if has_gpu else "GLOO",
|
| 104 |
+
init_method=dist_url,
|
| 105 |
+
world_size=world_size,
|
| 106 |
+
rank=global_rank,
|
| 107 |
+
timeout=timeout,
|
| 108 |
+
)
|
| 109 |
+
except Exception as e:
|
| 110 |
+
logger = logging.getLogger(__name__)
|
| 111 |
+
logger.error("Process group URL: {}".format(dist_url))
|
| 112 |
+
raise e
|
| 113 |
+
|
| 114 |
+
# Setup the local process group.
|
| 115 |
+
comm.create_local_process_group(num_gpus_per_machine)
|
| 116 |
+
if has_gpu:
|
| 117 |
+
torch.cuda.set_device(local_rank)
|
| 118 |
+
|
| 119 |
+
# synchronize is needed here to prevent a possible timeout after calling init_process_group
|
| 120 |
+
# See: https://github.com/facebookresearch/maskrcnn-benchmark/issues/172
|
| 121 |
+
comm.synchronize()
|
| 122 |
+
|
| 123 |
+
main_func(*args)
|
RAVE-main/annotator/oneformer/detectron2/engine/train_loop.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import numpy as np
|
| 6 |
+
import time
|
| 7 |
+
import weakref
|
| 8 |
+
from typing import List, Mapping, Optional
|
| 9 |
+
import torch
|
| 10 |
+
from torch.nn.parallel import DataParallel, DistributedDataParallel
|
| 11 |
+
|
| 12 |
+
import annotator.oneformer.detectron2.utils.comm as comm
|
| 13 |
+
from annotator.oneformer.detectron2.utils.events import EventStorage, get_event_storage
|
| 14 |
+
from annotator.oneformer.detectron2.utils.logger import _log_api_usage
|
| 15 |
+
|
| 16 |
+
__all__ = ["HookBase", "TrainerBase", "SimpleTrainer", "AMPTrainer"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class HookBase:
|
| 20 |
+
"""
|
| 21 |
+
Base class for hooks that can be registered with :class:`TrainerBase`.
|
| 22 |
+
|
| 23 |
+
Each hook can implement 4 methods. The way they are called is demonstrated
|
| 24 |
+
in the following snippet:
|
| 25 |
+
::
|
| 26 |
+
hook.before_train()
|
| 27 |
+
for iter in range(start_iter, max_iter):
|
| 28 |
+
hook.before_step()
|
| 29 |
+
trainer.run_step()
|
| 30 |
+
hook.after_step()
|
| 31 |
+
iter += 1
|
| 32 |
+
hook.after_train()
|
| 33 |
+
|
| 34 |
+
Notes:
|
| 35 |
+
1. In the hook method, users can access ``self.trainer`` to access more
|
| 36 |
+
properties about the context (e.g., model, current iteration, or config
|
| 37 |
+
if using :class:`DefaultTrainer`).
|
| 38 |
+
|
| 39 |
+
2. A hook that does something in :meth:`before_step` can often be
|
| 40 |
+
implemented equivalently in :meth:`after_step`.
|
| 41 |
+
If the hook takes non-trivial time, it is strongly recommended to
|
| 42 |
+
implement the hook in :meth:`after_step` instead of :meth:`before_step`.
|
| 43 |
+
The convention is that :meth:`before_step` should only take negligible time.
|
| 44 |
+
|
| 45 |
+
Following this convention will allow hooks that do care about the difference
|
| 46 |
+
between :meth:`before_step` and :meth:`after_step` (e.g., timer) to
|
| 47 |
+
function properly.
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
trainer: "TrainerBase" = None
|
| 52 |
+
"""
|
| 53 |
+
A weak reference to the trainer object. Set by the trainer when the hook is registered.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def before_train(self):
|
| 57 |
+
"""
|
| 58 |
+
Called before the first iteration.
|
| 59 |
+
"""
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
def after_train(self):
|
| 63 |
+
"""
|
| 64 |
+
Called after the last iteration.
|
| 65 |
+
"""
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
def before_step(self):
|
| 69 |
+
"""
|
| 70 |
+
Called before each iteration.
|
| 71 |
+
"""
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
def after_backward(self):
|
| 75 |
+
"""
|
| 76 |
+
Called after the backward pass of each iteration.
|
| 77 |
+
"""
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
def after_step(self):
|
| 81 |
+
"""
|
| 82 |
+
Called after each iteration.
|
| 83 |
+
"""
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
def state_dict(self):
|
| 87 |
+
"""
|
| 88 |
+
Hooks are stateless by default, but can be made checkpointable by
|
| 89 |
+
implementing `state_dict` and `load_state_dict`.
|
| 90 |
+
"""
|
| 91 |
+
return {}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class TrainerBase:
|
| 95 |
+
"""
|
| 96 |
+
Base class for iterative trainer with hooks.
|
| 97 |
+
|
| 98 |
+
The only assumption we made here is: the training runs in a loop.
|
| 99 |
+
A subclass can implement what the loop is.
|
| 100 |
+
We made no assumptions about the existence of dataloader, optimizer, model, etc.
|
| 101 |
+
|
| 102 |
+
Attributes:
|
| 103 |
+
iter(int): the current iteration.
|
| 104 |
+
|
| 105 |
+
start_iter(int): The iteration to start with.
|
| 106 |
+
By convention the minimum possible value is 0.
|
| 107 |
+
|
| 108 |
+
max_iter(int): The iteration to end training.
|
| 109 |
+
|
| 110 |
+
storage(EventStorage): An EventStorage that's opened during the course of training.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
def __init__(self) -> None:
|
| 114 |
+
self._hooks: List[HookBase] = []
|
| 115 |
+
self.iter: int = 0
|
| 116 |
+
self.start_iter: int = 0
|
| 117 |
+
self.max_iter: int
|
| 118 |
+
self.storage: EventStorage
|
| 119 |
+
_log_api_usage("trainer." + self.__class__.__name__)
|
| 120 |
+
|
| 121 |
+
def register_hooks(self, hooks: List[Optional[HookBase]]) -> None:
|
| 122 |
+
"""
|
| 123 |
+
Register hooks to the trainer. The hooks are executed in the order
|
| 124 |
+
they are registered.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
hooks (list[Optional[HookBase]]): list of hooks
|
| 128 |
+
"""
|
| 129 |
+
hooks = [h for h in hooks if h is not None]
|
| 130 |
+
for h in hooks:
|
| 131 |
+
assert isinstance(h, HookBase)
|
| 132 |
+
# To avoid circular reference, hooks and trainer cannot own each other.
|
| 133 |
+
# This normally does not matter, but will cause memory leak if the
|
| 134 |
+
# involved objects contain __del__:
|
| 135 |
+
# See http://engineering.hearsaysocial.com/2013/06/16/circular-references-in-python/
|
| 136 |
+
h.trainer = weakref.proxy(self)
|
| 137 |
+
self._hooks.extend(hooks)
|
| 138 |
+
|
| 139 |
+
def train(self, start_iter: int, max_iter: int):
|
| 140 |
+
"""
|
| 141 |
+
Args:
|
| 142 |
+
start_iter, max_iter (int): See docs above
|
| 143 |
+
"""
|
| 144 |
+
logger = logging.getLogger(__name__)
|
| 145 |
+
logger.info("Starting training from iteration {}".format(start_iter))
|
| 146 |
+
|
| 147 |
+
self.iter = self.start_iter = start_iter
|
| 148 |
+
self.max_iter = max_iter
|
| 149 |
+
|
| 150 |
+
with EventStorage(start_iter) as self.storage:
|
| 151 |
+
try:
|
| 152 |
+
self.before_train()
|
| 153 |
+
for self.iter in range(start_iter, max_iter):
|
| 154 |
+
self.before_step()
|
| 155 |
+
self.run_step()
|
| 156 |
+
self.after_step()
|
| 157 |
+
# self.iter == max_iter can be used by `after_train` to
|
| 158 |
+
# tell whether the training successfully finished or failed
|
| 159 |
+
# due to exceptions.
|
| 160 |
+
self.iter += 1
|
| 161 |
+
except Exception:
|
| 162 |
+
logger.exception("Exception during training:")
|
| 163 |
+
raise
|
| 164 |
+
finally:
|
| 165 |
+
self.after_train()
|
| 166 |
+
|
| 167 |
+
def before_train(self):
|
| 168 |
+
for h in self._hooks:
|
| 169 |
+
h.before_train()
|
| 170 |
+
|
| 171 |
+
def after_train(self):
|
| 172 |
+
self.storage.iter = self.iter
|
| 173 |
+
for h in self._hooks:
|
| 174 |
+
h.after_train()
|
| 175 |
+
|
| 176 |
+
def before_step(self):
|
| 177 |
+
# Maintain the invariant that storage.iter == trainer.iter
|
| 178 |
+
# for the entire execution of each step
|
| 179 |
+
self.storage.iter = self.iter
|
| 180 |
+
|
| 181 |
+
for h in self._hooks:
|
| 182 |
+
h.before_step()
|
| 183 |
+
|
| 184 |
+
def after_backward(self):
|
| 185 |
+
for h in self._hooks:
|
| 186 |
+
h.after_backward()
|
| 187 |
+
|
| 188 |
+
def after_step(self):
|
| 189 |
+
for h in self._hooks:
|
| 190 |
+
h.after_step()
|
| 191 |
+
|
| 192 |
+
def run_step(self):
|
| 193 |
+
raise NotImplementedError
|
| 194 |
+
|
| 195 |
+
def state_dict(self):
|
| 196 |
+
ret = {"iteration": self.iter}
|
| 197 |
+
hooks_state = {}
|
| 198 |
+
for h in self._hooks:
|
| 199 |
+
sd = h.state_dict()
|
| 200 |
+
if sd:
|
| 201 |
+
name = type(h).__qualname__
|
| 202 |
+
if name in hooks_state:
|
| 203 |
+
# TODO handle repetitive stateful hooks
|
| 204 |
+
continue
|
| 205 |
+
hooks_state[name] = sd
|
| 206 |
+
if hooks_state:
|
| 207 |
+
ret["hooks"] = hooks_state
|
| 208 |
+
return ret
|
| 209 |
+
|
| 210 |
+
def load_state_dict(self, state_dict):
|
| 211 |
+
logger = logging.getLogger(__name__)
|
| 212 |
+
self.iter = state_dict["iteration"]
|
| 213 |
+
for key, value in state_dict.get("hooks", {}).items():
|
| 214 |
+
for h in self._hooks:
|
| 215 |
+
try:
|
| 216 |
+
name = type(h).__qualname__
|
| 217 |
+
except AttributeError:
|
| 218 |
+
continue
|
| 219 |
+
if name == key:
|
| 220 |
+
h.load_state_dict(value)
|
| 221 |
+
break
|
| 222 |
+
else:
|
| 223 |
+
logger.warning(f"Cannot find the hook '{key}', its state_dict is ignored.")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class SimpleTrainer(TrainerBase):
|
| 227 |
+
"""
|
| 228 |
+
A simple trainer for the most common type of task:
|
| 229 |
+
single-cost single-optimizer single-data-source iterative optimization,
|
| 230 |
+
optionally using data-parallelism.
|
| 231 |
+
It assumes that every step, you:
|
| 232 |
+
|
| 233 |
+
1. Compute the loss with a data from the data_loader.
|
| 234 |
+
2. Compute the gradients with the above loss.
|
| 235 |
+
3. Update the model with the optimizer.
|
| 236 |
+
|
| 237 |
+
All other tasks during training (checkpointing, logging, evaluation, LR schedule)
|
| 238 |
+
are maintained by hooks, which can be registered by :meth:`TrainerBase.register_hooks`.
|
| 239 |
+
|
| 240 |
+
If you want to do anything fancier than this,
|
| 241 |
+
either subclass TrainerBase and implement your own `run_step`,
|
| 242 |
+
or write your own training loop.
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
def __init__(self, model, data_loader, optimizer, gather_metric_period=1):
|
| 246 |
+
"""
|
| 247 |
+
Args:
|
| 248 |
+
model: a torch Module. Takes a data from data_loader and returns a
|
| 249 |
+
dict of losses.
|
| 250 |
+
data_loader: an iterable. Contains data to be used to call model.
|
| 251 |
+
optimizer: a torch optimizer.
|
| 252 |
+
gather_metric_period: an int. Every gather_metric_period iterations
|
| 253 |
+
the metrics are gathered from all the ranks to rank 0 and logged.
|
| 254 |
+
"""
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
"""
|
| 258 |
+
We set the model to training mode in the trainer.
|
| 259 |
+
However it's valid to train a model that's in eval mode.
|
| 260 |
+
If you want your model (or a submodule of it) to behave
|
| 261 |
+
like evaluation during training, you can overwrite its train() method.
|
| 262 |
+
"""
|
| 263 |
+
model.train()
|
| 264 |
+
|
| 265 |
+
self.model = model
|
| 266 |
+
self.data_loader = data_loader
|
| 267 |
+
# to access the data loader iterator, call `self._data_loader_iter`
|
| 268 |
+
self._data_loader_iter_obj = None
|
| 269 |
+
self.optimizer = optimizer
|
| 270 |
+
self.gather_metric_period = gather_metric_period
|
| 271 |
+
|
| 272 |
+
def run_step(self):
|
| 273 |
+
"""
|
| 274 |
+
Implement the standard training logic described above.
|
| 275 |
+
"""
|
| 276 |
+
assert self.model.training, "[SimpleTrainer] model was changed to eval mode!"
|
| 277 |
+
start = time.perf_counter()
|
| 278 |
+
"""
|
| 279 |
+
If you want to do something with the data, you can wrap the dataloader.
|
| 280 |
+
"""
|
| 281 |
+
data = next(self._data_loader_iter)
|
| 282 |
+
data_time = time.perf_counter() - start
|
| 283 |
+
|
| 284 |
+
"""
|
| 285 |
+
If you want to do something with the losses, you can wrap the model.
|
| 286 |
+
"""
|
| 287 |
+
loss_dict = self.model(data)
|
| 288 |
+
if isinstance(loss_dict, torch.Tensor):
|
| 289 |
+
losses = loss_dict
|
| 290 |
+
loss_dict = {"total_loss": loss_dict}
|
| 291 |
+
else:
|
| 292 |
+
losses = sum(loss_dict.values())
|
| 293 |
+
|
| 294 |
+
"""
|
| 295 |
+
If you need to accumulate gradients or do something similar, you can
|
| 296 |
+
wrap the optimizer with your custom `zero_grad()` method.
|
| 297 |
+
"""
|
| 298 |
+
self.optimizer.zero_grad()
|
| 299 |
+
losses.backward()
|
| 300 |
+
|
| 301 |
+
self.after_backward()
|
| 302 |
+
|
| 303 |
+
self._write_metrics(loss_dict, data_time)
|
| 304 |
+
|
| 305 |
+
"""
|
| 306 |
+
If you need gradient clipping/scaling or other processing, you can
|
| 307 |
+
wrap the optimizer with your custom `step()` method. But it is
|
| 308 |
+
suboptimal as explained in https://arxiv.org/abs/2006.15704 Sec 3.2.4
|
| 309 |
+
"""
|
| 310 |
+
self.optimizer.step()
|
| 311 |
+
|
| 312 |
+
@property
|
| 313 |
+
def _data_loader_iter(self):
|
| 314 |
+
# only create the data loader iterator when it is used
|
| 315 |
+
if self._data_loader_iter_obj is None:
|
| 316 |
+
self._data_loader_iter_obj = iter(self.data_loader)
|
| 317 |
+
return self._data_loader_iter_obj
|
| 318 |
+
|
| 319 |
+
def reset_data_loader(self, data_loader_builder):
|
| 320 |
+
"""
|
| 321 |
+
Delete and replace the current data loader with a new one, which will be created
|
| 322 |
+
by calling `data_loader_builder` (without argument).
|
| 323 |
+
"""
|
| 324 |
+
del self.data_loader
|
| 325 |
+
data_loader = data_loader_builder()
|
| 326 |
+
self.data_loader = data_loader
|
| 327 |
+
self._data_loader_iter_obj = None
|
| 328 |
+
|
| 329 |
+
def _write_metrics(
|
| 330 |
+
self,
|
| 331 |
+
loss_dict: Mapping[str, torch.Tensor],
|
| 332 |
+
data_time: float,
|
| 333 |
+
prefix: str = "",
|
| 334 |
+
) -> None:
|
| 335 |
+
if (self.iter + 1) % self.gather_metric_period == 0:
|
| 336 |
+
SimpleTrainer.write_metrics(loss_dict, data_time, prefix)
|
| 337 |
+
|
| 338 |
+
@staticmethod
|
| 339 |
+
def write_metrics(
|
| 340 |
+
loss_dict: Mapping[str, torch.Tensor],
|
| 341 |
+
data_time: float,
|
| 342 |
+
prefix: str = "",
|
| 343 |
+
) -> None:
|
| 344 |
+
"""
|
| 345 |
+
Args:
|
| 346 |
+
loss_dict (dict): dict of scalar losses
|
| 347 |
+
data_time (float): time taken by the dataloader iteration
|
| 348 |
+
prefix (str): prefix for logging keys
|
| 349 |
+
"""
|
| 350 |
+
metrics_dict = {k: v.detach().cpu().item() for k, v in loss_dict.items()}
|
| 351 |
+
metrics_dict["data_time"] = data_time
|
| 352 |
+
|
| 353 |
+
# Gather metrics among all workers for logging
|
| 354 |
+
# This assumes we do DDP-style training, which is currently the only
|
| 355 |
+
# supported method in detectron2.
|
| 356 |
+
all_metrics_dict = comm.gather(metrics_dict)
|
| 357 |
+
|
| 358 |
+
if comm.is_main_process():
|
| 359 |
+
storage = get_event_storage()
|
| 360 |
+
|
| 361 |
+
# data_time among workers can have high variance. The actual latency
|
| 362 |
+
# caused by data_time is the maximum among workers.
|
| 363 |
+
data_time = np.max([x.pop("data_time") for x in all_metrics_dict])
|
| 364 |
+
storage.put_scalar("data_time", data_time)
|
| 365 |
+
|
| 366 |
+
# average the rest metrics
|
| 367 |
+
metrics_dict = {
|
| 368 |
+
k: np.mean([x[k] for x in all_metrics_dict]) for k in all_metrics_dict[0].keys()
|
| 369 |
+
}
|
| 370 |
+
total_losses_reduced = sum(metrics_dict.values())
|
| 371 |
+
if not np.isfinite(total_losses_reduced):
|
| 372 |
+
raise FloatingPointError(
|
| 373 |
+
f"Loss became infinite or NaN at iteration={storage.iter}!\n"
|
| 374 |
+
f"loss_dict = {metrics_dict}"
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
storage.put_scalar("{}total_loss".format(prefix), total_losses_reduced)
|
| 378 |
+
if len(metrics_dict) > 1:
|
| 379 |
+
storage.put_scalars(**metrics_dict)
|
| 380 |
+
|
| 381 |
+
def state_dict(self):
|
| 382 |
+
ret = super().state_dict()
|
| 383 |
+
ret["optimizer"] = self.optimizer.state_dict()
|
| 384 |
+
return ret
|
| 385 |
+
|
| 386 |
+
def load_state_dict(self, state_dict):
|
| 387 |
+
super().load_state_dict(state_dict)
|
| 388 |
+
self.optimizer.load_state_dict(state_dict["optimizer"])
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class AMPTrainer(SimpleTrainer):
|
| 392 |
+
"""
|
| 393 |
+
Like :class:`SimpleTrainer`, but uses PyTorch's native automatic mixed precision
|
| 394 |
+
in the training loop.
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
def __init__(
|
| 398 |
+
self,
|
| 399 |
+
model,
|
| 400 |
+
data_loader,
|
| 401 |
+
optimizer,
|
| 402 |
+
gather_metric_period=1,
|
| 403 |
+
grad_scaler=None,
|
| 404 |
+
precision: torch.dtype = torch.float16,
|
| 405 |
+
log_grad_scaler: bool = False,
|
| 406 |
+
):
|
| 407 |
+
"""
|
| 408 |
+
Args:
|
| 409 |
+
model, data_loader, optimizer, gather_metric_period: same as in :class:`SimpleTrainer`.
|
| 410 |
+
grad_scaler: torch GradScaler to automatically scale gradients.
|
| 411 |
+
precision: torch.dtype as the target precision to cast to in computations
|
| 412 |
+
"""
|
| 413 |
+
unsupported = "AMPTrainer does not support single-process multi-device training!"
|
| 414 |
+
if isinstance(model, DistributedDataParallel):
|
| 415 |
+
assert not (model.device_ids and len(model.device_ids) > 1), unsupported
|
| 416 |
+
assert not isinstance(model, DataParallel), unsupported
|
| 417 |
+
|
| 418 |
+
super().__init__(model, data_loader, optimizer, gather_metric_period)
|
| 419 |
+
|
| 420 |
+
if grad_scaler is None:
|
| 421 |
+
from torch.cuda.amp import GradScaler
|
| 422 |
+
|
| 423 |
+
grad_scaler = GradScaler()
|
| 424 |
+
self.grad_scaler = grad_scaler
|
| 425 |
+
self.precision = precision
|
| 426 |
+
self.log_grad_scaler = log_grad_scaler
|
| 427 |
+
|
| 428 |
+
def run_step(self):
|
| 429 |
+
"""
|
| 430 |
+
Implement the AMP training logic.
|
| 431 |
+
"""
|
| 432 |
+
assert self.model.training, "[AMPTrainer] model was changed to eval mode!"
|
| 433 |
+
assert torch.cuda.is_available(), "[AMPTrainer] CUDA is required for AMP training!"
|
| 434 |
+
from torch.cuda.amp import autocast
|
| 435 |
+
|
| 436 |
+
start = time.perf_counter()
|
| 437 |
+
data = next(self._data_loader_iter)
|
| 438 |
+
data_time = time.perf_counter() - start
|
| 439 |
+
|
| 440 |
+
with autocast(dtype=self.precision):
|
| 441 |
+
loss_dict = self.model(data)
|
| 442 |
+
if isinstance(loss_dict, torch.Tensor):
|
| 443 |
+
losses = loss_dict
|
| 444 |
+
loss_dict = {"total_loss": loss_dict}
|
| 445 |
+
else:
|
| 446 |
+
losses = sum(loss_dict.values())
|
| 447 |
+
|
| 448 |
+
self.optimizer.zero_grad()
|
| 449 |
+
self.grad_scaler.scale(losses).backward()
|
| 450 |
+
|
| 451 |
+
if self.log_grad_scaler:
|
| 452 |
+
storage = get_event_storage()
|
| 453 |
+
storage.put_scalar("[metric]grad_scaler", self.grad_scaler.get_scale())
|
| 454 |
+
|
| 455 |
+
self.after_backward()
|
| 456 |
+
|
| 457 |
+
self._write_metrics(loss_dict, data_time)
|
| 458 |
+
|
| 459 |
+
self.grad_scaler.step(self.optimizer)
|
| 460 |
+
self.grad_scaler.update()
|
| 461 |
+
|
| 462 |
+
def state_dict(self):
|
| 463 |
+
ret = super().state_dict()
|
| 464 |
+
ret["grad_scaler"] = self.grad_scaler.state_dict()
|
| 465 |
+
return ret
|
| 466 |
+
|
| 467 |
+
def load_state_dict(self, state_dict):
|
| 468 |
+
super().load_state_dict(state_dict)
|
| 469 |
+
self.grad_scaler.load_state_dict(state_dict["grad_scaler"])
|
RAVE-main/annotator/oneformer/detectron2/evaluation/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
from .cityscapes_evaluation import CityscapesInstanceEvaluator, CityscapesSemSegEvaluator
|
| 3 |
+
from .coco_evaluation import COCOEvaluator
|
| 4 |
+
from .rotated_coco_evaluation import RotatedCOCOEvaluator
|
| 5 |
+
from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context, inference_on_dataset
|
| 6 |
+
from .lvis_evaluation import LVISEvaluator
|
| 7 |
+
from .panoptic_evaluation import COCOPanopticEvaluator
|
| 8 |
+
from .pascal_voc_evaluation import PascalVOCDetectionEvaluator
|
| 9 |
+
from .sem_seg_evaluation import SemSegEvaluator
|
| 10 |
+
from .testing import print_csv_format, verify_results
|
| 11 |
+
|
| 12 |
+
__all__ = [k for k in globals().keys() if not k.startswith("_")]
|
RAVE-main/annotator/oneformer/detectron2/evaluation/cityscapes_evaluation.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import glob
|
| 3 |
+
import logging
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
import tempfile
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
import torch
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
from annotator.oneformer.detectron2.data import MetadataCatalog
|
| 12 |
+
from annotator.oneformer.detectron2.utils import comm
|
| 13 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 14 |
+
|
| 15 |
+
from .evaluator import DatasetEvaluator
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class CityscapesEvaluator(DatasetEvaluator):
|
| 19 |
+
"""
|
| 20 |
+
Base class for evaluation using cityscapes API.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, dataset_name):
|
| 24 |
+
"""
|
| 25 |
+
Args:
|
| 26 |
+
dataset_name (str): the name of the dataset.
|
| 27 |
+
It must have the following metadata associated with it:
|
| 28 |
+
"thing_classes", "gt_dir".
|
| 29 |
+
"""
|
| 30 |
+
self._metadata = MetadataCatalog.get(dataset_name)
|
| 31 |
+
self._cpu_device = torch.device("cpu")
|
| 32 |
+
self._logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
def reset(self):
|
| 35 |
+
self._working_dir = tempfile.TemporaryDirectory(prefix="cityscapes_eval_")
|
| 36 |
+
self._temp_dir = self._working_dir.name
|
| 37 |
+
# All workers will write to the same results directory
|
| 38 |
+
# TODO this does not work in distributed training
|
| 39 |
+
assert (
|
| 40 |
+
comm.get_local_size() == comm.get_world_size()
|
| 41 |
+
), "CityscapesEvaluator currently do not work with multiple machines."
|
| 42 |
+
self._temp_dir = comm.all_gather(self._temp_dir)[0]
|
| 43 |
+
if self._temp_dir != self._working_dir.name:
|
| 44 |
+
self._working_dir.cleanup()
|
| 45 |
+
self._logger.info(
|
| 46 |
+
"Writing cityscapes results to temporary directory {} ...".format(self._temp_dir)
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class CityscapesInstanceEvaluator(CityscapesEvaluator):
|
| 51 |
+
"""
|
| 52 |
+
Evaluate instance segmentation results on cityscapes dataset using cityscapes API.
|
| 53 |
+
|
| 54 |
+
Note:
|
| 55 |
+
* It does not work in multi-machine distributed training.
|
| 56 |
+
* It contains a synchronization, therefore has to be used on all ranks.
|
| 57 |
+
* Only the main process runs evaluation.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def process(self, inputs, outputs):
|
| 61 |
+
from cityscapesscripts.helpers.labels import name2label
|
| 62 |
+
|
| 63 |
+
for input, output in zip(inputs, outputs):
|
| 64 |
+
file_name = input["file_name"]
|
| 65 |
+
basename = os.path.splitext(os.path.basename(file_name))[0]
|
| 66 |
+
pred_txt = os.path.join(self._temp_dir, basename + "_pred.txt")
|
| 67 |
+
|
| 68 |
+
if "instances" in output:
|
| 69 |
+
output = output["instances"].to(self._cpu_device)
|
| 70 |
+
num_instances = len(output)
|
| 71 |
+
with open(pred_txt, "w") as fout:
|
| 72 |
+
for i in range(num_instances):
|
| 73 |
+
pred_class = output.pred_classes[i]
|
| 74 |
+
classes = self._metadata.thing_classes[pred_class]
|
| 75 |
+
class_id = name2label[classes].id
|
| 76 |
+
score = output.scores[i]
|
| 77 |
+
mask = output.pred_masks[i].numpy().astype("uint8")
|
| 78 |
+
png_filename = os.path.join(
|
| 79 |
+
self._temp_dir, basename + "_{}_{}.png".format(i, classes)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
Image.fromarray(mask * 255).save(png_filename)
|
| 83 |
+
fout.write(
|
| 84 |
+
"{} {} {}\n".format(os.path.basename(png_filename), class_id, score)
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
# Cityscapes requires a prediction file for every ground truth image.
|
| 88 |
+
with open(pred_txt, "w") as fout:
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
def evaluate(self):
|
| 92 |
+
"""
|
| 93 |
+
Returns:
|
| 94 |
+
dict: has a key "segm", whose value is a dict of "AP" and "AP50".
|
| 95 |
+
"""
|
| 96 |
+
comm.synchronize()
|
| 97 |
+
if comm.get_rank() > 0:
|
| 98 |
+
return
|
| 99 |
+
import cityscapesscripts.evaluation.evalInstanceLevelSemanticLabeling as cityscapes_eval
|
| 100 |
+
|
| 101 |
+
self._logger.info("Evaluating results under {} ...".format(self._temp_dir))
|
| 102 |
+
|
| 103 |
+
# set some global states in cityscapes evaluation API, before evaluating
|
| 104 |
+
cityscapes_eval.args.predictionPath = os.path.abspath(self._temp_dir)
|
| 105 |
+
cityscapes_eval.args.predictionWalk = None
|
| 106 |
+
cityscapes_eval.args.JSONOutput = False
|
| 107 |
+
cityscapes_eval.args.colorized = False
|
| 108 |
+
cityscapes_eval.args.gtInstancesFile = os.path.join(self._temp_dir, "gtInstances.json")
|
| 109 |
+
|
| 110 |
+
# These lines are adopted from
|
| 111 |
+
# https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalInstanceLevelSemanticLabeling.py # noqa
|
| 112 |
+
gt_dir = PathManager.get_local_path(self._metadata.gt_dir)
|
| 113 |
+
groundTruthImgList = glob.glob(os.path.join(gt_dir, "*", "*_gtFine_instanceIds.png"))
|
| 114 |
+
assert len(
|
| 115 |
+
groundTruthImgList
|
| 116 |
+
), "Cannot find any ground truth images to use for evaluation. Searched for: {}".format(
|
| 117 |
+
cityscapes_eval.args.groundTruthSearch
|
| 118 |
+
)
|
| 119 |
+
predictionImgList = []
|
| 120 |
+
for gt in groundTruthImgList:
|
| 121 |
+
predictionImgList.append(cityscapes_eval.getPrediction(gt, cityscapes_eval.args))
|
| 122 |
+
results = cityscapes_eval.evaluateImgLists(
|
| 123 |
+
predictionImgList, groundTruthImgList, cityscapes_eval.args
|
| 124 |
+
)["averages"]
|
| 125 |
+
|
| 126 |
+
ret = OrderedDict()
|
| 127 |
+
ret["segm"] = {"AP": results["allAp"] * 100, "AP50": results["allAp50%"] * 100}
|
| 128 |
+
self._working_dir.cleanup()
|
| 129 |
+
return ret
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class CityscapesSemSegEvaluator(CityscapesEvaluator):
|
| 133 |
+
"""
|
| 134 |
+
Evaluate semantic segmentation results on cityscapes dataset using cityscapes API.
|
| 135 |
+
|
| 136 |
+
Note:
|
| 137 |
+
* It does not work in multi-machine distributed training.
|
| 138 |
+
* It contains a synchronization, therefore has to be used on all ranks.
|
| 139 |
+
* Only the main process runs evaluation.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
def process(self, inputs, outputs):
|
| 143 |
+
from cityscapesscripts.helpers.labels import trainId2label
|
| 144 |
+
|
| 145 |
+
for input, output in zip(inputs, outputs):
|
| 146 |
+
file_name = input["file_name"]
|
| 147 |
+
basename = os.path.splitext(os.path.basename(file_name))[0]
|
| 148 |
+
pred_filename = os.path.join(self._temp_dir, basename + "_pred.png")
|
| 149 |
+
|
| 150 |
+
output = output["sem_seg"].argmax(dim=0).to(self._cpu_device).numpy()
|
| 151 |
+
pred = 255 * np.ones(output.shape, dtype=np.uint8)
|
| 152 |
+
for train_id, label in trainId2label.items():
|
| 153 |
+
if label.ignoreInEval:
|
| 154 |
+
continue
|
| 155 |
+
pred[output == train_id] = label.id
|
| 156 |
+
Image.fromarray(pred).save(pred_filename)
|
| 157 |
+
|
| 158 |
+
def evaluate(self):
|
| 159 |
+
comm.synchronize()
|
| 160 |
+
if comm.get_rank() > 0:
|
| 161 |
+
return
|
| 162 |
+
# Load the Cityscapes eval script *after* setting the required env var,
|
| 163 |
+
# since the script reads CITYSCAPES_DATASET into global variables at load time.
|
| 164 |
+
import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as cityscapes_eval
|
| 165 |
+
|
| 166 |
+
self._logger.info("Evaluating results under {} ...".format(self._temp_dir))
|
| 167 |
+
|
| 168 |
+
# set some global states in cityscapes evaluation API, before evaluating
|
| 169 |
+
cityscapes_eval.args.predictionPath = os.path.abspath(self._temp_dir)
|
| 170 |
+
cityscapes_eval.args.predictionWalk = None
|
| 171 |
+
cityscapes_eval.args.JSONOutput = False
|
| 172 |
+
cityscapes_eval.args.colorized = False
|
| 173 |
+
|
| 174 |
+
# These lines are adopted from
|
| 175 |
+
# https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalPixelLevelSemanticLabeling.py # noqa
|
| 176 |
+
gt_dir = PathManager.get_local_path(self._metadata.gt_dir)
|
| 177 |
+
groundTruthImgList = glob.glob(os.path.join(gt_dir, "*", "*_gtFine_labelIds.png"))
|
| 178 |
+
assert len(
|
| 179 |
+
groundTruthImgList
|
| 180 |
+
), "Cannot find any ground truth images to use for evaluation. Searched for: {}".format(
|
| 181 |
+
cityscapes_eval.args.groundTruthSearch
|
| 182 |
+
)
|
| 183 |
+
predictionImgList = []
|
| 184 |
+
for gt in groundTruthImgList:
|
| 185 |
+
predictionImgList.append(cityscapes_eval.getPrediction(cityscapes_eval.args, gt))
|
| 186 |
+
results = cityscapes_eval.evaluateImgLists(
|
| 187 |
+
predictionImgList, groundTruthImgList, cityscapes_eval.args
|
| 188 |
+
)
|
| 189 |
+
ret = OrderedDict()
|
| 190 |
+
ret["sem_seg"] = {
|
| 191 |
+
"IoU": 100.0 * results["averageScoreClasses"],
|
| 192 |
+
"iIoU": 100.0 * results["averageScoreInstClasses"],
|
| 193 |
+
"IoU_sup": 100.0 * results["averageScoreCategories"],
|
| 194 |
+
"iIoU_sup": 100.0 * results["averageScoreInstCategories"],
|
| 195 |
+
}
|
| 196 |
+
self._working_dir.cleanup()
|
| 197 |
+
return ret
|
RAVE-main/annotator/oneformer/detectron2/evaluation/coco_evaluation.py
ADDED
|
@@ -0,0 +1,722 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import contextlib
|
| 3 |
+
import copy
|
| 4 |
+
import io
|
| 5 |
+
import itertools
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import numpy as np
|
| 9 |
+
import os
|
| 10 |
+
import pickle
|
| 11 |
+
from collections import OrderedDict
|
| 12 |
+
import annotator.oneformer.pycocotools.mask as mask_util
|
| 13 |
+
import torch
|
| 14 |
+
from annotator.oneformer.pycocotools.coco import COCO
|
| 15 |
+
from annotator.oneformer.pycocotools.cocoeval import COCOeval
|
| 16 |
+
from tabulate import tabulate
|
| 17 |
+
|
| 18 |
+
import annotator.oneformer.detectron2.utils.comm as comm
|
| 19 |
+
from annotator.oneformer.detectron2.config import CfgNode
|
| 20 |
+
from annotator.oneformer.detectron2.data import MetadataCatalog
|
| 21 |
+
from annotator.oneformer.detectron2.data.datasets.coco import convert_to_coco_json
|
| 22 |
+
from annotator.oneformer.detectron2.structures import Boxes, BoxMode, pairwise_iou
|
| 23 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 24 |
+
from annotator.oneformer.detectron2.utils.logger import create_small_table
|
| 25 |
+
|
| 26 |
+
from .evaluator import DatasetEvaluator
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from annotator.oneformer.detectron2.evaluation.fast_eval_api import COCOeval_opt
|
| 30 |
+
except ImportError:
|
| 31 |
+
COCOeval_opt = COCOeval
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class COCOEvaluator(DatasetEvaluator):
|
| 35 |
+
"""
|
| 36 |
+
Evaluate AR for object proposals, AP for instance detection/segmentation, AP
|
| 37 |
+
for keypoint detection outputs using COCO's metrics.
|
| 38 |
+
See http://cocodataset.org/#detection-eval and
|
| 39 |
+
http://cocodataset.org/#keypoints-eval to understand its metrics.
|
| 40 |
+
The metrics range from 0 to 100 (instead of 0 to 1), where a -1 or NaN means
|
| 41 |
+
the metric cannot be computed (e.g. due to no predictions made).
|
| 42 |
+
|
| 43 |
+
In addition to COCO, this evaluator is able to support any bounding box detection,
|
| 44 |
+
instance segmentation, or keypoint detection dataset.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
dataset_name,
|
| 50 |
+
tasks=None,
|
| 51 |
+
distributed=True,
|
| 52 |
+
output_dir=None,
|
| 53 |
+
*,
|
| 54 |
+
max_dets_per_image=None,
|
| 55 |
+
use_fast_impl=True,
|
| 56 |
+
kpt_oks_sigmas=(),
|
| 57 |
+
allow_cached_coco=True,
|
| 58 |
+
):
|
| 59 |
+
"""
|
| 60 |
+
Args:
|
| 61 |
+
dataset_name (str): name of the dataset to be evaluated.
|
| 62 |
+
It must have either the following corresponding metadata:
|
| 63 |
+
|
| 64 |
+
"json_file": the path to the COCO format annotation
|
| 65 |
+
|
| 66 |
+
Or it must be in detectron2's standard dataset format
|
| 67 |
+
so it can be converted to COCO format automatically.
|
| 68 |
+
tasks (tuple[str]): tasks that can be evaluated under the given
|
| 69 |
+
configuration. A task is one of "bbox", "segm", "keypoints".
|
| 70 |
+
By default, will infer this automatically from predictions.
|
| 71 |
+
distributed (True): if True, will collect results from all ranks and run evaluation
|
| 72 |
+
in the main process.
|
| 73 |
+
Otherwise, will only evaluate the results in the current process.
|
| 74 |
+
output_dir (str): optional, an output directory to dump all
|
| 75 |
+
results predicted on the dataset. The dump contains two files:
|
| 76 |
+
|
| 77 |
+
1. "instances_predictions.pth" a file that can be loaded with `torch.load` and
|
| 78 |
+
contains all the results in the format they are produced by the model.
|
| 79 |
+
2. "coco_instances_results.json" a json file in COCO's result format.
|
| 80 |
+
max_dets_per_image (int): limit on the maximum number of detections per image.
|
| 81 |
+
By default in COCO, this limit is to 100, but this can be customized
|
| 82 |
+
to be greater, as is needed in evaluation metrics AP fixed and AP pool
|
| 83 |
+
(see https://arxiv.org/pdf/2102.01066.pdf)
|
| 84 |
+
This doesn't affect keypoint evaluation.
|
| 85 |
+
use_fast_impl (bool): use a fast but **unofficial** implementation to compute AP.
|
| 86 |
+
Although the results should be very close to the official implementation in COCO
|
| 87 |
+
API, it is still recommended to compute results with the official API for use in
|
| 88 |
+
papers. The faster implementation also uses more RAM.
|
| 89 |
+
kpt_oks_sigmas (list[float]): The sigmas used to calculate keypoint OKS.
|
| 90 |
+
See http://cocodataset.org/#keypoints-eval
|
| 91 |
+
When empty, it will use the defaults in COCO.
|
| 92 |
+
Otherwise it should be the same length as ROI_KEYPOINT_HEAD.NUM_KEYPOINTS.
|
| 93 |
+
allow_cached_coco (bool): Whether to use cached coco json from previous validation
|
| 94 |
+
runs. You should set this to False if you need to use different validation data.
|
| 95 |
+
Defaults to True.
|
| 96 |
+
"""
|
| 97 |
+
self._logger = logging.getLogger(__name__)
|
| 98 |
+
self._distributed = distributed
|
| 99 |
+
self._output_dir = output_dir
|
| 100 |
+
|
| 101 |
+
if use_fast_impl and (COCOeval_opt is COCOeval):
|
| 102 |
+
self._logger.info("Fast COCO eval is not built. Falling back to official COCO eval.")
|
| 103 |
+
use_fast_impl = False
|
| 104 |
+
self._use_fast_impl = use_fast_impl
|
| 105 |
+
|
| 106 |
+
# COCOeval requires the limit on the number of detections per image (maxDets) to be a list
|
| 107 |
+
# with at least 3 elements. The default maxDets in COCOeval is [1, 10, 100], in which the
|
| 108 |
+
# 3rd element (100) is used as the limit on the number of detections per image when
|
| 109 |
+
# evaluating AP. COCOEvaluator expects an integer for max_dets_per_image, so for COCOeval,
|
| 110 |
+
# we reformat max_dets_per_image into [1, 10, max_dets_per_image], based on the defaults.
|
| 111 |
+
if max_dets_per_image is None:
|
| 112 |
+
max_dets_per_image = [1, 10, 100]
|
| 113 |
+
else:
|
| 114 |
+
max_dets_per_image = [1, 10, max_dets_per_image]
|
| 115 |
+
self._max_dets_per_image = max_dets_per_image
|
| 116 |
+
|
| 117 |
+
if tasks is not None and isinstance(tasks, CfgNode):
|
| 118 |
+
kpt_oks_sigmas = (
|
| 119 |
+
tasks.TEST.KEYPOINT_OKS_SIGMAS if not kpt_oks_sigmas else kpt_oks_sigmas
|
| 120 |
+
)
|
| 121 |
+
self._logger.warn(
|
| 122 |
+
"COCO Evaluator instantiated using config, this is deprecated behavior."
|
| 123 |
+
" Please pass in explicit arguments instead."
|
| 124 |
+
)
|
| 125 |
+
self._tasks = None # Infering it from predictions should be better
|
| 126 |
+
else:
|
| 127 |
+
self._tasks = tasks
|
| 128 |
+
|
| 129 |
+
self._cpu_device = torch.device("cpu")
|
| 130 |
+
|
| 131 |
+
self._metadata = MetadataCatalog.get(dataset_name)
|
| 132 |
+
if not hasattr(self._metadata, "json_file"):
|
| 133 |
+
if output_dir is None:
|
| 134 |
+
raise ValueError(
|
| 135 |
+
"output_dir must be provided to COCOEvaluator "
|
| 136 |
+
"for datasets not in COCO format."
|
| 137 |
+
)
|
| 138 |
+
self._logger.info(f"Trying to convert '{dataset_name}' to COCO format ...")
|
| 139 |
+
|
| 140 |
+
cache_path = os.path.join(output_dir, f"{dataset_name}_coco_format.json")
|
| 141 |
+
self._metadata.json_file = cache_path
|
| 142 |
+
convert_to_coco_json(dataset_name, cache_path, allow_cached=allow_cached_coco)
|
| 143 |
+
|
| 144 |
+
json_file = PathManager.get_local_path(self._metadata.json_file)
|
| 145 |
+
with contextlib.redirect_stdout(io.StringIO()):
|
| 146 |
+
self._coco_api = COCO(json_file)
|
| 147 |
+
|
| 148 |
+
# Test set json files do not contain annotations (evaluation must be
|
| 149 |
+
# performed using the COCO evaluation server).
|
| 150 |
+
self._do_evaluation = "annotations" in self._coco_api.dataset
|
| 151 |
+
if self._do_evaluation:
|
| 152 |
+
self._kpt_oks_sigmas = kpt_oks_sigmas
|
| 153 |
+
|
| 154 |
+
def reset(self):
|
| 155 |
+
self._predictions = []
|
| 156 |
+
|
| 157 |
+
def process(self, inputs, outputs):
|
| 158 |
+
"""
|
| 159 |
+
Args:
|
| 160 |
+
inputs: the inputs to a COCO model (e.g., GeneralizedRCNN).
|
| 161 |
+
It is a list of dict. Each dict corresponds to an image and
|
| 162 |
+
contains keys like "height", "width", "file_name", "image_id".
|
| 163 |
+
outputs: the outputs of a COCO model. It is a list of dicts with key
|
| 164 |
+
"instances" that contains :class:`Instances`.
|
| 165 |
+
"""
|
| 166 |
+
for input, output in zip(inputs, outputs):
|
| 167 |
+
prediction = {"image_id": input["image_id"]}
|
| 168 |
+
|
| 169 |
+
if "instances" in output:
|
| 170 |
+
instances = output["instances"].to(self._cpu_device)
|
| 171 |
+
prediction["instances"] = instances_to_coco_json(instances, input["image_id"])
|
| 172 |
+
if "proposals" in output:
|
| 173 |
+
prediction["proposals"] = output["proposals"].to(self._cpu_device)
|
| 174 |
+
if len(prediction) > 1:
|
| 175 |
+
self._predictions.append(prediction)
|
| 176 |
+
|
| 177 |
+
def evaluate(self, img_ids=None):
|
| 178 |
+
"""
|
| 179 |
+
Args:
|
| 180 |
+
img_ids: a list of image IDs to evaluate on. Default to None for the whole dataset
|
| 181 |
+
"""
|
| 182 |
+
if self._distributed:
|
| 183 |
+
comm.synchronize()
|
| 184 |
+
predictions = comm.gather(self._predictions, dst=0)
|
| 185 |
+
predictions = list(itertools.chain(*predictions))
|
| 186 |
+
|
| 187 |
+
if not comm.is_main_process():
|
| 188 |
+
return {}
|
| 189 |
+
else:
|
| 190 |
+
predictions = self._predictions
|
| 191 |
+
|
| 192 |
+
if len(predictions) == 0:
|
| 193 |
+
self._logger.warning("[COCOEvaluator] Did not receive valid predictions.")
|
| 194 |
+
return {}
|
| 195 |
+
|
| 196 |
+
if self._output_dir:
|
| 197 |
+
PathManager.mkdirs(self._output_dir)
|
| 198 |
+
file_path = os.path.join(self._output_dir, "instances_predictions.pth")
|
| 199 |
+
with PathManager.open(file_path, "wb") as f:
|
| 200 |
+
torch.save(predictions, f)
|
| 201 |
+
|
| 202 |
+
self._results = OrderedDict()
|
| 203 |
+
if "proposals" in predictions[0]:
|
| 204 |
+
self._eval_box_proposals(predictions)
|
| 205 |
+
if "instances" in predictions[0]:
|
| 206 |
+
self._eval_predictions(predictions, img_ids=img_ids)
|
| 207 |
+
# Copy so the caller can do whatever with results
|
| 208 |
+
return copy.deepcopy(self._results)
|
| 209 |
+
|
| 210 |
+
def _tasks_from_predictions(self, predictions):
|
| 211 |
+
"""
|
| 212 |
+
Get COCO API "tasks" (i.e. iou_type) from COCO-format predictions.
|
| 213 |
+
"""
|
| 214 |
+
tasks = {"bbox"}
|
| 215 |
+
for pred in predictions:
|
| 216 |
+
if "segmentation" in pred:
|
| 217 |
+
tasks.add("segm")
|
| 218 |
+
if "keypoints" in pred:
|
| 219 |
+
tasks.add("keypoints")
|
| 220 |
+
return sorted(tasks)
|
| 221 |
+
|
| 222 |
+
def _eval_predictions(self, predictions, img_ids=None):
|
| 223 |
+
"""
|
| 224 |
+
Evaluate predictions. Fill self._results with the metrics of the tasks.
|
| 225 |
+
"""
|
| 226 |
+
self._logger.info("Preparing results for COCO format ...")
|
| 227 |
+
coco_results = list(itertools.chain(*[x["instances"] for x in predictions]))
|
| 228 |
+
tasks = self._tasks or self._tasks_from_predictions(coco_results)
|
| 229 |
+
|
| 230 |
+
# unmap the category ids for COCO
|
| 231 |
+
if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"):
|
| 232 |
+
dataset_id_to_contiguous_id = self._metadata.thing_dataset_id_to_contiguous_id
|
| 233 |
+
all_contiguous_ids = list(dataset_id_to_contiguous_id.values())
|
| 234 |
+
num_classes = len(all_contiguous_ids)
|
| 235 |
+
assert min(all_contiguous_ids) == 0 and max(all_contiguous_ids) == num_classes - 1
|
| 236 |
+
|
| 237 |
+
reverse_id_mapping = {v: k for k, v in dataset_id_to_contiguous_id.items()}
|
| 238 |
+
for result in coco_results:
|
| 239 |
+
category_id = result["category_id"]
|
| 240 |
+
assert category_id < num_classes, (
|
| 241 |
+
f"A prediction has class={category_id}, "
|
| 242 |
+
f"but the dataset only has {num_classes} classes and "
|
| 243 |
+
f"predicted class id should be in [0, {num_classes - 1}]."
|
| 244 |
+
)
|
| 245 |
+
result["category_id"] = reverse_id_mapping[category_id]
|
| 246 |
+
|
| 247 |
+
if self._output_dir:
|
| 248 |
+
file_path = os.path.join(self._output_dir, "coco_instances_results.json")
|
| 249 |
+
self._logger.info("Saving results to {}".format(file_path))
|
| 250 |
+
with PathManager.open(file_path, "w") as f:
|
| 251 |
+
f.write(json.dumps(coco_results))
|
| 252 |
+
f.flush()
|
| 253 |
+
|
| 254 |
+
if not self._do_evaluation:
|
| 255 |
+
self._logger.info("Annotations are not available for evaluation.")
|
| 256 |
+
return
|
| 257 |
+
|
| 258 |
+
self._logger.info(
|
| 259 |
+
"Evaluating predictions with {} COCO API...".format(
|
| 260 |
+
"unofficial" if self._use_fast_impl else "official"
|
| 261 |
+
)
|
| 262 |
+
)
|
| 263 |
+
for task in sorted(tasks):
|
| 264 |
+
assert task in {"bbox", "segm", "keypoints"}, f"Got unknown task: {task}!"
|
| 265 |
+
coco_eval = (
|
| 266 |
+
_evaluate_predictions_on_coco(
|
| 267 |
+
self._coco_api,
|
| 268 |
+
coco_results,
|
| 269 |
+
task,
|
| 270 |
+
kpt_oks_sigmas=self._kpt_oks_sigmas,
|
| 271 |
+
cocoeval_fn=COCOeval_opt if self._use_fast_impl else COCOeval,
|
| 272 |
+
img_ids=img_ids,
|
| 273 |
+
max_dets_per_image=self._max_dets_per_image,
|
| 274 |
+
)
|
| 275 |
+
if len(coco_results) > 0
|
| 276 |
+
else None # cocoapi does not handle empty results very well
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
res = self._derive_coco_results(
|
| 280 |
+
coco_eval, task, class_names=self._metadata.get("thing_classes")
|
| 281 |
+
)
|
| 282 |
+
self._results[task] = res
|
| 283 |
+
|
| 284 |
+
def _eval_box_proposals(self, predictions):
|
| 285 |
+
"""
|
| 286 |
+
Evaluate the box proposals in predictions.
|
| 287 |
+
Fill self._results with the metrics for "box_proposals" task.
|
| 288 |
+
"""
|
| 289 |
+
if self._output_dir:
|
| 290 |
+
# Saving generated box proposals to file.
|
| 291 |
+
# Predicted box_proposals are in XYXY_ABS mode.
|
| 292 |
+
bbox_mode = BoxMode.XYXY_ABS.value
|
| 293 |
+
ids, boxes, objectness_logits = [], [], []
|
| 294 |
+
for prediction in predictions:
|
| 295 |
+
ids.append(prediction["image_id"])
|
| 296 |
+
boxes.append(prediction["proposals"].proposal_boxes.tensor.numpy())
|
| 297 |
+
objectness_logits.append(prediction["proposals"].objectness_logits.numpy())
|
| 298 |
+
|
| 299 |
+
proposal_data = {
|
| 300 |
+
"boxes": boxes,
|
| 301 |
+
"objectness_logits": objectness_logits,
|
| 302 |
+
"ids": ids,
|
| 303 |
+
"bbox_mode": bbox_mode,
|
| 304 |
+
}
|
| 305 |
+
with PathManager.open(os.path.join(self._output_dir, "box_proposals.pkl"), "wb") as f:
|
| 306 |
+
pickle.dump(proposal_data, f)
|
| 307 |
+
|
| 308 |
+
if not self._do_evaluation:
|
| 309 |
+
self._logger.info("Annotations are not available for evaluation.")
|
| 310 |
+
return
|
| 311 |
+
|
| 312 |
+
self._logger.info("Evaluating bbox proposals ...")
|
| 313 |
+
res = {}
|
| 314 |
+
areas = {"all": "", "small": "s", "medium": "m", "large": "l"}
|
| 315 |
+
for limit in [100, 1000]:
|
| 316 |
+
for area, suffix in areas.items():
|
| 317 |
+
stats = _evaluate_box_proposals(predictions, self._coco_api, area=area, limit=limit)
|
| 318 |
+
key = "AR{}@{:d}".format(suffix, limit)
|
| 319 |
+
res[key] = float(stats["ar"].item() * 100)
|
| 320 |
+
self._logger.info("Proposal metrics: \n" + create_small_table(res))
|
| 321 |
+
self._results["box_proposals"] = res
|
| 322 |
+
|
| 323 |
+
def _derive_coco_results(self, coco_eval, iou_type, class_names=None):
|
| 324 |
+
"""
|
| 325 |
+
Derive the desired score numbers from summarized COCOeval.
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
coco_eval (None or COCOEval): None represents no predictions from model.
|
| 329 |
+
iou_type (str):
|
| 330 |
+
class_names (None or list[str]): if provided, will use it to predict
|
| 331 |
+
per-category AP.
|
| 332 |
+
|
| 333 |
+
Returns:
|
| 334 |
+
a dict of {metric name: score}
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
metrics = {
|
| 338 |
+
"bbox": ["AP", "AP50", "AP75", "APs", "APm", "APl"],
|
| 339 |
+
"segm": ["AP", "AP50", "AP75", "APs", "APm", "APl"],
|
| 340 |
+
"keypoints": ["AP", "AP50", "AP75", "APm", "APl"],
|
| 341 |
+
}[iou_type]
|
| 342 |
+
|
| 343 |
+
if coco_eval is None:
|
| 344 |
+
self._logger.warn("No predictions from the model!")
|
| 345 |
+
return {metric: float("nan") for metric in metrics}
|
| 346 |
+
|
| 347 |
+
# the standard metrics
|
| 348 |
+
results = {
|
| 349 |
+
metric: float(coco_eval.stats[idx] * 100 if coco_eval.stats[idx] >= 0 else "nan")
|
| 350 |
+
for idx, metric in enumerate(metrics)
|
| 351 |
+
}
|
| 352 |
+
self._logger.info(
|
| 353 |
+
"Evaluation results for {}: \n".format(iou_type) + create_small_table(results)
|
| 354 |
+
)
|
| 355 |
+
if not np.isfinite(sum(results.values())):
|
| 356 |
+
self._logger.info("Some metrics cannot be computed and is shown as NaN.")
|
| 357 |
+
|
| 358 |
+
if class_names is None or len(class_names) <= 1:
|
| 359 |
+
return results
|
| 360 |
+
# Compute per-category AP
|
| 361 |
+
# from https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L222-L252 # noqa
|
| 362 |
+
precisions = coco_eval.eval["precision"]
|
| 363 |
+
# precision has dims (iou, recall, cls, area range, max dets)
|
| 364 |
+
assert len(class_names) == precisions.shape[2]
|
| 365 |
+
|
| 366 |
+
results_per_category = []
|
| 367 |
+
for idx, name in enumerate(class_names):
|
| 368 |
+
# area range index 0: all area ranges
|
| 369 |
+
# max dets index -1: typically 100 per image
|
| 370 |
+
precision = precisions[:, :, idx, 0, -1]
|
| 371 |
+
precision = precision[precision > -1]
|
| 372 |
+
ap = np.mean(precision) if precision.size else float("nan")
|
| 373 |
+
results_per_category.append(("{}".format(name), float(ap * 100)))
|
| 374 |
+
|
| 375 |
+
# tabulate it
|
| 376 |
+
N_COLS = min(6, len(results_per_category) * 2)
|
| 377 |
+
results_flatten = list(itertools.chain(*results_per_category))
|
| 378 |
+
results_2d = itertools.zip_longest(*[results_flatten[i::N_COLS] for i in range(N_COLS)])
|
| 379 |
+
table = tabulate(
|
| 380 |
+
results_2d,
|
| 381 |
+
tablefmt="pipe",
|
| 382 |
+
floatfmt=".3f",
|
| 383 |
+
headers=["category", "AP"] * (N_COLS // 2),
|
| 384 |
+
numalign="left",
|
| 385 |
+
)
|
| 386 |
+
self._logger.info("Per-category {} AP: \n".format(iou_type) + table)
|
| 387 |
+
|
| 388 |
+
results.update({"AP-" + name: ap for name, ap in results_per_category})
|
| 389 |
+
return results
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def instances_to_coco_json(instances, img_id):
|
| 393 |
+
"""
|
| 394 |
+
Dump an "Instances" object to a COCO-format json that's used for evaluation.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
instances (Instances):
|
| 398 |
+
img_id (int): the image id
|
| 399 |
+
|
| 400 |
+
Returns:
|
| 401 |
+
list[dict]: list of json annotations in COCO format.
|
| 402 |
+
"""
|
| 403 |
+
num_instance = len(instances)
|
| 404 |
+
if num_instance == 0:
|
| 405 |
+
return []
|
| 406 |
+
|
| 407 |
+
boxes = instances.pred_boxes.tensor.numpy()
|
| 408 |
+
boxes = BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
|
| 409 |
+
boxes = boxes.tolist()
|
| 410 |
+
scores = instances.scores.tolist()
|
| 411 |
+
classes = instances.pred_classes.tolist()
|
| 412 |
+
|
| 413 |
+
has_mask = instances.has("pred_masks")
|
| 414 |
+
if has_mask:
|
| 415 |
+
# use RLE to encode the masks, because they are too large and takes memory
|
| 416 |
+
# since this evaluator stores outputs of the entire dataset
|
| 417 |
+
rles = [
|
| 418 |
+
mask_util.encode(np.array(mask[:, :, None], order="F", dtype="uint8"))[0]
|
| 419 |
+
for mask in instances.pred_masks
|
| 420 |
+
]
|
| 421 |
+
for rle in rles:
|
| 422 |
+
# "counts" is an array encoded by mask_util as a byte-stream. Python3's
|
| 423 |
+
# json writer which always produces strings cannot serialize a bytestream
|
| 424 |
+
# unless you decode it. Thankfully, utf-8 works out (which is also what
|
| 425 |
+
# the annotator.oneformer.pycocotools/_mask.pyx does).
|
| 426 |
+
rle["counts"] = rle["counts"].decode("utf-8")
|
| 427 |
+
|
| 428 |
+
has_keypoints = instances.has("pred_keypoints")
|
| 429 |
+
if has_keypoints:
|
| 430 |
+
keypoints = instances.pred_keypoints
|
| 431 |
+
|
| 432 |
+
results = []
|
| 433 |
+
for k in range(num_instance):
|
| 434 |
+
result = {
|
| 435 |
+
"image_id": img_id,
|
| 436 |
+
"category_id": classes[k],
|
| 437 |
+
"bbox": boxes[k],
|
| 438 |
+
"score": scores[k],
|
| 439 |
+
}
|
| 440 |
+
if has_mask:
|
| 441 |
+
result["segmentation"] = rles[k]
|
| 442 |
+
if has_keypoints:
|
| 443 |
+
# In COCO annotations,
|
| 444 |
+
# keypoints coordinates are pixel indices.
|
| 445 |
+
# However our predictions are floating point coordinates.
|
| 446 |
+
# Therefore we subtract 0.5 to be consistent with the annotation format.
|
| 447 |
+
# This is the inverse of data loading logic in `datasets/coco.py`.
|
| 448 |
+
keypoints[k][:, :2] -= 0.5
|
| 449 |
+
result["keypoints"] = keypoints[k].flatten().tolist()
|
| 450 |
+
results.append(result)
|
| 451 |
+
return results
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
# inspired from Detectron:
|
| 455 |
+
# https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L255 # noqa
|
| 456 |
+
def _evaluate_box_proposals(dataset_predictions, coco_api, thresholds=None, area="all", limit=None):
|
| 457 |
+
"""
|
| 458 |
+
Evaluate detection proposal recall metrics. This function is a much
|
| 459 |
+
faster alternative to the official COCO API recall evaluation code. However,
|
| 460 |
+
it produces slightly different results.
|
| 461 |
+
"""
|
| 462 |
+
# Record max overlap value for each gt box
|
| 463 |
+
# Return vector of overlap values
|
| 464 |
+
areas = {
|
| 465 |
+
"all": 0,
|
| 466 |
+
"small": 1,
|
| 467 |
+
"medium": 2,
|
| 468 |
+
"large": 3,
|
| 469 |
+
"96-128": 4,
|
| 470 |
+
"128-256": 5,
|
| 471 |
+
"256-512": 6,
|
| 472 |
+
"512-inf": 7,
|
| 473 |
+
}
|
| 474 |
+
area_ranges = [
|
| 475 |
+
[0**2, 1e5**2], # all
|
| 476 |
+
[0**2, 32**2], # small
|
| 477 |
+
[32**2, 96**2], # medium
|
| 478 |
+
[96**2, 1e5**2], # large
|
| 479 |
+
[96**2, 128**2], # 96-128
|
| 480 |
+
[128**2, 256**2], # 128-256
|
| 481 |
+
[256**2, 512**2], # 256-512
|
| 482 |
+
[512**2, 1e5**2],
|
| 483 |
+
] # 512-inf
|
| 484 |
+
assert area in areas, "Unknown area range: {}".format(area)
|
| 485 |
+
area_range = area_ranges[areas[area]]
|
| 486 |
+
gt_overlaps = []
|
| 487 |
+
num_pos = 0
|
| 488 |
+
|
| 489 |
+
for prediction_dict in dataset_predictions:
|
| 490 |
+
predictions = prediction_dict["proposals"]
|
| 491 |
+
|
| 492 |
+
# sort predictions in descending order
|
| 493 |
+
# TODO maybe remove this and make it explicit in the documentation
|
| 494 |
+
inds = predictions.objectness_logits.sort(descending=True)[1]
|
| 495 |
+
predictions = predictions[inds]
|
| 496 |
+
|
| 497 |
+
ann_ids = coco_api.getAnnIds(imgIds=prediction_dict["image_id"])
|
| 498 |
+
anno = coco_api.loadAnns(ann_ids)
|
| 499 |
+
gt_boxes = [
|
| 500 |
+
BoxMode.convert(obj["bbox"], BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)
|
| 501 |
+
for obj in anno
|
| 502 |
+
if obj["iscrowd"] == 0
|
| 503 |
+
]
|
| 504 |
+
gt_boxes = torch.as_tensor(gt_boxes).reshape(-1, 4) # guard against no boxes
|
| 505 |
+
gt_boxes = Boxes(gt_boxes)
|
| 506 |
+
gt_areas = torch.as_tensor([obj["area"] for obj in anno if obj["iscrowd"] == 0])
|
| 507 |
+
|
| 508 |
+
if len(gt_boxes) == 0 or len(predictions) == 0:
|
| 509 |
+
continue
|
| 510 |
+
|
| 511 |
+
valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1])
|
| 512 |
+
gt_boxes = gt_boxes[valid_gt_inds]
|
| 513 |
+
|
| 514 |
+
num_pos += len(gt_boxes)
|
| 515 |
+
|
| 516 |
+
if len(gt_boxes) == 0:
|
| 517 |
+
continue
|
| 518 |
+
|
| 519 |
+
if limit is not None and len(predictions) > limit:
|
| 520 |
+
predictions = predictions[:limit]
|
| 521 |
+
|
| 522 |
+
overlaps = pairwise_iou(predictions.proposal_boxes, gt_boxes)
|
| 523 |
+
|
| 524 |
+
_gt_overlaps = torch.zeros(len(gt_boxes))
|
| 525 |
+
for j in range(min(len(predictions), len(gt_boxes))):
|
| 526 |
+
# find which proposal box maximally covers each gt box
|
| 527 |
+
# and get the iou amount of coverage for each gt box
|
| 528 |
+
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
|
| 529 |
+
|
| 530 |
+
# find which gt box is 'best' covered (i.e. 'best' = most iou)
|
| 531 |
+
gt_ovr, gt_ind = max_overlaps.max(dim=0)
|
| 532 |
+
assert gt_ovr >= 0
|
| 533 |
+
# find the proposal box that covers the best covered gt box
|
| 534 |
+
box_ind = argmax_overlaps[gt_ind]
|
| 535 |
+
# record the iou coverage of this gt box
|
| 536 |
+
_gt_overlaps[j] = overlaps[box_ind, gt_ind]
|
| 537 |
+
assert _gt_overlaps[j] == gt_ovr
|
| 538 |
+
# mark the proposal box and the gt box as used
|
| 539 |
+
overlaps[box_ind, :] = -1
|
| 540 |
+
overlaps[:, gt_ind] = -1
|
| 541 |
+
|
| 542 |
+
# append recorded iou coverage level
|
| 543 |
+
gt_overlaps.append(_gt_overlaps)
|
| 544 |
+
gt_overlaps = (
|
| 545 |
+
torch.cat(gt_overlaps, dim=0) if len(gt_overlaps) else torch.zeros(0, dtype=torch.float32)
|
| 546 |
+
)
|
| 547 |
+
gt_overlaps, _ = torch.sort(gt_overlaps)
|
| 548 |
+
|
| 549 |
+
if thresholds is None:
|
| 550 |
+
step = 0.05
|
| 551 |
+
thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32)
|
| 552 |
+
recalls = torch.zeros_like(thresholds)
|
| 553 |
+
# compute recall for each iou threshold
|
| 554 |
+
for i, t in enumerate(thresholds):
|
| 555 |
+
recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos)
|
| 556 |
+
# ar = 2 * np.trapz(recalls, thresholds)
|
| 557 |
+
ar = recalls.mean()
|
| 558 |
+
return {
|
| 559 |
+
"ar": ar,
|
| 560 |
+
"recalls": recalls,
|
| 561 |
+
"thresholds": thresholds,
|
| 562 |
+
"gt_overlaps": gt_overlaps,
|
| 563 |
+
"num_pos": num_pos,
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def _evaluate_predictions_on_coco(
|
| 568 |
+
coco_gt,
|
| 569 |
+
coco_results,
|
| 570 |
+
iou_type,
|
| 571 |
+
kpt_oks_sigmas=None,
|
| 572 |
+
cocoeval_fn=COCOeval_opt,
|
| 573 |
+
img_ids=None,
|
| 574 |
+
max_dets_per_image=None,
|
| 575 |
+
):
|
| 576 |
+
"""
|
| 577 |
+
Evaluate the coco results using COCOEval API.
|
| 578 |
+
"""
|
| 579 |
+
assert len(coco_results) > 0
|
| 580 |
+
|
| 581 |
+
if iou_type == "segm":
|
| 582 |
+
coco_results = copy.deepcopy(coco_results)
|
| 583 |
+
# When evaluating mask AP, if the results contain bbox, cocoapi will
|
| 584 |
+
# use the box area as the area of the instance, instead of the mask area.
|
| 585 |
+
# This leads to a different definition of small/medium/large.
|
| 586 |
+
# We remove the bbox field to let mask AP use mask area.
|
| 587 |
+
for c in coco_results:
|
| 588 |
+
c.pop("bbox", None)
|
| 589 |
+
|
| 590 |
+
coco_dt = coco_gt.loadRes(coco_results)
|
| 591 |
+
coco_eval = cocoeval_fn(coco_gt, coco_dt, iou_type)
|
| 592 |
+
# For COCO, the default max_dets_per_image is [1, 10, 100].
|
| 593 |
+
if max_dets_per_image is None:
|
| 594 |
+
max_dets_per_image = [1, 10, 100] # Default from COCOEval
|
| 595 |
+
else:
|
| 596 |
+
assert (
|
| 597 |
+
len(max_dets_per_image) >= 3
|
| 598 |
+
), "COCOeval requires maxDets (and max_dets_per_image) to have length at least 3"
|
| 599 |
+
# In the case that user supplies a custom input for max_dets_per_image,
|
| 600 |
+
# apply COCOevalMaxDets to evaluate AP with the custom input.
|
| 601 |
+
if max_dets_per_image[2] != 100:
|
| 602 |
+
coco_eval = COCOevalMaxDets(coco_gt, coco_dt, iou_type)
|
| 603 |
+
if iou_type != "keypoints":
|
| 604 |
+
coco_eval.params.maxDets = max_dets_per_image
|
| 605 |
+
|
| 606 |
+
if img_ids is not None:
|
| 607 |
+
coco_eval.params.imgIds = img_ids
|
| 608 |
+
|
| 609 |
+
if iou_type == "keypoints":
|
| 610 |
+
# Use the COCO default keypoint OKS sigmas unless overrides are specified
|
| 611 |
+
if kpt_oks_sigmas:
|
| 612 |
+
assert hasattr(coco_eval.params, "kpt_oks_sigmas"), "annotator.oneformer.pycocotools is too old!"
|
| 613 |
+
coco_eval.params.kpt_oks_sigmas = np.array(kpt_oks_sigmas)
|
| 614 |
+
# COCOAPI requires every detection and every gt to have keypoints, so
|
| 615 |
+
# we just take the first entry from both
|
| 616 |
+
num_keypoints_dt = len(coco_results[0]["keypoints"]) // 3
|
| 617 |
+
num_keypoints_gt = len(next(iter(coco_gt.anns.values()))["keypoints"]) // 3
|
| 618 |
+
num_keypoints_oks = len(coco_eval.params.kpt_oks_sigmas)
|
| 619 |
+
assert num_keypoints_oks == num_keypoints_dt == num_keypoints_gt, (
|
| 620 |
+
f"[COCOEvaluator] Prediction contain {num_keypoints_dt} keypoints. "
|
| 621 |
+
f"Ground truth contains {num_keypoints_gt} keypoints. "
|
| 622 |
+
f"The length of cfg.TEST.KEYPOINT_OKS_SIGMAS is {num_keypoints_oks}. "
|
| 623 |
+
"They have to agree with each other. For meaning of OKS, please refer to "
|
| 624 |
+
"http://cocodataset.org/#keypoints-eval."
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
coco_eval.evaluate()
|
| 628 |
+
coco_eval.accumulate()
|
| 629 |
+
coco_eval.summarize()
|
| 630 |
+
|
| 631 |
+
return coco_eval
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class COCOevalMaxDets(COCOeval):
|
| 635 |
+
"""
|
| 636 |
+
Modified version of COCOeval for evaluating AP with a custom
|
| 637 |
+
maxDets (by default for COCO, maxDets is 100)
|
| 638 |
+
"""
|
| 639 |
+
|
| 640 |
+
def summarize(self):
|
| 641 |
+
"""
|
| 642 |
+
Compute and display summary metrics for evaluation results given
|
| 643 |
+
a custom value for max_dets_per_image
|
| 644 |
+
"""
|
| 645 |
+
|
| 646 |
+
def _summarize(ap=1, iouThr=None, areaRng="all", maxDets=100):
|
| 647 |
+
p = self.params
|
| 648 |
+
iStr = " {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}"
|
| 649 |
+
titleStr = "Average Precision" if ap == 1 else "Average Recall"
|
| 650 |
+
typeStr = "(AP)" if ap == 1 else "(AR)"
|
| 651 |
+
iouStr = (
|
| 652 |
+
"{:0.2f}:{:0.2f}".format(p.iouThrs[0], p.iouThrs[-1])
|
| 653 |
+
if iouThr is None
|
| 654 |
+
else "{:0.2f}".format(iouThr)
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
|
| 658 |
+
mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
|
| 659 |
+
if ap == 1:
|
| 660 |
+
# dimension of precision: [TxRxKxAxM]
|
| 661 |
+
s = self.eval["precision"]
|
| 662 |
+
# IoU
|
| 663 |
+
if iouThr is not None:
|
| 664 |
+
t = np.where(iouThr == p.iouThrs)[0]
|
| 665 |
+
s = s[t]
|
| 666 |
+
s = s[:, :, :, aind, mind]
|
| 667 |
+
else:
|
| 668 |
+
# dimension of recall: [TxKxAxM]
|
| 669 |
+
s = self.eval["recall"]
|
| 670 |
+
if iouThr is not None:
|
| 671 |
+
t = np.where(iouThr == p.iouThrs)[0]
|
| 672 |
+
s = s[t]
|
| 673 |
+
s = s[:, :, aind, mind]
|
| 674 |
+
if len(s[s > -1]) == 0:
|
| 675 |
+
mean_s = -1
|
| 676 |
+
else:
|
| 677 |
+
mean_s = np.mean(s[s > -1])
|
| 678 |
+
print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))
|
| 679 |
+
return mean_s
|
| 680 |
+
|
| 681 |
+
def _summarizeDets():
|
| 682 |
+
stats = np.zeros((12,))
|
| 683 |
+
# Evaluate AP using the custom limit on maximum detections per image
|
| 684 |
+
stats[0] = _summarize(1, maxDets=self.params.maxDets[2])
|
| 685 |
+
stats[1] = _summarize(1, iouThr=0.5, maxDets=self.params.maxDets[2])
|
| 686 |
+
stats[2] = _summarize(1, iouThr=0.75, maxDets=self.params.maxDets[2])
|
| 687 |
+
stats[3] = _summarize(1, areaRng="small", maxDets=self.params.maxDets[2])
|
| 688 |
+
stats[4] = _summarize(1, areaRng="medium", maxDets=self.params.maxDets[2])
|
| 689 |
+
stats[5] = _summarize(1, areaRng="large", maxDets=self.params.maxDets[2])
|
| 690 |
+
stats[6] = _summarize(0, maxDets=self.params.maxDets[0])
|
| 691 |
+
stats[7] = _summarize(0, maxDets=self.params.maxDets[1])
|
| 692 |
+
stats[8] = _summarize(0, maxDets=self.params.maxDets[2])
|
| 693 |
+
stats[9] = _summarize(0, areaRng="small", maxDets=self.params.maxDets[2])
|
| 694 |
+
stats[10] = _summarize(0, areaRng="medium", maxDets=self.params.maxDets[2])
|
| 695 |
+
stats[11] = _summarize(0, areaRng="large", maxDets=self.params.maxDets[2])
|
| 696 |
+
return stats
|
| 697 |
+
|
| 698 |
+
def _summarizeKps():
|
| 699 |
+
stats = np.zeros((10,))
|
| 700 |
+
stats[0] = _summarize(1, maxDets=20)
|
| 701 |
+
stats[1] = _summarize(1, maxDets=20, iouThr=0.5)
|
| 702 |
+
stats[2] = _summarize(1, maxDets=20, iouThr=0.75)
|
| 703 |
+
stats[3] = _summarize(1, maxDets=20, areaRng="medium")
|
| 704 |
+
stats[4] = _summarize(1, maxDets=20, areaRng="large")
|
| 705 |
+
stats[5] = _summarize(0, maxDets=20)
|
| 706 |
+
stats[6] = _summarize(0, maxDets=20, iouThr=0.5)
|
| 707 |
+
stats[7] = _summarize(0, maxDets=20, iouThr=0.75)
|
| 708 |
+
stats[8] = _summarize(0, maxDets=20, areaRng="medium")
|
| 709 |
+
stats[9] = _summarize(0, maxDets=20, areaRng="large")
|
| 710 |
+
return stats
|
| 711 |
+
|
| 712 |
+
if not self.eval:
|
| 713 |
+
raise Exception("Please run accumulate() first")
|
| 714 |
+
iouType = self.params.iouType
|
| 715 |
+
if iouType == "segm" or iouType == "bbox":
|
| 716 |
+
summarize = _summarizeDets
|
| 717 |
+
elif iouType == "keypoints":
|
| 718 |
+
summarize = _summarizeKps
|
| 719 |
+
self.stats = summarize()
|
| 720 |
+
|
| 721 |
+
def __str__(self):
|
| 722 |
+
self.summarize()
|
RAVE-main/annotator/oneformer/detectron2/evaluation/evaluator.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import datetime
|
| 3 |
+
import logging
|
| 4 |
+
import time
|
| 5 |
+
from collections import OrderedDict, abc
|
| 6 |
+
from contextlib import ExitStack, contextmanager
|
| 7 |
+
from typing import List, Union
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
|
| 11 |
+
from annotator.oneformer.detectron2.utils.comm import get_world_size, is_main_process
|
| 12 |
+
from annotator.oneformer.detectron2.utils.logger import log_every_n_seconds
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class DatasetEvaluator:
|
| 16 |
+
"""
|
| 17 |
+
Base class for a dataset evaluator.
|
| 18 |
+
|
| 19 |
+
The function :func:`inference_on_dataset` runs the model over
|
| 20 |
+
all samples in the dataset, and have a DatasetEvaluator to process the inputs/outputs.
|
| 21 |
+
|
| 22 |
+
This class will accumulate information of the inputs/outputs (by :meth:`process`),
|
| 23 |
+
and produce evaluation results in the end (by :meth:`evaluate`).
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def reset(self):
|
| 27 |
+
"""
|
| 28 |
+
Preparation for a new round of evaluation.
|
| 29 |
+
Should be called before starting a round of evaluation.
|
| 30 |
+
"""
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
def process(self, inputs, outputs):
|
| 34 |
+
"""
|
| 35 |
+
Process the pair of inputs and outputs.
|
| 36 |
+
If they contain batches, the pairs can be consumed one-by-one using `zip`:
|
| 37 |
+
|
| 38 |
+
.. code-block:: python
|
| 39 |
+
|
| 40 |
+
for input_, output in zip(inputs, outputs):
|
| 41 |
+
# do evaluation on single input/output pair
|
| 42 |
+
...
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
inputs (list): the inputs that's used to call the model.
|
| 46 |
+
outputs (list): the return value of `model(inputs)`
|
| 47 |
+
"""
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
def evaluate(self):
|
| 51 |
+
"""
|
| 52 |
+
Evaluate/summarize the performance, after processing all input/output pairs.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
dict:
|
| 56 |
+
A new evaluator class can return a dict of arbitrary format
|
| 57 |
+
as long as the user can process the results.
|
| 58 |
+
In our train_net.py, we expect the following format:
|
| 59 |
+
|
| 60 |
+
* key: the name of the task (e.g., bbox)
|
| 61 |
+
* value: a dict of {metric name: score}, e.g.: {"AP50": 80}
|
| 62 |
+
"""
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class DatasetEvaluators(DatasetEvaluator):
|
| 67 |
+
"""
|
| 68 |
+
Wrapper class to combine multiple :class:`DatasetEvaluator` instances.
|
| 69 |
+
|
| 70 |
+
This class dispatches every evaluation call to
|
| 71 |
+
all of its :class:`DatasetEvaluator`.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, evaluators):
|
| 75 |
+
"""
|
| 76 |
+
Args:
|
| 77 |
+
evaluators (list): the evaluators to combine.
|
| 78 |
+
"""
|
| 79 |
+
super().__init__()
|
| 80 |
+
self._evaluators = evaluators
|
| 81 |
+
|
| 82 |
+
def reset(self):
|
| 83 |
+
for evaluator in self._evaluators:
|
| 84 |
+
evaluator.reset()
|
| 85 |
+
|
| 86 |
+
def process(self, inputs, outputs):
|
| 87 |
+
for evaluator in self._evaluators:
|
| 88 |
+
evaluator.process(inputs, outputs)
|
| 89 |
+
|
| 90 |
+
def evaluate(self):
|
| 91 |
+
results = OrderedDict()
|
| 92 |
+
for evaluator in self._evaluators:
|
| 93 |
+
result = evaluator.evaluate()
|
| 94 |
+
if is_main_process() and result is not None:
|
| 95 |
+
for k, v in result.items():
|
| 96 |
+
assert (
|
| 97 |
+
k not in results
|
| 98 |
+
), "Different evaluators produce results with the same key {}".format(k)
|
| 99 |
+
results[k] = v
|
| 100 |
+
return results
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def inference_on_dataset(
|
| 104 |
+
model, data_loader, evaluator: Union[DatasetEvaluator, List[DatasetEvaluator], None]
|
| 105 |
+
):
|
| 106 |
+
"""
|
| 107 |
+
Run model on the data_loader and evaluate the metrics with evaluator.
|
| 108 |
+
Also benchmark the inference speed of `model.__call__` accurately.
|
| 109 |
+
The model will be used in eval mode.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
model (callable): a callable which takes an object from
|
| 113 |
+
`data_loader` and returns some outputs.
|
| 114 |
+
|
| 115 |
+
If it's an nn.Module, it will be temporarily set to `eval` mode.
|
| 116 |
+
If you wish to evaluate a model in `training` mode instead, you can
|
| 117 |
+
wrap the given model and override its behavior of `.eval()` and `.train()`.
|
| 118 |
+
data_loader: an iterable object with a length.
|
| 119 |
+
The elements it generates will be the inputs to the model.
|
| 120 |
+
evaluator: the evaluator(s) to run. Use `None` if you only want to benchmark,
|
| 121 |
+
but don't want to do any evaluation.
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
The return value of `evaluator.evaluate()`
|
| 125 |
+
"""
|
| 126 |
+
num_devices = get_world_size()
|
| 127 |
+
logger = logging.getLogger(__name__)
|
| 128 |
+
logger.info("Start inference on {} batches".format(len(data_loader)))
|
| 129 |
+
|
| 130 |
+
total = len(data_loader) # inference data loader must have a fixed length
|
| 131 |
+
if evaluator is None:
|
| 132 |
+
# create a no-op evaluator
|
| 133 |
+
evaluator = DatasetEvaluators([])
|
| 134 |
+
if isinstance(evaluator, abc.MutableSequence):
|
| 135 |
+
evaluator = DatasetEvaluators(evaluator)
|
| 136 |
+
evaluator.reset()
|
| 137 |
+
|
| 138 |
+
num_warmup = min(5, total - 1)
|
| 139 |
+
start_time = time.perf_counter()
|
| 140 |
+
total_data_time = 0
|
| 141 |
+
total_compute_time = 0
|
| 142 |
+
total_eval_time = 0
|
| 143 |
+
with ExitStack() as stack:
|
| 144 |
+
if isinstance(model, nn.Module):
|
| 145 |
+
stack.enter_context(inference_context(model))
|
| 146 |
+
stack.enter_context(torch.no_grad())
|
| 147 |
+
|
| 148 |
+
start_data_time = time.perf_counter()
|
| 149 |
+
for idx, inputs in enumerate(data_loader):
|
| 150 |
+
total_data_time += time.perf_counter() - start_data_time
|
| 151 |
+
if idx == num_warmup:
|
| 152 |
+
start_time = time.perf_counter()
|
| 153 |
+
total_data_time = 0
|
| 154 |
+
total_compute_time = 0
|
| 155 |
+
total_eval_time = 0
|
| 156 |
+
|
| 157 |
+
start_compute_time = time.perf_counter()
|
| 158 |
+
outputs = model(inputs)
|
| 159 |
+
if torch.cuda.is_available():
|
| 160 |
+
torch.cuda.synchronize()
|
| 161 |
+
total_compute_time += time.perf_counter() - start_compute_time
|
| 162 |
+
|
| 163 |
+
start_eval_time = time.perf_counter()
|
| 164 |
+
evaluator.process(inputs, outputs)
|
| 165 |
+
total_eval_time += time.perf_counter() - start_eval_time
|
| 166 |
+
|
| 167 |
+
iters_after_start = idx + 1 - num_warmup * int(idx >= num_warmup)
|
| 168 |
+
data_seconds_per_iter = total_data_time / iters_after_start
|
| 169 |
+
compute_seconds_per_iter = total_compute_time / iters_after_start
|
| 170 |
+
eval_seconds_per_iter = total_eval_time / iters_after_start
|
| 171 |
+
total_seconds_per_iter = (time.perf_counter() - start_time) / iters_after_start
|
| 172 |
+
if idx >= num_warmup * 2 or compute_seconds_per_iter > 5:
|
| 173 |
+
eta = datetime.timedelta(seconds=int(total_seconds_per_iter * (total - idx - 1)))
|
| 174 |
+
log_every_n_seconds(
|
| 175 |
+
logging.INFO,
|
| 176 |
+
(
|
| 177 |
+
f"Inference done {idx + 1}/{total}. "
|
| 178 |
+
f"Dataloading: {data_seconds_per_iter:.4f} s/iter. "
|
| 179 |
+
f"Inference: {compute_seconds_per_iter:.4f} s/iter. "
|
| 180 |
+
f"Eval: {eval_seconds_per_iter:.4f} s/iter. "
|
| 181 |
+
f"Total: {total_seconds_per_iter:.4f} s/iter. "
|
| 182 |
+
f"ETA={eta}"
|
| 183 |
+
),
|
| 184 |
+
n=5,
|
| 185 |
+
)
|
| 186 |
+
start_data_time = time.perf_counter()
|
| 187 |
+
|
| 188 |
+
# Measure the time only for this worker (before the synchronization barrier)
|
| 189 |
+
total_time = time.perf_counter() - start_time
|
| 190 |
+
total_time_str = str(datetime.timedelta(seconds=total_time))
|
| 191 |
+
# NOTE this format is parsed by grep
|
| 192 |
+
logger.info(
|
| 193 |
+
"Total inference time: {} ({:.6f} s / iter per device, on {} devices)".format(
|
| 194 |
+
total_time_str, total_time / (total - num_warmup), num_devices
|
| 195 |
+
)
|
| 196 |
+
)
|
| 197 |
+
total_compute_time_str = str(datetime.timedelta(seconds=int(total_compute_time)))
|
| 198 |
+
logger.info(
|
| 199 |
+
"Total inference pure compute time: {} ({:.6f} s / iter per device, on {} devices)".format(
|
| 200 |
+
total_compute_time_str, total_compute_time / (total - num_warmup), num_devices
|
| 201 |
+
)
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
results = evaluator.evaluate()
|
| 205 |
+
# An evaluator may return None when not in main process.
|
| 206 |
+
# Replace it by an empty dict instead to make it easier for downstream code to handle
|
| 207 |
+
if results is None:
|
| 208 |
+
results = {}
|
| 209 |
+
return results
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@contextmanager
|
| 213 |
+
def inference_context(model):
|
| 214 |
+
"""
|
| 215 |
+
A context where the model is temporarily changed to eval mode,
|
| 216 |
+
and restored to previous mode afterwards.
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
model: a torch Module
|
| 220 |
+
"""
|
| 221 |
+
training_mode = model.training
|
| 222 |
+
model.eval()
|
| 223 |
+
yield
|
| 224 |
+
model.train(training_mode)
|
RAVE-main/annotator/oneformer/detectron2/evaluation/fast_eval_api.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import copy
|
| 3 |
+
import logging
|
| 4 |
+
import numpy as np
|
| 5 |
+
import time
|
| 6 |
+
from annotator.oneformer.pycocotools.cocoeval import COCOeval
|
| 7 |
+
|
| 8 |
+
from annotator.oneformer.detectron2 import _C
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class COCOeval_opt(COCOeval):
|
| 14 |
+
"""
|
| 15 |
+
This is a slightly modified version of the original COCO API, where the functions evaluateImg()
|
| 16 |
+
and accumulate() are implemented in C++ to speedup evaluation
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def evaluate(self):
|
| 20 |
+
"""
|
| 21 |
+
Run per image evaluation on given images and store results in self.evalImgs_cpp, a
|
| 22 |
+
datastructure that isn't readable from Python but is used by a c++ implementation of
|
| 23 |
+
accumulate(). Unlike the original COCO PythonAPI, we don't populate the datastructure
|
| 24 |
+
self.evalImgs because this datastructure is a computational bottleneck.
|
| 25 |
+
:return: None
|
| 26 |
+
"""
|
| 27 |
+
tic = time.time()
|
| 28 |
+
|
| 29 |
+
p = self.params
|
| 30 |
+
# add backward compatibility if useSegm is specified in params
|
| 31 |
+
if p.useSegm is not None:
|
| 32 |
+
p.iouType = "segm" if p.useSegm == 1 else "bbox"
|
| 33 |
+
logger.info("Evaluate annotation type *{}*".format(p.iouType))
|
| 34 |
+
p.imgIds = list(np.unique(p.imgIds))
|
| 35 |
+
if p.useCats:
|
| 36 |
+
p.catIds = list(np.unique(p.catIds))
|
| 37 |
+
p.maxDets = sorted(p.maxDets)
|
| 38 |
+
self.params = p
|
| 39 |
+
|
| 40 |
+
self._prepare() # bottleneck
|
| 41 |
+
|
| 42 |
+
# loop through images, area range, max detection number
|
| 43 |
+
catIds = p.catIds if p.useCats else [-1]
|
| 44 |
+
|
| 45 |
+
if p.iouType == "segm" or p.iouType == "bbox":
|
| 46 |
+
computeIoU = self.computeIoU
|
| 47 |
+
elif p.iouType == "keypoints":
|
| 48 |
+
computeIoU = self.computeOks
|
| 49 |
+
self.ious = {
|
| 50 |
+
(imgId, catId): computeIoU(imgId, catId) for imgId in p.imgIds for catId in catIds
|
| 51 |
+
} # bottleneck
|
| 52 |
+
|
| 53 |
+
maxDet = p.maxDets[-1]
|
| 54 |
+
|
| 55 |
+
# <<<< Beginning of code differences with original COCO API
|
| 56 |
+
def convert_instances_to_cpp(instances, is_det=False):
|
| 57 |
+
# Convert annotations for a list of instances in an image to a format that's fast
|
| 58 |
+
# to access in C++
|
| 59 |
+
instances_cpp = []
|
| 60 |
+
for instance in instances:
|
| 61 |
+
instance_cpp = _C.InstanceAnnotation(
|
| 62 |
+
int(instance["id"]),
|
| 63 |
+
instance["score"] if is_det else instance.get("score", 0.0),
|
| 64 |
+
instance["area"],
|
| 65 |
+
bool(instance.get("iscrowd", 0)),
|
| 66 |
+
bool(instance.get("ignore", 0)),
|
| 67 |
+
)
|
| 68 |
+
instances_cpp.append(instance_cpp)
|
| 69 |
+
return instances_cpp
|
| 70 |
+
|
| 71 |
+
# Convert GT annotations, detections, and IOUs to a format that's fast to access in C++
|
| 72 |
+
ground_truth_instances = [
|
| 73 |
+
[convert_instances_to_cpp(self._gts[imgId, catId]) for catId in p.catIds]
|
| 74 |
+
for imgId in p.imgIds
|
| 75 |
+
]
|
| 76 |
+
detected_instances = [
|
| 77 |
+
[convert_instances_to_cpp(self._dts[imgId, catId], is_det=True) for catId in p.catIds]
|
| 78 |
+
for imgId in p.imgIds
|
| 79 |
+
]
|
| 80 |
+
ious = [[self.ious[imgId, catId] for catId in catIds] for imgId in p.imgIds]
|
| 81 |
+
|
| 82 |
+
if not p.useCats:
|
| 83 |
+
# For each image, flatten per-category lists into a single list
|
| 84 |
+
ground_truth_instances = [[[o for c in i for o in c]] for i in ground_truth_instances]
|
| 85 |
+
detected_instances = [[[o for c in i for o in c]] for i in detected_instances]
|
| 86 |
+
|
| 87 |
+
# Call C++ implementation of self.evaluateImgs()
|
| 88 |
+
self._evalImgs_cpp = _C.COCOevalEvaluateImages(
|
| 89 |
+
p.areaRng, maxDet, p.iouThrs, ious, ground_truth_instances, detected_instances
|
| 90 |
+
)
|
| 91 |
+
self._evalImgs = None
|
| 92 |
+
|
| 93 |
+
self._paramsEval = copy.deepcopy(self.params)
|
| 94 |
+
toc = time.time()
|
| 95 |
+
logger.info("COCOeval_opt.evaluate() finished in {:0.2f} seconds.".format(toc - tic))
|
| 96 |
+
# >>>> End of code differences with original COCO API
|
| 97 |
+
|
| 98 |
+
def accumulate(self):
|
| 99 |
+
"""
|
| 100 |
+
Accumulate per image evaluation results and store the result in self.eval. Does not
|
| 101 |
+
support changing parameter settings from those used by self.evaluate()
|
| 102 |
+
"""
|
| 103 |
+
logger.info("Accumulating evaluation results...")
|
| 104 |
+
tic = time.time()
|
| 105 |
+
assert hasattr(
|
| 106 |
+
self, "_evalImgs_cpp"
|
| 107 |
+
), "evaluate() must be called before accmulate() is called."
|
| 108 |
+
|
| 109 |
+
self.eval = _C.COCOevalAccumulate(self._paramsEval, self._evalImgs_cpp)
|
| 110 |
+
|
| 111 |
+
# recall is num_iou_thresholds X num_categories X num_area_ranges X num_max_detections
|
| 112 |
+
self.eval["recall"] = np.array(self.eval["recall"]).reshape(
|
| 113 |
+
self.eval["counts"][:1] + self.eval["counts"][2:]
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# precision and scores are num_iou_thresholds X num_recall_thresholds X num_categories X
|
| 117 |
+
# num_area_ranges X num_max_detections
|
| 118 |
+
self.eval["precision"] = np.array(self.eval["precision"]).reshape(self.eval["counts"])
|
| 119 |
+
self.eval["scores"] = np.array(self.eval["scores"]).reshape(self.eval["counts"])
|
| 120 |
+
toc = time.time()
|
| 121 |
+
logger.info("COCOeval_opt.accumulate() finished in {:0.2f} seconds.".format(toc - tic))
|
RAVE-main/annotator/oneformer/detectron2/evaluation/lvis_evaluation.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import copy
|
| 3 |
+
import itertools
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import pickle
|
| 8 |
+
from collections import OrderedDict
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
import annotator.oneformer.detectron2.utils.comm as comm
|
| 12 |
+
from annotator.oneformer.detectron2.config import CfgNode
|
| 13 |
+
from annotator.oneformer.detectron2.data import MetadataCatalog
|
| 14 |
+
from annotator.oneformer.detectron2.structures import Boxes, BoxMode, pairwise_iou
|
| 15 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 16 |
+
from annotator.oneformer.detectron2.utils.logger import create_small_table
|
| 17 |
+
|
| 18 |
+
from .coco_evaluation import instances_to_coco_json
|
| 19 |
+
from .evaluator import DatasetEvaluator
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class LVISEvaluator(DatasetEvaluator):
|
| 23 |
+
"""
|
| 24 |
+
Evaluate object proposal and instance detection/segmentation outputs using
|
| 25 |
+
LVIS's metrics and evaluation API.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
dataset_name,
|
| 31 |
+
tasks=None,
|
| 32 |
+
distributed=True,
|
| 33 |
+
output_dir=None,
|
| 34 |
+
*,
|
| 35 |
+
max_dets_per_image=None,
|
| 36 |
+
):
|
| 37 |
+
"""
|
| 38 |
+
Args:
|
| 39 |
+
dataset_name (str): name of the dataset to be evaluated.
|
| 40 |
+
It must have the following corresponding metadata:
|
| 41 |
+
"json_file": the path to the LVIS format annotation
|
| 42 |
+
tasks (tuple[str]): tasks that can be evaluated under the given
|
| 43 |
+
configuration. A task is one of "bbox", "segm".
|
| 44 |
+
By default, will infer this automatically from predictions.
|
| 45 |
+
distributed (True): if True, will collect results from all ranks for evaluation.
|
| 46 |
+
Otherwise, will evaluate the results in the current process.
|
| 47 |
+
output_dir (str): optional, an output directory to dump results.
|
| 48 |
+
max_dets_per_image (None or int): limit on maximum detections per image in evaluating AP
|
| 49 |
+
This limit, by default of the LVIS dataset, is 300.
|
| 50 |
+
"""
|
| 51 |
+
from lvis import LVIS
|
| 52 |
+
|
| 53 |
+
self._logger = logging.getLogger(__name__)
|
| 54 |
+
|
| 55 |
+
if tasks is not None and isinstance(tasks, CfgNode):
|
| 56 |
+
self._logger.warn(
|
| 57 |
+
"COCO Evaluator instantiated using config, this is deprecated behavior."
|
| 58 |
+
" Please pass in explicit arguments instead."
|
| 59 |
+
)
|
| 60 |
+
self._tasks = None # Infering it from predictions should be better
|
| 61 |
+
else:
|
| 62 |
+
self._tasks = tasks
|
| 63 |
+
|
| 64 |
+
self._distributed = distributed
|
| 65 |
+
self._output_dir = output_dir
|
| 66 |
+
self._max_dets_per_image = max_dets_per_image
|
| 67 |
+
|
| 68 |
+
self._cpu_device = torch.device("cpu")
|
| 69 |
+
|
| 70 |
+
self._metadata = MetadataCatalog.get(dataset_name)
|
| 71 |
+
json_file = PathManager.get_local_path(self._metadata.json_file)
|
| 72 |
+
self._lvis_api = LVIS(json_file)
|
| 73 |
+
# Test set json files do not contain annotations (evaluation must be
|
| 74 |
+
# performed using the LVIS evaluation server).
|
| 75 |
+
self._do_evaluation = len(self._lvis_api.get_ann_ids()) > 0
|
| 76 |
+
|
| 77 |
+
def reset(self):
|
| 78 |
+
self._predictions = []
|
| 79 |
+
|
| 80 |
+
def process(self, inputs, outputs):
|
| 81 |
+
"""
|
| 82 |
+
Args:
|
| 83 |
+
inputs: the inputs to a LVIS model (e.g., GeneralizedRCNN).
|
| 84 |
+
It is a list of dict. Each dict corresponds to an image and
|
| 85 |
+
contains keys like "height", "width", "file_name", "image_id".
|
| 86 |
+
outputs: the outputs of a LVIS model. It is a list of dicts with key
|
| 87 |
+
"instances" that contains :class:`Instances`.
|
| 88 |
+
"""
|
| 89 |
+
for input, output in zip(inputs, outputs):
|
| 90 |
+
prediction = {"image_id": input["image_id"]}
|
| 91 |
+
|
| 92 |
+
if "instances" in output:
|
| 93 |
+
instances = output["instances"].to(self._cpu_device)
|
| 94 |
+
prediction["instances"] = instances_to_coco_json(instances, input["image_id"])
|
| 95 |
+
if "proposals" in output:
|
| 96 |
+
prediction["proposals"] = output["proposals"].to(self._cpu_device)
|
| 97 |
+
self._predictions.append(prediction)
|
| 98 |
+
|
| 99 |
+
def evaluate(self):
|
| 100 |
+
if self._distributed:
|
| 101 |
+
comm.synchronize()
|
| 102 |
+
predictions = comm.gather(self._predictions, dst=0)
|
| 103 |
+
predictions = list(itertools.chain(*predictions))
|
| 104 |
+
|
| 105 |
+
if not comm.is_main_process():
|
| 106 |
+
return
|
| 107 |
+
else:
|
| 108 |
+
predictions = self._predictions
|
| 109 |
+
|
| 110 |
+
if len(predictions) == 0:
|
| 111 |
+
self._logger.warning("[LVISEvaluator] Did not receive valid predictions.")
|
| 112 |
+
return {}
|
| 113 |
+
|
| 114 |
+
if self._output_dir:
|
| 115 |
+
PathManager.mkdirs(self._output_dir)
|
| 116 |
+
file_path = os.path.join(self._output_dir, "instances_predictions.pth")
|
| 117 |
+
with PathManager.open(file_path, "wb") as f:
|
| 118 |
+
torch.save(predictions, f)
|
| 119 |
+
|
| 120 |
+
self._results = OrderedDict()
|
| 121 |
+
if "proposals" in predictions[0]:
|
| 122 |
+
self._eval_box_proposals(predictions)
|
| 123 |
+
if "instances" in predictions[0]:
|
| 124 |
+
self._eval_predictions(predictions)
|
| 125 |
+
# Copy so the caller can do whatever with results
|
| 126 |
+
return copy.deepcopy(self._results)
|
| 127 |
+
|
| 128 |
+
def _tasks_from_predictions(self, predictions):
|
| 129 |
+
for pred in predictions:
|
| 130 |
+
if "segmentation" in pred:
|
| 131 |
+
return ("bbox", "segm")
|
| 132 |
+
return ("bbox",)
|
| 133 |
+
|
| 134 |
+
def _eval_predictions(self, predictions):
|
| 135 |
+
"""
|
| 136 |
+
Evaluate predictions. Fill self._results with the metrics of the tasks.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
predictions (list[dict]): list of outputs from the model
|
| 140 |
+
"""
|
| 141 |
+
self._logger.info("Preparing results in the LVIS format ...")
|
| 142 |
+
lvis_results = list(itertools.chain(*[x["instances"] for x in predictions]))
|
| 143 |
+
tasks = self._tasks or self._tasks_from_predictions(lvis_results)
|
| 144 |
+
|
| 145 |
+
# LVIS evaluator can be used to evaluate results for COCO dataset categories.
|
| 146 |
+
# In this case `_metadata` variable will have a field with COCO-specific category mapping.
|
| 147 |
+
if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"):
|
| 148 |
+
reverse_id_mapping = {
|
| 149 |
+
v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items()
|
| 150 |
+
}
|
| 151 |
+
for result in lvis_results:
|
| 152 |
+
result["category_id"] = reverse_id_mapping[result["category_id"]]
|
| 153 |
+
else:
|
| 154 |
+
# unmap the category ids for LVIS (from 0-indexed to 1-indexed)
|
| 155 |
+
for result in lvis_results:
|
| 156 |
+
result["category_id"] += 1
|
| 157 |
+
|
| 158 |
+
if self._output_dir:
|
| 159 |
+
file_path = os.path.join(self._output_dir, "lvis_instances_results.json")
|
| 160 |
+
self._logger.info("Saving results to {}".format(file_path))
|
| 161 |
+
with PathManager.open(file_path, "w") as f:
|
| 162 |
+
f.write(json.dumps(lvis_results))
|
| 163 |
+
f.flush()
|
| 164 |
+
|
| 165 |
+
if not self._do_evaluation:
|
| 166 |
+
self._logger.info("Annotations are not available for evaluation.")
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
self._logger.info("Evaluating predictions ...")
|
| 170 |
+
for task in sorted(tasks):
|
| 171 |
+
res = _evaluate_predictions_on_lvis(
|
| 172 |
+
self._lvis_api,
|
| 173 |
+
lvis_results,
|
| 174 |
+
task,
|
| 175 |
+
max_dets_per_image=self._max_dets_per_image,
|
| 176 |
+
class_names=self._metadata.get("thing_classes"),
|
| 177 |
+
)
|
| 178 |
+
self._results[task] = res
|
| 179 |
+
|
| 180 |
+
def _eval_box_proposals(self, predictions):
|
| 181 |
+
"""
|
| 182 |
+
Evaluate the box proposals in predictions.
|
| 183 |
+
Fill self._results with the metrics for "box_proposals" task.
|
| 184 |
+
"""
|
| 185 |
+
if self._output_dir:
|
| 186 |
+
# Saving generated box proposals to file.
|
| 187 |
+
# Predicted box_proposals are in XYXY_ABS mode.
|
| 188 |
+
bbox_mode = BoxMode.XYXY_ABS.value
|
| 189 |
+
ids, boxes, objectness_logits = [], [], []
|
| 190 |
+
for prediction in predictions:
|
| 191 |
+
ids.append(prediction["image_id"])
|
| 192 |
+
boxes.append(prediction["proposals"].proposal_boxes.tensor.numpy())
|
| 193 |
+
objectness_logits.append(prediction["proposals"].objectness_logits.numpy())
|
| 194 |
+
|
| 195 |
+
proposal_data = {
|
| 196 |
+
"boxes": boxes,
|
| 197 |
+
"objectness_logits": objectness_logits,
|
| 198 |
+
"ids": ids,
|
| 199 |
+
"bbox_mode": bbox_mode,
|
| 200 |
+
}
|
| 201 |
+
with PathManager.open(os.path.join(self._output_dir, "box_proposals.pkl"), "wb") as f:
|
| 202 |
+
pickle.dump(proposal_data, f)
|
| 203 |
+
|
| 204 |
+
if not self._do_evaluation:
|
| 205 |
+
self._logger.info("Annotations are not available for evaluation.")
|
| 206 |
+
return
|
| 207 |
+
|
| 208 |
+
self._logger.info("Evaluating bbox proposals ...")
|
| 209 |
+
res = {}
|
| 210 |
+
areas = {"all": "", "small": "s", "medium": "m", "large": "l"}
|
| 211 |
+
for limit in [100, 1000]:
|
| 212 |
+
for area, suffix in areas.items():
|
| 213 |
+
stats = _evaluate_box_proposals(predictions, self._lvis_api, area=area, limit=limit)
|
| 214 |
+
key = "AR{}@{:d}".format(suffix, limit)
|
| 215 |
+
res[key] = float(stats["ar"].item() * 100)
|
| 216 |
+
self._logger.info("Proposal metrics: \n" + create_small_table(res))
|
| 217 |
+
self._results["box_proposals"] = res
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# inspired from Detectron:
|
| 221 |
+
# https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L255 # noqa
|
| 222 |
+
def _evaluate_box_proposals(dataset_predictions, lvis_api, thresholds=None, area="all", limit=None):
|
| 223 |
+
"""
|
| 224 |
+
Evaluate detection proposal recall metrics. This function is a much
|
| 225 |
+
faster alternative to the official LVIS API recall evaluation code. However,
|
| 226 |
+
it produces slightly different results.
|
| 227 |
+
"""
|
| 228 |
+
# Record max overlap value for each gt box
|
| 229 |
+
# Return vector of overlap values
|
| 230 |
+
areas = {
|
| 231 |
+
"all": 0,
|
| 232 |
+
"small": 1,
|
| 233 |
+
"medium": 2,
|
| 234 |
+
"large": 3,
|
| 235 |
+
"96-128": 4,
|
| 236 |
+
"128-256": 5,
|
| 237 |
+
"256-512": 6,
|
| 238 |
+
"512-inf": 7,
|
| 239 |
+
}
|
| 240 |
+
area_ranges = [
|
| 241 |
+
[0**2, 1e5**2], # all
|
| 242 |
+
[0**2, 32**2], # small
|
| 243 |
+
[32**2, 96**2], # medium
|
| 244 |
+
[96**2, 1e5**2], # large
|
| 245 |
+
[96**2, 128**2], # 96-128
|
| 246 |
+
[128**2, 256**2], # 128-256
|
| 247 |
+
[256**2, 512**2], # 256-512
|
| 248 |
+
[512**2, 1e5**2],
|
| 249 |
+
] # 512-inf
|
| 250 |
+
assert area in areas, "Unknown area range: {}".format(area)
|
| 251 |
+
area_range = area_ranges[areas[area]]
|
| 252 |
+
gt_overlaps = []
|
| 253 |
+
num_pos = 0
|
| 254 |
+
|
| 255 |
+
for prediction_dict in dataset_predictions:
|
| 256 |
+
predictions = prediction_dict["proposals"]
|
| 257 |
+
|
| 258 |
+
# sort predictions in descending order
|
| 259 |
+
# TODO maybe remove this and make it explicit in the documentation
|
| 260 |
+
inds = predictions.objectness_logits.sort(descending=True)[1]
|
| 261 |
+
predictions = predictions[inds]
|
| 262 |
+
|
| 263 |
+
ann_ids = lvis_api.get_ann_ids(img_ids=[prediction_dict["image_id"]])
|
| 264 |
+
anno = lvis_api.load_anns(ann_ids)
|
| 265 |
+
gt_boxes = [
|
| 266 |
+
BoxMode.convert(obj["bbox"], BoxMode.XYWH_ABS, BoxMode.XYXY_ABS) for obj in anno
|
| 267 |
+
]
|
| 268 |
+
gt_boxes = torch.as_tensor(gt_boxes).reshape(-1, 4) # guard against no boxes
|
| 269 |
+
gt_boxes = Boxes(gt_boxes)
|
| 270 |
+
gt_areas = torch.as_tensor([obj["area"] for obj in anno])
|
| 271 |
+
|
| 272 |
+
if len(gt_boxes) == 0 or len(predictions) == 0:
|
| 273 |
+
continue
|
| 274 |
+
|
| 275 |
+
valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1])
|
| 276 |
+
gt_boxes = gt_boxes[valid_gt_inds]
|
| 277 |
+
|
| 278 |
+
num_pos += len(gt_boxes)
|
| 279 |
+
|
| 280 |
+
if len(gt_boxes) == 0:
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
if limit is not None and len(predictions) > limit:
|
| 284 |
+
predictions = predictions[:limit]
|
| 285 |
+
|
| 286 |
+
overlaps = pairwise_iou(predictions.proposal_boxes, gt_boxes)
|
| 287 |
+
|
| 288 |
+
_gt_overlaps = torch.zeros(len(gt_boxes))
|
| 289 |
+
for j in range(min(len(predictions), len(gt_boxes))):
|
| 290 |
+
# find which proposal box maximally covers each gt box
|
| 291 |
+
# and get the iou amount of coverage for each gt box
|
| 292 |
+
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
|
| 293 |
+
|
| 294 |
+
# find which gt box is 'best' covered (i.e. 'best' = most iou)
|
| 295 |
+
gt_ovr, gt_ind = max_overlaps.max(dim=0)
|
| 296 |
+
assert gt_ovr >= 0
|
| 297 |
+
# find the proposal box that covers the best covered gt box
|
| 298 |
+
box_ind = argmax_overlaps[gt_ind]
|
| 299 |
+
# record the iou coverage of this gt box
|
| 300 |
+
_gt_overlaps[j] = overlaps[box_ind, gt_ind]
|
| 301 |
+
assert _gt_overlaps[j] == gt_ovr
|
| 302 |
+
# mark the proposal box and the gt box as used
|
| 303 |
+
overlaps[box_ind, :] = -1
|
| 304 |
+
overlaps[:, gt_ind] = -1
|
| 305 |
+
|
| 306 |
+
# append recorded iou coverage level
|
| 307 |
+
gt_overlaps.append(_gt_overlaps)
|
| 308 |
+
gt_overlaps = (
|
| 309 |
+
torch.cat(gt_overlaps, dim=0) if len(gt_overlaps) else torch.zeros(0, dtype=torch.float32)
|
| 310 |
+
)
|
| 311 |
+
gt_overlaps, _ = torch.sort(gt_overlaps)
|
| 312 |
+
|
| 313 |
+
if thresholds is None:
|
| 314 |
+
step = 0.05
|
| 315 |
+
thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32)
|
| 316 |
+
recalls = torch.zeros_like(thresholds)
|
| 317 |
+
# compute recall for each iou threshold
|
| 318 |
+
for i, t in enumerate(thresholds):
|
| 319 |
+
recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos)
|
| 320 |
+
# ar = 2 * np.trapz(recalls, thresholds)
|
| 321 |
+
ar = recalls.mean()
|
| 322 |
+
return {
|
| 323 |
+
"ar": ar,
|
| 324 |
+
"recalls": recalls,
|
| 325 |
+
"thresholds": thresholds,
|
| 326 |
+
"gt_overlaps": gt_overlaps,
|
| 327 |
+
"num_pos": num_pos,
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _evaluate_predictions_on_lvis(
|
| 332 |
+
lvis_gt, lvis_results, iou_type, max_dets_per_image=None, class_names=None
|
| 333 |
+
):
|
| 334 |
+
"""
|
| 335 |
+
Args:
|
| 336 |
+
iou_type (str):
|
| 337 |
+
max_dets_per_image (None or int): limit on maximum detections per image in evaluating AP
|
| 338 |
+
This limit, by default of the LVIS dataset, is 300.
|
| 339 |
+
class_names (None or list[str]): if provided, will use it to predict
|
| 340 |
+
per-category AP.
|
| 341 |
+
|
| 342 |
+
Returns:
|
| 343 |
+
a dict of {metric name: score}
|
| 344 |
+
"""
|
| 345 |
+
metrics = {
|
| 346 |
+
"bbox": ["AP", "AP50", "AP75", "APs", "APm", "APl", "APr", "APc", "APf"],
|
| 347 |
+
"segm": ["AP", "AP50", "AP75", "APs", "APm", "APl", "APr", "APc", "APf"],
|
| 348 |
+
}[iou_type]
|
| 349 |
+
|
| 350 |
+
logger = logging.getLogger(__name__)
|
| 351 |
+
|
| 352 |
+
if len(lvis_results) == 0: # TODO: check if needed
|
| 353 |
+
logger.warn("No predictions from the model!")
|
| 354 |
+
return {metric: float("nan") for metric in metrics}
|
| 355 |
+
|
| 356 |
+
if iou_type == "segm":
|
| 357 |
+
lvis_results = copy.deepcopy(lvis_results)
|
| 358 |
+
# When evaluating mask AP, if the results contain bbox, LVIS API will
|
| 359 |
+
# use the box area as the area of the instance, instead of the mask area.
|
| 360 |
+
# This leads to a different definition of small/medium/large.
|
| 361 |
+
# We remove the bbox field to let mask AP use mask area.
|
| 362 |
+
for c in lvis_results:
|
| 363 |
+
c.pop("bbox", None)
|
| 364 |
+
|
| 365 |
+
if max_dets_per_image is None:
|
| 366 |
+
max_dets_per_image = 300 # Default for LVIS dataset
|
| 367 |
+
|
| 368 |
+
from lvis import LVISEval, LVISResults
|
| 369 |
+
|
| 370 |
+
logger.info(f"Evaluating with max detections per image = {max_dets_per_image}")
|
| 371 |
+
lvis_results = LVISResults(lvis_gt, lvis_results, max_dets=max_dets_per_image)
|
| 372 |
+
lvis_eval = LVISEval(lvis_gt, lvis_results, iou_type)
|
| 373 |
+
lvis_eval.run()
|
| 374 |
+
lvis_eval.print_results()
|
| 375 |
+
|
| 376 |
+
# Pull the standard metrics from the LVIS results
|
| 377 |
+
results = lvis_eval.get_results()
|
| 378 |
+
results = {metric: float(results[metric] * 100) for metric in metrics}
|
| 379 |
+
logger.info("Evaluation results for {}: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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import contextlib
|
| 3 |
+
import io
|
| 4 |
+
import itertools
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
import numpy as np
|
| 8 |
+
import os
|
| 9 |
+
import tempfile
|
| 10 |
+
from collections import OrderedDict
|
| 11 |
+
from typing import Optional
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from tabulate import tabulate
|
| 14 |
+
|
| 15 |
+
from annotator.oneformer.detectron2.data import MetadataCatalog
|
| 16 |
+
from annotator.oneformer.detectron2.utils import comm
|
| 17 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 18 |
+
|
| 19 |
+
from .evaluator import DatasetEvaluator
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class COCOPanopticEvaluator(DatasetEvaluator):
|
| 25 |
+
"""
|
| 26 |
+
Evaluate Panoptic Quality metrics on COCO using PanopticAPI.
|
| 27 |
+
It saves panoptic segmentation prediction in `output_dir`
|
| 28 |
+
|
| 29 |
+
It contains a synchronize call and has to be called from all workers.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, dataset_name: str, output_dir: Optional[str] = None):
|
| 33 |
+
"""
|
| 34 |
+
Args:
|
| 35 |
+
dataset_name: name of the dataset
|
| 36 |
+
output_dir: output directory to save results for evaluation.
|
| 37 |
+
"""
|
| 38 |
+
self._metadata = MetadataCatalog.get(dataset_name)
|
| 39 |
+
self._thing_contiguous_id_to_dataset_id = {
|
| 40 |
+
v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items()
|
| 41 |
+
}
|
| 42 |
+
self._stuff_contiguous_id_to_dataset_id = {
|
| 43 |
+
v: k for k, v in self._metadata.stuff_dataset_id_to_contiguous_id.items()
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
self._output_dir = output_dir
|
| 47 |
+
if self._output_dir is not None:
|
| 48 |
+
PathManager.mkdirs(self._output_dir)
|
| 49 |
+
|
| 50 |
+
def reset(self):
|
| 51 |
+
self._predictions = []
|
| 52 |
+
|
| 53 |
+
def _convert_category_id(self, segment_info):
|
| 54 |
+
isthing = segment_info.pop("isthing", None)
|
| 55 |
+
if isthing is None:
|
| 56 |
+
# the model produces panoptic category id directly. No more conversion needed
|
| 57 |
+
return segment_info
|
| 58 |
+
if isthing is True:
|
| 59 |
+
segment_info["category_id"] = self._thing_contiguous_id_to_dataset_id[
|
| 60 |
+
segment_info["category_id"]
|
| 61 |
+
]
|
| 62 |
+
else:
|
| 63 |
+
segment_info["category_id"] = self._stuff_contiguous_id_to_dataset_id[
|
| 64 |
+
segment_info["category_id"]
|
| 65 |
+
]
|
| 66 |
+
return segment_info
|
| 67 |
+
|
| 68 |
+
def process(self, inputs, outputs):
|
| 69 |
+
from panopticapi.utils import id2rgb
|
| 70 |
+
|
| 71 |
+
for input, output in zip(inputs, outputs):
|
| 72 |
+
panoptic_img, segments_info = output["panoptic_seg"]
|
| 73 |
+
panoptic_img = panoptic_img.cpu().numpy()
|
| 74 |
+
if segments_info is None:
|
| 75 |
+
# If "segments_info" is None, we assume "panoptic_img" is a
|
| 76 |
+
# H*W int32 image storing the panoptic_id in the format of
|
| 77 |
+
# category_id * label_divisor + instance_id. We reserve -1 for
|
| 78 |
+
# VOID label, and add 1 to panoptic_img since the official
|
| 79 |
+
# evaluation script uses 0 for VOID label.
|
| 80 |
+
label_divisor = self._metadata.label_divisor
|
| 81 |
+
segments_info = []
|
| 82 |
+
for panoptic_label in np.unique(panoptic_img):
|
| 83 |
+
if panoptic_label == -1:
|
| 84 |
+
# VOID region.
|
| 85 |
+
continue
|
| 86 |
+
pred_class = panoptic_label // label_divisor
|
| 87 |
+
isthing = (
|
| 88 |
+
pred_class in self._metadata.thing_dataset_id_to_contiguous_id.values()
|
| 89 |
+
)
|
| 90 |
+
segments_info.append(
|
| 91 |
+
{
|
| 92 |
+
"id": int(panoptic_label) + 1,
|
| 93 |
+
"category_id": int(pred_class),
|
| 94 |
+
"isthing": bool(isthing),
|
| 95 |
+
}
|
| 96 |
+
)
|
| 97 |
+
# Official evaluation script uses 0 for VOID label.
|
| 98 |
+
panoptic_img += 1
|
| 99 |
+
|
| 100 |
+
file_name = os.path.basename(input["file_name"])
|
| 101 |
+
file_name_png = os.path.splitext(file_name)[0] + ".png"
|
| 102 |
+
with io.BytesIO() as out:
|
| 103 |
+
Image.fromarray(id2rgb(panoptic_img)).save(out, format="PNG")
|
| 104 |
+
segments_info = [self._convert_category_id(x) for x in segments_info]
|
| 105 |
+
self._predictions.append(
|
| 106 |
+
{
|
| 107 |
+
"image_id": input["image_id"],
|
| 108 |
+
"file_name": file_name_png,
|
| 109 |
+
"png_string": out.getvalue(),
|
| 110 |
+
"segments_info": segments_info,
|
| 111 |
+
}
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def evaluate(self):
|
| 115 |
+
comm.synchronize()
|
| 116 |
+
|
| 117 |
+
self._predictions = comm.gather(self._predictions)
|
| 118 |
+
self._predictions = list(itertools.chain(*self._predictions))
|
| 119 |
+
if not comm.is_main_process():
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
# PanopticApi requires local files
|
| 123 |
+
gt_json = PathManager.get_local_path(self._metadata.panoptic_json)
|
| 124 |
+
gt_folder = PathManager.get_local_path(self._metadata.panoptic_root)
|
| 125 |
+
|
| 126 |
+
with tempfile.TemporaryDirectory(prefix="panoptic_eval") as pred_dir:
|
| 127 |
+
logger.info("Writing all panoptic predictions to {} ...".format(pred_dir))
|
| 128 |
+
for p in self._predictions:
|
| 129 |
+
with open(os.path.join(pred_dir, p["file_name"]), "wb") as f:
|
| 130 |
+
f.write(p.pop("png_string"))
|
| 131 |
+
|
| 132 |
+
with open(gt_json, "r") as f:
|
| 133 |
+
json_data = json.load(f)
|
| 134 |
+
json_data["annotations"] = self._predictions
|
| 135 |
+
|
| 136 |
+
output_dir = self._output_dir or pred_dir
|
| 137 |
+
predictions_json = os.path.join(output_dir, "predictions.json")
|
| 138 |
+
with PathManager.open(predictions_json, "w") as f:
|
| 139 |
+
f.write(json.dumps(json_data))
|
| 140 |
+
|
| 141 |
+
from panopticapi.evaluation import pq_compute
|
| 142 |
+
|
| 143 |
+
with contextlib.redirect_stdout(io.StringIO()):
|
| 144 |
+
pq_res = pq_compute(
|
| 145 |
+
gt_json,
|
| 146 |
+
PathManager.get_local_path(predictions_json),
|
| 147 |
+
gt_folder=gt_folder,
|
| 148 |
+
pred_folder=pred_dir,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
res = {}
|
| 152 |
+
res["PQ"] = 100 * pq_res["All"]["pq"]
|
| 153 |
+
res["SQ"] = 100 * pq_res["All"]["sq"]
|
| 154 |
+
res["RQ"] = 100 * pq_res["All"]["rq"]
|
| 155 |
+
res["PQ_th"] = 100 * pq_res["Things"]["pq"]
|
| 156 |
+
res["SQ_th"] = 100 * pq_res["Things"]["sq"]
|
| 157 |
+
res["RQ_th"] = 100 * pq_res["Things"]["rq"]
|
| 158 |
+
res["PQ_st"] = 100 * pq_res["Stuff"]["pq"]
|
| 159 |
+
res["SQ_st"] = 100 * pq_res["Stuff"]["sq"]
|
| 160 |
+
res["RQ_st"] = 100 * pq_res["Stuff"]["rq"]
|
| 161 |
+
|
| 162 |
+
results = OrderedDict({"panoptic_seg": res})
|
| 163 |
+
_print_panoptic_results(pq_res)
|
| 164 |
+
|
| 165 |
+
return results
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _print_panoptic_results(pq_res):
|
| 169 |
+
headers = ["", "PQ", "SQ", "RQ", "#categories"]
|
| 170 |
+
data = []
|
| 171 |
+
for name in ["All", "Things", "Stuff"]:
|
| 172 |
+
row = [name] + [pq_res[name][k] * 100 for k in ["pq", "sq", "rq"]] + [pq_res[name]["n"]]
|
| 173 |
+
data.append(row)
|
| 174 |
+
table = tabulate(
|
| 175 |
+
data, headers=headers, tablefmt="pipe", floatfmt=".3f", stralign="center", numalign="center"
|
| 176 |
+
)
|
| 177 |
+
logger.info("Panoptic Evaluation Results:\n" + table)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
from annotator.oneformer.detectron2.utils.logger import setup_logger
|
| 182 |
+
|
| 183 |
+
logger = setup_logger()
|
| 184 |
+
import argparse
|
| 185 |
+
|
| 186 |
+
parser = argparse.ArgumentParser()
|
| 187 |
+
parser.add_argument("--gt-json")
|
| 188 |
+
parser.add_argument("--gt-dir")
|
| 189 |
+
parser.add_argument("--pred-json")
|
| 190 |
+
parser.add_argument("--pred-dir")
|
| 191 |
+
args = parser.parse_args()
|
| 192 |
+
|
| 193 |
+
from panopticapi.evaluation import pq_compute
|
| 194 |
+
|
| 195 |
+
with contextlib.redirect_stdout(io.StringIO()):
|
| 196 |
+
pq_res = pq_compute(
|
| 197 |
+
args.gt_json, args.pred_json, gt_folder=args.gt_dir, pred_folder=args.pred_dir
|
| 198 |
+
)
|
| 199 |
+
_print_panoptic_results(pq_res)
|
RAVE-main/annotator/oneformer/detectron2/evaluation/pascal_voc_evaluation.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
+
import tempfile
|
| 8 |
+
import xml.etree.ElementTree as ET
|
| 9 |
+
from collections import OrderedDict, defaultdict
|
| 10 |
+
from functools import lru_cache
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from annotator.oneformer.detectron2.data import MetadataCatalog
|
| 14 |
+
from annotator.oneformer.detectron2.utils import comm
|
| 15 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 16 |
+
|
| 17 |
+
from .evaluator import DatasetEvaluator
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class PascalVOCDetectionEvaluator(DatasetEvaluator):
|
| 21 |
+
"""
|
| 22 |
+
Evaluate Pascal VOC style AP for Pascal VOC dataset.
|
| 23 |
+
It contains a synchronization, therefore has to be called from all ranks.
|
| 24 |
+
|
| 25 |
+
Note that the concept of AP can be implemented in different ways and may not
|
| 26 |
+
produce identical results. This class mimics the implementation of the official
|
| 27 |
+
Pascal VOC Matlab API, and should produce similar but not identical results to the
|
| 28 |
+
official API.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, dataset_name):
|
| 32 |
+
"""
|
| 33 |
+
Args:
|
| 34 |
+
dataset_name (str): name of the dataset, e.g., "voc_2007_test"
|
| 35 |
+
"""
|
| 36 |
+
self._dataset_name = dataset_name
|
| 37 |
+
meta = MetadataCatalog.get(dataset_name)
|
| 38 |
+
|
| 39 |
+
# Too many tiny files, download all to local for speed.
|
| 40 |
+
annotation_dir_local = PathManager.get_local_path(
|
| 41 |
+
os.path.join(meta.dirname, "Annotations/")
|
| 42 |
+
)
|
| 43 |
+
self._anno_file_template = os.path.join(annotation_dir_local, "{}.xml")
|
| 44 |
+
self._image_set_path = os.path.join(meta.dirname, "ImageSets", "Main", meta.split + ".txt")
|
| 45 |
+
self._class_names = meta.thing_classes
|
| 46 |
+
assert meta.year in [2007, 2012], meta.year
|
| 47 |
+
self._is_2007 = meta.year == 2007
|
| 48 |
+
self._cpu_device = torch.device("cpu")
|
| 49 |
+
self._logger = logging.getLogger(__name__)
|
| 50 |
+
|
| 51 |
+
def reset(self):
|
| 52 |
+
self._predictions = defaultdict(list) # class name -> list of prediction strings
|
| 53 |
+
|
| 54 |
+
def process(self, inputs, outputs):
|
| 55 |
+
for input, output in zip(inputs, outputs):
|
| 56 |
+
image_id = input["image_id"]
|
| 57 |
+
instances = output["instances"].to(self._cpu_device)
|
| 58 |
+
boxes = instances.pred_boxes.tensor.numpy()
|
| 59 |
+
scores = instances.scores.tolist()
|
| 60 |
+
classes = instances.pred_classes.tolist()
|
| 61 |
+
for box, score, cls in zip(boxes, scores, classes):
|
| 62 |
+
xmin, ymin, xmax, ymax = box
|
| 63 |
+
# The inverse of data loading logic in `datasets/pascal_voc.py`
|
| 64 |
+
xmin += 1
|
| 65 |
+
ymin += 1
|
| 66 |
+
self._predictions[cls].append(
|
| 67 |
+
f"{image_id} {score:.3f} {xmin:.1f} {ymin:.1f} {xmax:.1f} {ymax:.1f}"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def evaluate(self):
|
| 71 |
+
"""
|
| 72 |
+
Returns:
|
| 73 |
+
dict: has a key "segm", whose value is a dict of "AP", "AP50", and "AP75".
|
| 74 |
+
"""
|
| 75 |
+
all_predictions = comm.gather(self._predictions, dst=0)
|
| 76 |
+
if not comm.is_main_process():
|
| 77 |
+
return
|
| 78 |
+
predictions = defaultdict(list)
|
| 79 |
+
for predictions_per_rank in all_predictions:
|
| 80 |
+
for clsid, lines in predictions_per_rank.items():
|
| 81 |
+
predictions[clsid].extend(lines)
|
| 82 |
+
del all_predictions
|
| 83 |
+
|
| 84 |
+
self._logger.info(
|
| 85 |
+
"Evaluating {} using {} metric. "
|
| 86 |
+
"Note that results do not use the official Matlab API.".format(
|
| 87 |
+
self._dataset_name, 2007 if self._is_2007 else 2012
|
| 88 |
+
)
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
with tempfile.TemporaryDirectory(prefix="pascal_voc_eval_") as dirname:
|
| 92 |
+
res_file_template = os.path.join(dirname, "{}.txt")
|
| 93 |
+
|
| 94 |
+
aps = defaultdict(list) # iou -> ap per class
|
| 95 |
+
for cls_id, cls_name in enumerate(self._class_names):
|
| 96 |
+
lines = predictions.get(cls_id, [""])
|
| 97 |
+
|
| 98 |
+
with open(res_file_template.format(cls_name), "w") as f:
|
| 99 |
+
f.write("\n".join(lines))
|
| 100 |
+
|
| 101 |
+
for thresh in range(50, 100, 5):
|
| 102 |
+
rec, prec, ap = voc_eval(
|
| 103 |
+
res_file_template,
|
| 104 |
+
self._anno_file_template,
|
| 105 |
+
self._image_set_path,
|
| 106 |
+
cls_name,
|
| 107 |
+
ovthresh=thresh / 100.0,
|
| 108 |
+
use_07_metric=self._is_2007,
|
| 109 |
+
)
|
| 110 |
+
aps[thresh].append(ap * 100)
|
| 111 |
+
|
| 112 |
+
ret = OrderedDict()
|
| 113 |
+
mAP = {iou: np.mean(x) for iou, x in aps.items()}
|
| 114 |
+
ret["bbox"] = {"AP": np.mean(list(mAP.values())), "AP50": mAP[50], "AP75": mAP[75]}
|
| 115 |
+
return ret
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
##############################################################################
|
| 119 |
+
#
|
| 120 |
+
# Below code is modified from
|
| 121 |
+
# https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/datasets/voc_eval.py
|
| 122 |
+
# --------------------------------------------------------
|
| 123 |
+
# Fast/er R-CNN
|
| 124 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 125 |
+
# Written by Bharath Hariharan
|
| 126 |
+
# --------------------------------------------------------
|
| 127 |
+
|
| 128 |
+
"""Python implementation of the PASCAL VOC devkit's AP evaluation code."""
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@lru_cache(maxsize=None)
|
| 132 |
+
def parse_rec(filename):
|
| 133 |
+
"""Parse a PASCAL VOC xml file."""
|
| 134 |
+
with PathManager.open(filename) as f:
|
| 135 |
+
tree = ET.parse(f)
|
| 136 |
+
objects = []
|
| 137 |
+
for obj in tree.findall("object"):
|
| 138 |
+
obj_struct = {}
|
| 139 |
+
obj_struct["name"] = obj.find("name").text
|
| 140 |
+
obj_struct["pose"] = obj.find("pose").text
|
| 141 |
+
obj_struct["truncated"] = int(obj.find("truncated").text)
|
| 142 |
+
obj_struct["difficult"] = int(obj.find("difficult").text)
|
| 143 |
+
bbox = obj.find("bndbox")
|
| 144 |
+
obj_struct["bbox"] = [
|
| 145 |
+
int(bbox.find("xmin").text),
|
| 146 |
+
int(bbox.find("ymin").text),
|
| 147 |
+
int(bbox.find("xmax").text),
|
| 148 |
+
int(bbox.find("ymax").text),
|
| 149 |
+
]
|
| 150 |
+
objects.append(obj_struct)
|
| 151 |
+
|
| 152 |
+
return objects
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def voc_ap(rec, prec, use_07_metric=False):
|
| 156 |
+
"""Compute VOC AP given precision and recall. If use_07_metric is true, uses
|
| 157 |
+
the VOC 07 11-point method (default:False).
|
| 158 |
+
"""
|
| 159 |
+
if use_07_metric:
|
| 160 |
+
# 11 point metric
|
| 161 |
+
ap = 0.0
|
| 162 |
+
for t in np.arange(0.0, 1.1, 0.1):
|
| 163 |
+
if np.sum(rec >= t) == 0:
|
| 164 |
+
p = 0
|
| 165 |
+
else:
|
| 166 |
+
p = np.max(prec[rec >= t])
|
| 167 |
+
ap = ap + p / 11.0
|
| 168 |
+
else:
|
| 169 |
+
# correct AP calculation
|
| 170 |
+
# first append sentinel values at the end
|
| 171 |
+
mrec = np.concatenate(([0.0], rec, [1.0]))
|
| 172 |
+
mpre = np.concatenate(([0.0], prec, [0.0]))
|
| 173 |
+
|
| 174 |
+
# compute the precision envelope
|
| 175 |
+
for i in range(mpre.size - 1, 0, -1):
|
| 176 |
+
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
|
| 177 |
+
|
| 178 |
+
# to calculate area under PR curve, look for points
|
| 179 |
+
# where X axis (recall) changes value
|
| 180 |
+
i = np.where(mrec[1:] != mrec[:-1])[0]
|
| 181 |
+
|
| 182 |
+
# and sum (\Delta recall) * prec
|
| 183 |
+
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
|
| 184 |
+
return ap
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def voc_eval(detpath, annopath, imagesetfile, classname, ovthresh=0.5, use_07_metric=False):
|
| 188 |
+
"""rec, prec, ap = voc_eval(detpath,
|
| 189 |
+
annopath,
|
| 190 |
+
imagesetfile,
|
| 191 |
+
classname,
|
| 192 |
+
[ovthresh],
|
| 193 |
+
[use_07_metric])
|
| 194 |
+
|
| 195 |
+
Top level function that does the PASCAL VOC evaluation.
|
| 196 |
+
|
| 197 |
+
detpath: Path to detections
|
| 198 |
+
detpath.format(classname) should produce the detection results file.
|
| 199 |
+
annopath: Path to annotations
|
| 200 |
+
annopath.format(imagename) should be the xml annotations file.
|
| 201 |
+
imagesetfile: Text file containing the list of images, one image per line.
|
| 202 |
+
classname: Category name (duh)
|
| 203 |
+
[ovthresh]: Overlap threshold (default = 0.5)
|
| 204 |
+
[use_07_metric]: Whether to use VOC07's 11 point AP computation
|
| 205 |
+
(default False)
|
| 206 |
+
"""
|
| 207 |
+
# assumes detections are in detpath.format(classname)
|
| 208 |
+
# assumes annotations are in annopath.format(imagename)
|
| 209 |
+
# assumes imagesetfile is a text file with each line an image name
|
| 210 |
+
|
| 211 |
+
# first load gt
|
| 212 |
+
# read list of images
|
| 213 |
+
with PathManager.open(imagesetfile, "r") as f:
|
| 214 |
+
lines = f.readlines()
|
| 215 |
+
imagenames = [x.strip() for x in lines]
|
| 216 |
+
|
| 217 |
+
# load annots
|
| 218 |
+
recs = {}
|
| 219 |
+
for imagename in imagenames:
|
| 220 |
+
recs[imagename] = parse_rec(annopath.format(imagename))
|
| 221 |
+
|
| 222 |
+
# extract gt objects for this class
|
| 223 |
+
class_recs = {}
|
| 224 |
+
npos = 0
|
| 225 |
+
for imagename in imagenames:
|
| 226 |
+
R = [obj for obj in recs[imagename] if obj["name"] == classname]
|
| 227 |
+
bbox = np.array([x["bbox"] for x in R])
|
| 228 |
+
difficult = np.array([x["difficult"] for x in R]).astype(bool)
|
| 229 |
+
# difficult = np.array([False for x in R]).astype(bool) # treat all "difficult" as GT
|
| 230 |
+
det = [False] * len(R)
|
| 231 |
+
npos = npos + sum(~difficult)
|
| 232 |
+
class_recs[imagename] = {"bbox": bbox, "difficult": difficult, "det": det}
|
| 233 |
+
|
| 234 |
+
# read dets
|
| 235 |
+
detfile = detpath.format(classname)
|
| 236 |
+
with open(detfile, "r") as f:
|
| 237 |
+
lines = f.readlines()
|
| 238 |
+
|
| 239 |
+
splitlines = [x.strip().split(" ") for x in lines]
|
| 240 |
+
image_ids = [x[0] for x in splitlines]
|
| 241 |
+
confidence = np.array([float(x[1]) for x in splitlines])
|
| 242 |
+
BB = np.array([[float(z) for z in x[2:]] for x in splitlines]).reshape(-1, 4)
|
| 243 |
+
|
| 244 |
+
# sort by confidence
|
| 245 |
+
sorted_ind = np.argsort(-confidence)
|
| 246 |
+
BB = BB[sorted_ind, :]
|
| 247 |
+
image_ids = [image_ids[x] for x in sorted_ind]
|
| 248 |
+
|
| 249 |
+
# go down dets and mark TPs and FPs
|
| 250 |
+
nd = len(image_ids)
|
| 251 |
+
tp = np.zeros(nd)
|
| 252 |
+
fp = np.zeros(nd)
|
| 253 |
+
for d in range(nd):
|
| 254 |
+
R = class_recs[image_ids[d]]
|
| 255 |
+
bb = BB[d, :].astype(float)
|
| 256 |
+
ovmax = -np.inf
|
| 257 |
+
BBGT = R["bbox"].astype(float)
|
| 258 |
+
|
| 259 |
+
if BBGT.size > 0:
|
| 260 |
+
# compute overlaps
|
| 261 |
+
# intersection
|
| 262 |
+
ixmin = np.maximum(BBGT[:, 0], bb[0])
|
| 263 |
+
iymin = np.maximum(BBGT[:, 1], bb[1])
|
| 264 |
+
ixmax = np.minimum(BBGT[:, 2], bb[2])
|
| 265 |
+
iymax = np.minimum(BBGT[:, 3], bb[3])
|
| 266 |
+
iw = np.maximum(ixmax - ixmin + 1.0, 0.0)
|
| 267 |
+
ih = np.maximum(iymax - iymin + 1.0, 0.0)
|
| 268 |
+
inters = iw * ih
|
| 269 |
+
|
| 270 |
+
# union
|
| 271 |
+
uni = (
|
| 272 |
+
(bb[2] - bb[0] + 1.0) * (bb[3] - bb[1] + 1.0)
|
| 273 |
+
+ (BBGT[:, 2] - BBGT[:, 0] + 1.0) * (BBGT[:, 3] - BBGT[:, 1] + 1.0)
|
| 274 |
+
- inters
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
overlaps = inters / uni
|
| 278 |
+
ovmax = np.max(overlaps)
|
| 279 |
+
jmax = np.argmax(overlaps)
|
| 280 |
+
|
| 281 |
+
if ovmax > ovthresh:
|
| 282 |
+
if not R["difficult"][jmax]:
|
| 283 |
+
if not R["det"][jmax]:
|
| 284 |
+
tp[d] = 1.0
|
| 285 |
+
R["det"][jmax] = 1
|
| 286 |
+
else:
|
| 287 |
+
fp[d] = 1.0
|
| 288 |
+
else:
|
| 289 |
+
fp[d] = 1.0
|
| 290 |
+
|
| 291 |
+
# compute precision recall
|
| 292 |
+
fp = np.cumsum(fp)
|
| 293 |
+
tp = np.cumsum(tp)
|
| 294 |
+
rec = tp / float(npos)
|
| 295 |
+
# avoid divide by zero in case the first detection matches a difficult
|
| 296 |
+
# ground truth
|
| 297 |
+
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
|
| 298 |
+
ap = voc_ap(rec, prec, use_07_metric)
|
| 299 |
+
|
| 300 |
+
return rec, prec, ap
|
RAVE-main/annotator/oneformer/detectron2/evaluation/rotated_coco_evaluation.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import itertools
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
import torch
|
| 7 |
+
from annotator.oneformer.pycocotools.cocoeval import COCOeval, maskUtils
|
| 8 |
+
|
| 9 |
+
from annotator.oneformer.detectron2.structures import BoxMode, RotatedBoxes, pairwise_iou_rotated
|
| 10 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 11 |
+
|
| 12 |
+
from .coco_evaluation import COCOEvaluator
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class RotatedCOCOeval(COCOeval):
|
| 16 |
+
@staticmethod
|
| 17 |
+
def is_rotated(box_list):
|
| 18 |
+
if type(box_list) == np.ndarray:
|
| 19 |
+
return box_list.shape[1] == 5
|
| 20 |
+
elif type(box_list) == list:
|
| 21 |
+
if box_list == []: # cannot decide the box_dim
|
| 22 |
+
return False
|
| 23 |
+
return np.all(
|
| 24 |
+
np.array(
|
| 25 |
+
[
|
| 26 |
+
(len(obj) == 5) and ((type(obj) == list) or (type(obj) == np.ndarray))
|
| 27 |
+
for obj in box_list
|
| 28 |
+
]
|
| 29 |
+
)
|
| 30 |
+
)
|
| 31 |
+
return False
|
| 32 |
+
|
| 33 |
+
@staticmethod
|
| 34 |
+
def boxlist_to_tensor(boxlist, output_box_dim):
|
| 35 |
+
if type(boxlist) == np.ndarray:
|
| 36 |
+
box_tensor = torch.from_numpy(boxlist)
|
| 37 |
+
elif type(boxlist) == list:
|
| 38 |
+
if boxlist == []:
|
| 39 |
+
return torch.zeros((0, output_box_dim), dtype=torch.float32)
|
| 40 |
+
else:
|
| 41 |
+
box_tensor = torch.FloatTensor(boxlist)
|
| 42 |
+
else:
|
| 43 |
+
raise Exception("Unrecognized boxlist type")
|
| 44 |
+
|
| 45 |
+
input_box_dim = box_tensor.shape[1]
|
| 46 |
+
if input_box_dim != output_box_dim:
|
| 47 |
+
if input_box_dim == 4 and output_box_dim == 5:
|
| 48 |
+
box_tensor = BoxMode.convert(box_tensor, BoxMode.XYWH_ABS, BoxMode.XYWHA_ABS)
|
| 49 |
+
else:
|
| 50 |
+
raise Exception(
|
| 51 |
+
"Unable to convert from {}-dim box to {}-dim box".format(
|
| 52 |
+
input_box_dim, output_box_dim
|
| 53 |
+
)
|
| 54 |
+
)
|
| 55 |
+
return box_tensor
|
| 56 |
+
|
| 57 |
+
def compute_iou_dt_gt(self, dt, gt, is_crowd):
|
| 58 |
+
if self.is_rotated(dt) or self.is_rotated(gt):
|
| 59 |
+
# TODO: take is_crowd into consideration
|
| 60 |
+
assert all(c == 0 for c in is_crowd)
|
| 61 |
+
dt = RotatedBoxes(self.boxlist_to_tensor(dt, output_box_dim=5))
|
| 62 |
+
gt = RotatedBoxes(self.boxlist_to_tensor(gt, output_box_dim=5))
|
| 63 |
+
return pairwise_iou_rotated(dt, gt)
|
| 64 |
+
else:
|
| 65 |
+
# This is the same as the classical COCO evaluation
|
| 66 |
+
return maskUtils.iou(dt, gt, is_crowd)
|
| 67 |
+
|
| 68 |
+
def computeIoU(self, imgId, catId):
|
| 69 |
+
p = self.params
|
| 70 |
+
if p.useCats:
|
| 71 |
+
gt = self._gts[imgId, catId]
|
| 72 |
+
dt = self._dts[imgId, catId]
|
| 73 |
+
else:
|
| 74 |
+
gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
|
| 75 |
+
dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
|
| 76 |
+
if len(gt) == 0 and len(dt) == 0:
|
| 77 |
+
return []
|
| 78 |
+
inds = np.argsort([-d["score"] for d in dt], kind="mergesort")
|
| 79 |
+
dt = [dt[i] for i in inds]
|
| 80 |
+
if len(dt) > p.maxDets[-1]:
|
| 81 |
+
dt = dt[0 : p.maxDets[-1]]
|
| 82 |
+
|
| 83 |
+
assert p.iouType == "bbox", "unsupported iouType for iou computation"
|
| 84 |
+
|
| 85 |
+
g = [g["bbox"] for g in gt]
|
| 86 |
+
d = [d["bbox"] for d in dt]
|
| 87 |
+
|
| 88 |
+
# compute iou between each dt and gt region
|
| 89 |
+
iscrowd = [int(o["iscrowd"]) for o in gt]
|
| 90 |
+
|
| 91 |
+
# Note: this function is copied from cocoeval.py in cocoapi
|
| 92 |
+
# and the major difference is here.
|
| 93 |
+
ious = self.compute_iou_dt_gt(d, g, iscrowd)
|
| 94 |
+
return ious
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class RotatedCOCOEvaluator(COCOEvaluator):
|
| 98 |
+
"""
|
| 99 |
+
Evaluate object proposal/instance detection outputs using COCO-like metrics and APIs,
|
| 100 |
+
with rotated boxes support.
|
| 101 |
+
Note: this uses IOU only and does not consider angle differences.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def process(self, inputs, outputs):
|
| 105 |
+
"""
|
| 106 |
+
Args:
|
| 107 |
+
inputs: the inputs to a COCO model (e.g., GeneralizedRCNN).
|
| 108 |
+
It is a list of dict. Each dict corresponds to an image and
|
| 109 |
+
contains keys like "height", "width", "file_name", "image_id".
|
| 110 |
+
outputs: the outputs of a COCO model. It is a list of dicts with key
|
| 111 |
+
"instances" that contains :class:`Instances`.
|
| 112 |
+
"""
|
| 113 |
+
for input, output in zip(inputs, outputs):
|
| 114 |
+
prediction = {"image_id": input["image_id"]}
|
| 115 |
+
|
| 116 |
+
if "instances" in output:
|
| 117 |
+
instances = output["instances"].to(self._cpu_device)
|
| 118 |
+
|
| 119 |
+
prediction["instances"] = self.instances_to_json(instances, input["image_id"])
|
| 120 |
+
if "proposals" in output:
|
| 121 |
+
prediction["proposals"] = output["proposals"].to(self._cpu_device)
|
| 122 |
+
self._predictions.append(prediction)
|
| 123 |
+
|
| 124 |
+
def instances_to_json(self, instances, img_id):
|
| 125 |
+
num_instance = len(instances)
|
| 126 |
+
if num_instance == 0:
|
| 127 |
+
return []
|
| 128 |
+
|
| 129 |
+
boxes = instances.pred_boxes.tensor.numpy()
|
| 130 |
+
if boxes.shape[1] == 4:
|
| 131 |
+
boxes = BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)
|
| 132 |
+
boxes = boxes.tolist()
|
| 133 |
+
scores = instances.scores.tolist()
|
| 134 |
+
classes = instances.pred_classes.tolist()
|
| 135 |
+
|
| 136 |
+
results = []
|
| 137 |
+
for k in range(num_instance):
|
| 138 |
+
result = {
|
| 139 |
+
"image_id": img_id,
|
| 140 |
+
"category_id": classes[k],
|
| 141 |
+
"bbox": boxes[k],
|
| 142 |
+
"score": scores[k],
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
results.append(result)
|
| 146 |
+
return results
|
| 147 |
+
|
| 148 |
+
def _eval_predictions(self, predictions, img_ids=None): # img_ids: unused
|
| 149 |
+
"""
|
| 150 |
+
Evaluate predictions on the given tasks.
|
| 151 |
+
Fill self._results with the metrics of the tasks.
|
| 152 |
+
"""
|
| 153 |
+
self._logger.info("Preparing results for COCO format ...")
|
| 154 |
+
coco_results = list(itertools.chain(*[x["instances"] for x in predictions]))
|
| 155 |
+
|
| 156 |
+
# unmap the category ids for COCO
|
| 157 |
+
if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"):
|
| 158 |
+
reverse_id_mapping = {
|
| 159 |
+
v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items()
|
| 160 |
+
}
|
| 161 |
+
for result in coco_results:
|
| 162 |
+
result["category_id"] = reverse_id_mapping[result["category_id"]]
|
| 163 |
+
|
| 164 |
+
if self._output_dir:
|
| 165 |
+
file_path = os.path.join(self._output_dir, "coco_instances_results.json")
|
| 166 |
+
self._logger.info("Saving results to {}".format(file_path))
|
| 167 |
+
with PathManager.open(file_path, "w") as f:
|
| 168 |
+
f.write(json.dumps(coco_results))
|
| 169 |
+
f.flush()
|
| 170 |
+
|
| 171 |
+
if not self._do_evaluation:
|
| 172 |
+
self._logger.info("Annotations are not available for evaluation.")
|
| 173 |
+
return
|
| 174 |
+
|
| 175 |
+
self._logger.info("Evaluating predictions ...")
|
| 176 |
+
|
| 177 |
+
assert self._tasks is None or set(self._tasks) == {
|
| 178 |
+
"bbox"
|
| 179 |
+
}, "[RotatedCOCOEvaluator] Only bbox evaluation is supported"
|
| 180 |
+
coco_eval = (
|
| 181 |
+
self._evaluate_predictions_on_coco(self._coco_api, coco_results)
|
| 182 |
+
if len(coco_results) > 0
|
| 183 |
+
else None # cocoapi does not handle empty results very well
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
task = "bbox"
|
| 187 |
+
res = self._derive_coco_results(
|
| 188 |
+
coco_eval, task, class_names=self._metadata.get("thing_classes")
|
| 189 |
+
)
|
| 190 |
+
self._results[task] = res
|
| 191 |
+
|
| 192 |
+
def _evaluate_predictions_on_coco(self, coco_gt, coco_results):
|
| 193 |
+
"""
|
| 194 |
+
Evaluate the coco results using COCOEval API.
|
| 195 |
+
"""
|
| 196 |
+
assert len(coco_results) > 0
|
| 197 |
+
|
| 198 |
+
coco_dt = coco_gt.loadRes(coco_results)
|
| 199 |
+
|
| 200 |
+
# Only bbox is supported for now
|
| 201 |
+
coco_eval = RotatedCOCOeval(coco_gt, coco_dt, iouType="bbox")
|
| 202 |
+
|
| 203 |
+
coco_eval.evaluate()
|
| 204 |
+
coco_eval.accumulate()
|
| 205 |
+
coco_eval.summarize()
|
| 206 |
+
|
| 207 |
+
return coco_eval
|
RAVE-main/annotator/oneformer/detectron2/evaluation/sem_seg_evaluation.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import itertools
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
from typing import Optional, Union
|
| 9 |
+
import annotator.oneformer.pycocotools.mask as mask_util
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog
|
| 14 |
+
from annotator.oneformer.detectron2.utils.comm import all_gather, is_main_process, synchronize
|
| 15 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 16 |
+
|
| 17 |
+
from .evaluator import DatasetEvaluator
|
| 18 |
+
|
| 19 |
+
_CV2_IMPORTED = True
|
| 20 |
+
try:
|
| 21 |
+
import cv2 # noqa
|
| 22 |
+
except ImportError:
|
| 23 |
+
# OpenCV is an optional dependency at the moment
|
| 24 |
+
_CV2_IMPORTED = False
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_image_into_numpy_array(
|
| 28 |
+
filename: str,
|
| 29 |
+
copy: bool = False,
|
| 30 |
+
dtype: Optional[Union[np.dtype, str]] = None,
|
| 31 |
+
) -> np.ndarray:
|
| 32 |
+
with PathManager.open(filename, "rb") as f:
|
| 33 |
+
array = np.array(Image.open(f), copy=copy, dtype=dtype)
|
| 34 |
+
return array
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SemSegEvaluator(DatasetEvaluator):
|
| 38 |
+
"""
|
| 39 |
+
Evaluate semantic segmentation metrics.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
dataset_name,
|
| 45 |
+
distributed=True,
|
| 46 |
+
output_dir=None,
|
| 47 |
+
*,
|
| 48 |
+
sem_seg_loading_fn=load_image_into_numpy_array,
|
| 49 |
+
num_classes=None,
|
| 50 |
+
ignore_label=None,
|
| 51 |
+
):
|
| 52 |
+
"""
|
| 53 |
+
Args:
|
| 54 |
+
dataset_name (str): name of the dataset to be evaluated.
|
| 55 |
+
distributed (bool): if True, will collect results from all ranks for evaluation.
|
| 56 |
+
Otherwise, will evaluate the results in the current process.
|
| 57 |
+
output_dir (str): an output directory to dump results.
|
| 58 |
+
sem_seg_loading_fn: function to read sem seg file and load into numpy array.
|
| 59 |
+
Default provided, but projects can customize.
|
| 60 |
+
num_classes, ignore_label: deprecated argument
|
| 61 |
+
"""
|
| 62 |
+
self._logger = logging.getLogger(__name__)
|
| 63 |
+
if num_classes is not None:
|
| 64 |
+
self._logger.warn(
|
| 65 |
+
"SemSegEvaluator(num_classes) is deprecated! It should be obtained from metadata."
|
| 66 |
+
)
|
| 67 |
+
if ignore_label is not None:
|
| 68 |
+
self._logger.warn(
|
| 69 |
+
"SemSegEvaluator(ignore_label) is deprecated! It should be obtained from metadata."
|
| 70 |
+
)
|
| 71 |
+
self._dataset_name = dataset_name
|
| 72 |
+
self._distributed = distributed
|
| 73 |
+
self._output_dir = output_dir
|
| 74 |
+
|
| 75 |
+
self._cpu_device = torch.device("cpu")
|
| 76 |
+
|
| 77 |
+
self.input_file_to_gt_file = {
|
| 78 |
+
dataset_record["file_name"]: dataset_record["sem_seg_file_name"]
|
| 79 |
+
for dataset_record in DatasetCatalog.get(dataset_name)
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
meta = MetadataCatalog.get(dataset_name)
|
| 83 |
+
# Dict that maps contiguous training ids to COCO category ids
|
| 84 |
+
try:
|
| 85 |
+
c2d = meta.stuff_dataset_id_to_contiguous_id
|
| 86 |
+
self._contiguous_id_to_dataset_id = {v: k for k, v in c2d.items()}
|
| 87 |
+
except AttributeError:
|
| 88 |
+
self._contiguous_id_to_dataset_id = None
|
| 89 |
+
self._class_names = meta.stuff_classes
|
| 90 |
+
self.sem_seg_loading_fn = sem_seg_loading_fn
|
| 91 |
+
self._num_classes = len(meta.stuff_classes)
|
| 92 |
+
if num_classes is not None:
|
| 93 |
+
assert self._num_classes == num_classes, f"{self._num_classes} != {num_classes}"
|
| 94 |
+
self._ignore_label = ignore_label if ignore_label is not None else meta.ignore_label
|
| 95 |
+
|
| 96 |
+
# This is because cv2.erode did not work for int datatype. Only works for uint8.
|
| 97 |
+
self._compute_boundary_iou = True
|
| 98 |
+
if not _CV2_IMPORTED:
|
| 99 |
+
self._compute_boundary_iou = False
|
| 100 |
+
self._logger.warn(
|
| 101 |
+
"""Boundary IoU calculation requires OpenCV. B-IoU metrics are
|
| 102 |
+
not going to be computed because OpenCV is not available to import."""
|
| 103 |
+
)
|
| 104 |
+
if self._num_classes >= np.iinfo(np.uint8).max:
|
| 105 |
+
self._compute_boundary_iou = False
|
| 106 |
+
self._logger.warn(
|
| 107 |
+
f"""SemSegEvaluator(num_classes) is more than supported value for Boundary IoU calculation!
|
| 108 |
+
B-IoU metrics are not going to be computed. Max allowed value (exclusive)
|
| 109 |
+
for num_classes for calculating Boundary IoU is {np.iinfo(np.uint8).max}.
|
| 110 |
+
The number of classes of dataset {self._dataset_name} is {self._num_classes}"""
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
def reset(self):
|
| 114 |
+
self._conf_matrix = np.zeros((self._num_classes + 1, self._num_classes + 1), dtype=np.int64)
|
| 115 |
+
self._b_conf_matrix = np.zeros(
|
| 116 |
+
(self._num_classes + 1, self._num_classes + 1), dtype=np.int64
|
| 117 |
+
)
|
| 118 |
+
self._predictions = []
|
| 119 |
+
|
| 120 |
+
def process(self, inputs, outputs):
|
| 121 |
+
"""
|
| 122 |
+
Args:
|
| 123 |
+
inputs: the inputs to a model.
|
| 124 |
+
It is a list of dicts. Each dict corresponds to an image and
|
| 125 |
+
contains keys like "height", "width", "file_name".
|
| 126 |
+
outputs: the outputs of a model. It is either list of semantic segmentation predictions
|
| 127 |
+
(Tensor [H, W]) or list of dicts with key "sem_seg" that contains semantic
|
| 128 |
+
segmentation prediction in the same format.
|
| 129 |
+
"""
|
| 130 |
+
for input, output in zip(inputs, outputs):
|
| 131 |
+
output = output["sem_seg"].argmax(dim=0).to(self._cpu_device)
|
| 132 |
+
pred = np.array(output, dtype=np.int)
|
| 133 |
+
gt_filename = self.input_file_to_gt_file[input["file_name"]]
|
| 134 |
+
gt = self.sem_seg_loading_fn(gt_filename, dtype=np.int)
|
| 135 |
+
|
| 136 |
+
gt[gt == self._ignore_label] = self._num_classes
|
| 137 |
+
|
| 138 |
+
self._conf_matrix += np.bincount(
|
| 139 |
+
(self._num_classes + 1) * pred.reshape(-1) + gt.reshape(-1),
|
| 140 |
+
minlength=self._conf_matrix.size,
|
| 141 |
+
).reshape(self._conf_matrix.shape)
|
| 142 |
+
|
| 143 |
+
if self._compute_boundary_iou:
|
| 144 |
+
b_gt = self._mask_to_boundary(gt.astype(np.uint8))
|
| 145 |
+
b_pred = self._mask_to_boundary(pred.astype(np.uint8))
|
| 146 |
+
|
| 147 |
+
self._b_conf_matrix += np.bincount(
|
| 148 |
+
(self._num_classes + 1) * b_pred.reshape(-1) + b_gt.reshape(-1),
|
| 149 |
+
minlength=self._conf_matrix.size,
|
| 150 |
+
).reshape(self._conf_matrix.shape)
|
| 151 |
+
|
| 152 |
+
self._predictions.extend(self.encode_json_sem_seg(pred, input["file_name"]))
|
| 153 |
+
|
| 154 |
+
def evaluate(self):
|
| 155 |
+
"""
|
| 156 |
+
Evaluates standard semantic segmentation metrics (http://cocodataset.org/#stuff-eval):
|
| 157 |
+
|
| 158 |
+
* Mean intersection-over-union averaged across classes (mIoU)
|
| 159 |
+
* Frequency Weighted IoU (fwIoU)
|
| 160 |
+
* Mean pixel accuracy averaged across classes (mACC)
|
| 161 |
+
* Pixel Accuracy (pACC)
|
| 162 |
+
"""
|
| 163 |
+
if self._distributed:
|
| 164 |
+
synchronize()
|
| 165 |
+
conf_matrix_list = all_gather(self._conf_matrix)
|
| 166 |
+
b_conf_matrix_list = all_gather(self._b_conf_matrix)
|
| 167 |
+
self._predictions = all_gather(self._predictions)
|
| 168 |
+
self._predictions = list(itertools.chain(*self._predictions))
|
| 169 |
+
if not is_main_process():
|
| 170 |
+
return
|
| 171 |
+
|
| 172 |
+
self._conf_matrix = np.zeros_like(self._conf_matrix)
|
| 173 |
+
for conf_matrix in conf_matrix_list:
|
| 174 |
+
self._conf_matrix += conf_matrix
|
| 175 |
+
|
| 176 |
+
self._b_conf_matrix = np.zeros_like(self._b_conf_matrix)
|
| 177 |
+
for b_conf_matrix in b_conf_matrix_list:
|
| 178 |
+
self._b_conf_matrix += b_conf_matrix
|
| 179 |
+
|
| 180 |
+
if self._output_dir:
|
| 181 |
+
PathManager.mkdirs(self._output_dir)
|
| 182 |
+
file_path = os.path.join(self._output_dir, "sem_seg_predictions.json")
|
| 183 |
+
with PathManager.open(file_path, "w") as f:
|
| 184 |
+
f.write(json.dumps(self._predictions))
|
| 185 |
+
|
| 186 |
+
acc = np.full(self._num_classes, np.nan, dtype=np.float)
|
| 187 |
+
iou = np.full(self._num_classes, np.nan, dtype=np.float)
|
| 188 |
+
tp = self._conf_matrix.diagonal()[:-1].astype(np.float)
|
| 189 |
+
pos_gt = np.sum(self._conf_matrix[:-1, :-1], axis=0).astype(np.float)
|
| 190 |
+
class_weights = pos_gt / np.sum(pos_gt)
|
| 191 |
+
pos_pred = np.sum(self._conf_matrix[:-1, :-1], axis=1).astype(np.float)
|
| 192 |
+
acc_valid = pos_gt > 0
|
| 193 |
+
acc[acc_valid] = tp[acc_valid] / pos_gt[acc_valid]
|
| 194 |
+
union = pos_gt + pos_pred - tp
|
| 195 |
+
iou_valid = np.logical_and(acc_valid, union > 0)
|
| 196 |
+
iou[iou_valid] = tp[iou_valid] / union[iou_valid]
|
| 197 |
+
macc = np.sum(acc[acc_valid]) / np.sum(acc_valid)
|
| 198 |
+
miou = np.sum(iou[iou_valid]) / np.sum(iou_valid)
|
| 199 |
+
fiou = np.sum(iou[iou_valid] * class_weights[iou_valid])
|
| 200 |
+
pacc = np.sum(tp) / np.sum(pos_gt)
|
| 201 |
+
|
| 202 |
+
if self._compute_boundary_iou:
|
| 203 |
+
b_iou = np.full(self._num_classes, np.nan, dtype=np.float)
|
| 204 |
+
b_tp = self._b_conf_matrix.diagonal()[:-1].astype(np.float)
|
| 205 |
+
b_pos_gt = np.sum(self._b_conf_matrix[:-1, :-1], axis=0).astype(np.float)
|
| 206 |
+
b_pos_pred = np.sum(self._b_conf_matrix[:-1, :-1], axis=1).astype(np.float)
|
| 207 |
+
b_union = b_pos_gt + b_pos_pred - b_tp
|
| 208 |
+
b_iou_valid = b_union > 0
|
| 209 |
+
b_iou[b_iou_valid] = b_tp[b_iou_valid] / b_union[b_iou_valid]
|
| 210 |
+
|
| 211 |
+
res = {}
|
| 212 |
+
res["mIoU"] = 100 * miou
|
| 213 |
+
res["fwIoU"] = 100 * fiou
|
| 214 |
+
for i, name in enumerate(self._class_names):
|
| 215 |
+
res[f"IoU-{name}"] = 100 * iou[i]
|
| 216 |
+
if self._compute_boundary_iou:
|
| 217 |
+
res[f"BoundaryIoU-{name}"] = 100 * b_iou[i]
|
| 218 |
+
res[f"min(IoU, B-Iou)-{name}"] = 100 * min(iou[i], b_iou[i])
|
| 219 |
+
res["mACC"] = 100 * macc
|
| 220 |
+
res["pACC"] = 100 * pacc
|
| 221 |
+
for i, name in enumerate(self._class_names):
|
| 222 |
+
res[f"ACC-{name}"] = 100 * acc[i]
|
| 223 |
+
|
| 224 |
+
if self._output_dir:
|
| 225 |
+
file_path = os.path.join(self._output_dir, "sem_seg_evaluation.pth")
|
| 226 |
+
with PathManager.open(file_path, "wb") as f:
|
| 227 |
+
torch.save(res, f)
|
| 228 |
+
results = OrderedDict({"sem_seg": res})
|
| 229 |
+
self._logger.info(results)
|
| 230 |
+
return results
|
| 231 |
+
|
| 232 |
+
def encode_json_sem_seg(self, sem_seg, input_file_name):
|
| 233 |
+
"""
|
| 234 |
+
Convert semantic segmentation to COCO stuff format with segments encoded as RLEs.
|
| 235 |
+
See http://cocodataset.org/#format-results
|
| 236 |
+
"""
|
| 237 |
+
json_list = []
|
| 238 |
+
for label in np.unique(sem_seg):
|
| 239 |
+
if self._contiguous_id_to_dataset_id is not None:
|
| 240 |
+
assert (
|
| 241 |
+
label in self._contiguous_id_to_dataset_id
|
| 242 |
+
), "Label {} is not in the metadata info for {}".format(label, self._dataset_name)
|
| 243 |
+
dataset_id = self._contiguous_id_to_dataset_id[label]
|
| 244 |
+
else:
|
| 245 |
+
dataset_id = int(label)
|
| 246 |
+
mask = (sem_seg == label).astype(np.uint8)
|
| 247 |
+
mask_rle = mask_util.encode(np.array(mask[:, :, None], order="F"))[0]
|
| 248 |
+
mask_rle["counts"] = mask_rle["counts"].decode("utf-8")
|
| 249 |
+
json_list.append(
|
| 250 |
+
{"file_name": input_file_name, "category_id": dataset_id, "segmentation": mask_rle}
|
| 251 |
+
)
|
| 252 |
+
return json_list
|
| 253 |
+
|
| 254 |
+
def _mask_to_boundary(self, mask: np.ndarray, dilation_ratio=0.02):
|
| 255 |
+
assert mask.ndim == 2, "mask_to_boundary expects a 2-dimensional image"
|
| 256 |
+
h, w = mask.shape
|
| 257 |
+
diag_len = np.sqrt(h**2 + w**2)
|
| 258 |
+
dilation = max(1, int(round(dilation_ratio * diag_len)))
|
| 259 |
+
kernel = np.ones((3, 3), dtype=np.uint8)
|
| 260 |
+
|
| 261 |
+
padded_mask = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0)
|
| 262 |
+
eroded_mask_with_padding = cv2.erode(padded_mask, kernel, iterations=dilation)
|
| 263 |
+
eroded_mask = eroded_mask_with_padding[1:-1, 1:-1]
|
| 264 |
+
boundary = mask - eroded_mask
|
| 265 |
+
return boundary
|
RAVE-main/annotator/oneformer/detectron2/evaluation/testing.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import logging
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pprint
|
| 5 |
+
import sys
|
| 6 |
+
from collections.abc import Mapping
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def print_csv_format(results):
|
| 10 |
+
"""
|
| 11 |
+
Print main metrics in a format similar to Detectron,
|
| 12 |
+
so that they are easy to copypaste into a spreadsheet.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
results (OrderedDict[dict]): task_name -> {metric -> score}
|
| 16 |
+
unordered dict can also be printed, but in arbitrary order
|
| 17 |
+
"""
|
| 18 |
+
assert isinstance(results, Mapping) or not len(results), results
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
for task, res in results.items():
|
| 21 |
+
if isinstance(res, Mapping):
|
| 22 |
+
# Don't print "AP-category" metrics since they are usually not tracked.
|
| 23 |
+
important_res = [(k, v) for k, v in res.items() if "-" not in k]
|
| 24 |
+
logger.info("copypaste: Task: {}".format(task))
|
| 25 |
+
logger.info("copypaste: " + ",".join([k[0] for k in important_res]))
|
| 26 |
+
logger.info("copypaste: " + ",".join(["{0:.4f}".format(k[1]) for k in important_res]))
|
| 27 |
+
else:
|
| 28 |
+
logger.info(f"copypaste: {task}={res}")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def verify_results(cfg, results):
|
| 32 |
+
"""
|
| 33 |
+
Args:
|
| 34 |
+
results (OrderedDict[dict]): task_name -> {metric -> score}
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
bool: whether the verification succeeds or not
|
| 38 |
+
"""
|
| 39 |
+
expected_results = cfg.TEST.EXPECTED_RESULTS
|
| 40 |
+
if not len(expected_results):
|
| 41 |
+
return True
|
| 42 |
+
|
| 43 |
+
ok = True
|
| 44 |
+
for task, metric, expected, tolerance in expected_results:
|
| 45 |
+
actual = results[task].get(metric, None)
|
| 46 |
+
if actual is None:
|
| 47 |
+
ok = False
|
| 48 |
+
continue
|
| 49 |
+
if not np.isfinite(actual):
|
| 50 |
+
ok = False
|
| 51 |
+
continue
|
| 52 |
+
diff = abs(actual - expected)
|
| 53 |
+
if diff > tolerance:
|
| 54 |
+
ok = False
|
| 55 |
+
|
| 56 |
+
logger = logging.getLogger(__name__)
|
| 57 |
+
if not ok:
|
| 58 |
+
logger.error("Result verification failed!")
|
| 59 |
+
logger.error("Expected Results: " + str(expected_results))
|
| 60 |
+
logger.error("Actual Results: " + pprint.pformat(results))
|
| 61 |
+
|
| 62 |
+
sys.exit(1)
|
| 63 |
+
else:
|
| 64 |
+
logger.info("Results verification passed.")
|
| 65 |
+
return ok
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def flatten_results_dict(results):
|
| 69 |
+
"""
|
| 70 |
+
Expand a hierarchical dict of scalars into a flat dict of scalars.
|
| 71 |
+
If results[k1][k2][k3] = v, the returned dict will have the entry
|
| 72 |
+
{"k1/k2/k3": v}.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
results (dict):
|
| 76 |
+
"""
|
| 77 |
+
r = {}
|
| 78 |
+
for k, v in results.items():
|
| 79 |
+
if isinstance(v, Mapping):
|
| 80 |
+
v = flatten_results_dict(v)
|
| 81 |
+
for kk, vv in v.items():
|
| 82 |
+
r[k + "/" + kk] = vv
|
| 83 |
+
else:
|
| 84 |
+
r[k] = v
|
| 85 |
+
return r
|
RAVE-main/annotator/oneformer/detectron2/model_zoo/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
"""
|
| 3 |
+
Model Zoo API for Detectron2: a collection of functions to create common model architectures
|
| 4 |
+
listed in `MODEL_ZOO.md <https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md>`_,
|
| 5 |
+
and optionally load their pre-trained weights.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from .model_zoo import get, get_config_file, get_checkpoint_url, get_config
|
| 9 |
+
|
| 10 |
+
__all__ = ["get_checkpoint_url", "get", "get_config_file", "get_config"]
|
RAVE-main/annotator/oneformer/detectron2/model_zoo/model_zoo.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 7 |
+
from annotator.oneformer.detectron2.checkpoint import DetectionCheckpointer
|
| 8 |
+
from annotator.oneformer.detectron2.config import CfgNode, LazyConfig, get_cfg, instantiate
|
| 9 |
+
from annotator.oneformer.detectron2.modeling import build_model
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _ModelZooUrls(object):
|
| 13 |
+
"""
|
| 14 |
+
Mapping from names to officially released Detectron2 pre-trained models.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
S3_PREFIX = "https://dl.fbaipublicfiles.com/detectron2/"
|
| 18 |
+
|
| 19 |
+
# format: {config_path.yaml} -> model_id/model_final_{commit}.pkl
|
| 20 |
+
CONFIG_PATH_TO_URL_SUFFIX = {
|
| 21 |
+
# COCO Detection with Faster R-CNN
|
| 22 |
+
"COCO-Detection/faster_rcnn_R_50_C4_1x": "137257644/model_final_721ade.pkl",
|
| 23 |
+
"COCO-Detection/faster_rcnn_R_50_DC5_1x": "137847829/model_final_51d356.pkl",
|
| 24 |
+
"COCO-Detection/faster_rcnn_R_50_FPN_1x": "137257794/model_final_b275ba.pkl",
|
| 25 |
+
"COCO-Detection/faster_rcnn_R_50_C4_3x": "137849393/model_final_f97cb7.pkl",
|
| 26 |
+
"COCO-Detection/faster_rcnn_R_50_DC5_3x": "137849425/model_final_68d202.pkl",
|
| 27 |
+
"COCO-Detection/faster_rcnn_R_50_FPN_3x": "137849458/model_final_280758.pkl",
|
| 28 |
+
"COCO-Detection/faster_rcnn_R_101_C4_3x": "138204752/model_final_298dad.pkl",
|
| 29 |
+
"COCO-Detection/faster_rcnn_R_101_DC5_3x": "138204841/model_final_3e0943.pkl",
|
| 30 |
+
"COCO-Detection/faster_rcnn_R_101_FPN_3x": "137851257/model_final_f6e8b1.pkl",
|
| 31 |
+
"COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x": "139173657/model_final_68b088.pkl",
|
| 32 |
+
# COCO Detection with RetinaNet
|
| 33 |
+
"COCO-Detection/retinanet_R_50_FPN_1x": "190397773/model_final_bfca0b.pkl",
|
| 34 |
+
"COCO-Detection/retinanet_R_50_FPN_3x": "190397829/model_final_5bd44e.pkl",
|
| 35 |
+
"COCO-Detection/retinanet_R_101_FPN_3x": "190397697/model_final_971ab9.pkl",
|
| 36 |
+
# COCO Detection with RPN and Fast R-CNN
|
| 37 |
+
"COCO-Detection/rpn_R_50_C4_1x": "137258005/model_final_450694.pkl",
|
| 38 |
+
"COCO-Detection/rpn_R_50_FPN_1x": "137258492/model_final_02ce48.pkl",
|
| 39 |
+
"COCO-Detection/fast_rcnn_R_50_FPN_1x": "137635226/model_final_e5f7ce.pkl",
|
| 40 |
+
# COCO Instance Segmentation Baselines with Mask R-CNN
|
| 41 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x": "137259246/model_final_9243eb.pkl",
|
| 42 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_1x": "137260150/model_final_4f86c3.pkl",
|
| 43 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x": "137260431/model_final_a54504.pkl",
|
| 44 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_50_C4_3x": "137849525/model_final_4ce675.pkl",
|
| 45 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_3x": "137849551/model_final_84107b.pkl",
|
| 46 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x": "137849600/model_final_f10217.pkl",
|
| 47 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_101_C4_3x": "138363239/model_final_a2914c.pkl",
|
| 48 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_101_DC5_3x": "138363294/model_final_0464b7.pkl",
|
| 49 |
+
"COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x": "138205316/model_final_a3ec72.pkl",
|
| 50 |
+
"COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x": "139653917/model_final_2d9806.pkl", # noqa
|
| 51 |
+
# New baselines using Large-Scale Jitter and Longer Training Schedule
|
| 52 |
+
"new_baselines/mask_rcnn_R_50_FPN_100ep_LSJ": "42047764/model_final_bb69de.pkl",
|
| 53 |
+
"new_baselines/mask_rcnn_R_50_FPN_200ep_LSJ": "42047638/model_final_89a8d3.pkl",
|
| 54 |
+
"new_baselines/mask_rcnn_R_50_FPN_400ep_LSJ": "42019571/model_final_14d201.pkl",
|
| 55 |
+
"new_baselines/mask_rcnn_R_101_FPN_100ep_LSJ": "42025812/model_final_4f7b58.pkl",
|
| 56 |
+
"new_baselines/mask_rcnn_R_101_FPN_200ep_LSJ": "42131867/model_final_0bb7ae.pkl",
|
| 57 |
+
"new_baselines/mask_rcnn_R_101_FPN_400ep_LSJ": "42073830/model_final_f96b26.pkl",
|
| 58 |
+
"new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ": "42047771/model_final_b7fbab.pkl", # noqa
|
| 59 |
+
"new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_200ep_LSJ": "42132721/model_final_5d87c1.pkl", # noqa
|
| 60 |
+
"new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_400ep_LSJ": "42025447/model_final_f1362d.pkl", # noqa
|
| 61 |
+
"new_baselines/mask_rcnn_regnety_4gf_dds_FPN_100ep_LSJ": "42047784/model_final_6ba57e.pkl", # noqa
|
| 62 |
+
"new_baselines/mask_rcnn_regnety_4gf_dds_FPN_200ep_LSJ": "42047642/model_final_27b9c1.pkl", # noqa
|
| 63 |
+
"new_baselines/mask_rcnn_regnety_4gf_dds_FPN_400ep_LSJ": "42045954/model_final_ef3a80.pkl", # noqa
|
| 64 |
+
# COCO Person Keypoint Detection Baselines with Keypoint R-CNN
|
| 65 |
+
"COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x": "137261548/model_final_04e291.pkl",
|
| 66 |
+
"COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x": "137849621/model_final_a6e10b.pkl",
|
| 67 |
+
"COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x": "138363331/model_final_997cc7.pkl",
|
| 68 |
+
"COCO-Keypoints/keypoint_rcnn_X_101_32x8d_FPN_3x": "139686956/model_final_5ad38f.pkl",
|
| 69 |
+
# COCO Panoptic Segmentation Baselines with Panoptic FPN
|
| 70 |
+
"COCO-PanopticSegmentation/panoptic_fpn_R_50_1x": "139514544/model_final_dbfeb4.pkl",
|
| 71 |
+
"COCO-PanopticSegmentation/panoptic_fpn_R_50_3x": "139514569/model_final_c10459.pkl",
|
| 72 |
+
"COCO-PanopticSegmentation/panoptic_fpn_R_101_3x": "139514519/model_final_cafdb1.pkl",
|
| 73 |
+
# LVIS Instance Segmentation Baselines with Mask R-CNN
|
| 74 |
+
"LVISv0.5-InstanceSegmentation/mask_rcnn_R_50_FPN_1x": "144219072/model_final_571f7c.pkl", # noqa
|
| 75 |
+
"LVISv0.5-InstanceSegmentation/mask_rcnn_R_101_FPN_1x": "144219035/model_final_824ab5.pkl", # noqa
|
| 76 |
+
"LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x": "144219108/model_final_5e3439.pkl", # noqa
|
| 77 |
+
# Cityscapes & Pascal VOC Baselines
|
| 78 |
+
"Cityscapes/mask_rcnn_R_50_FPN": "142423278/model_final_af9cf5.pkl",
|
| 79 |
+
"PascalVOC-Detection/faster_rcnn_R_50_C4": "142202221/model_final_b1acc2.pkl",
|
| 80 |
+
# Other Settings
|
| 81 |
+
"Misc/mask_rcnn_R_50_FPN_1x_dconv_c3-c5": "138602867/model_final_65c703.pkl",
|
| 82 |
+
"Misc/mask_rcnn_R_50_FPN_3x_dconv_c3-c5": "144998336/model_final_821d0b.pkl",
|
| 83 |
+
"Misc/cascade_mask_rcnn_R_50_FPN_1x": "138602847/model_final_e9d89b.pkl",
|
| 84 |
+
"Misc/cascade_mask_rcnn_R_50_FPN_3x": "144998488/model_final_480dd8.pkl",
|
| 85 |
+
"Misc/mask_rcnn_R_50_FPN_3x_syncbn": "169527823/model_final_3b3c51.pkl",
|
| 86 |
+
"Misc/mask_rcnn_R_50_FPN_3x_gn": "138602888/model_final_dc5d9e.pkl",
|
| 87 |
+
"Misc/scratch_mask_rcnn_R_50_FPN_3x_gn": "138602908/model_final_01ca85.pkl",
|
| 88 |
+
"Misc/scratch_mask_rcnn_R_50_FPN_9x_gn": "183808979/model_final_da7b4c.pkl",
|
| 89 |
+
"Misc/scratch_mask_rcnn_R_50_FPN_9x_syncbn": "184226666/model_final_5ce33e.pkl",
|
| 90 |
+
"Misc/panoptic_fpn_R_101_dconv_cascade_gn_3x": "139797668/model_final_be35db.pkl",
|
| 91 |
+
"Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv": "18131413/model_0039999_e76410.pkl", # noqa
|
| 92 |
+
# D1 Comparisons
|
| 93 |
+
"Detectron1-Comparisons/faster_rcnn_R_50_FPN_noaug_1x": "137781054/model_final_7ab50c.pkl", # noqa
|
| 94 |
+
"Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x": "137781281/model_final_62ca52.pkl", # noqa
|
| 95 |
+
"Detectron1-Comparisons/keypoint_rcnn_R_50_FPN_1x": "137781195/model_final_cce136.pkl",
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def query(config_path: str) -> Optional[str]:
|
| 100 |
+
"""
|
| 101 |
+
Args:
|
| 102 |
+
config_path: relative config filename
|
| 103 |
+
"""
|
| 104 |
+
name = config_path.replace(".yaml", "").replace(".py", "")
|
| 105 |
+
if name in _ModelZooUrls.CONFIG_PATH_TO_URL_SUFFIX:
|
| 106 |
+
suffix = _ModelZooUrls.CONFIG_PATH_TO_URL_SUFFIX[name]
|
| 107 |
+
return _ModelZooUrls.S3_PREFIX + name + "/" + suffix
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def get_checkpoint_url(config_path):
|
| 112 |
+
"""
|
| 113 |
+
Returns the URL to the model trained using the given config
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
config_path (str): config file name relative to detectron2's "configs/"
|
| 117 |
+
directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml"
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
str: a URL to the model
|
| 121 |
+
"""
|
| 122 |
+
url = _ModelZooUrls.query(config_path)
|
| 123 |
+
if url is None:
|
| 124 |
+
raise RuntimeError("Pretrained model for {} is not available!".format(config_path))
|
| 125 |
+
return url
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_config_file(config_path):
|
| 129 |
+
"""
|
| 130 |
+
Returns path to a builtin config file.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
config_path (str): config file name relative to detectron2's "configs/"
|
| 134 |
+
directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml"
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
str: the real path to the config file.
|
| 138 |
+
"""
|
| 139 |
+
cfg_file = pkg_resources.resource_filename(
|
| 140 |
+
"detectron2.model_zoo", os.path.join("configs", config_path)
|
| 141 |
+
)
|
| 142 |
+
if not os.path.exists(cfg_file):
|
| 143 |
+
raise RuntimeError("{} not available in Model Zoo!".format(config_path))
|
| 144 |
+
return cfg_file
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def get_config(config_path, trained: bool = False):
|
| 148 |
+
"""
|
| 149 |
+
Returns a config object for a model in model zoo.
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
config_path (str): config file name relative to detectron2's "configs/"
|
| 153 |
+
directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml"
|
| 154 |
+
trained (bool): If True, will set ``MODEL.WEIGHTS`` to trained model zoo weights.
|
| 155 |
+
If False, the checkpoint specified in the config file's ``MODEL.WEIGHTS`` is used
|
| 156 |
+
instead; this will typically (though not always) initialize a subset of weights using
|
| 157 |
+
an ImageNet pre-trained model, while randomly initializing the other weights.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
CfgNode or omegaconf.DictConfig: a config object
|
| 161 |
+
"""
|
| 162 |
+
cfg_file = get_config_file(config_path)
|
| 163 |
+
if cfg_file.endswith(".yaml"):
|
| 164 |
+
cfg = get_cfg()
|
| 165 |
+
cfg.merge_from_file(cfg_file)
|
| 166 |
+
if trained:
|
| 167 |
+
cfg.MODEL.WEIGHTS = get_checkpoint_url(config_path)
|
| 168 |
+
return cfg
|
| 169 |
+
elif cfg_file.endswith(".py"):
|
| 170 |
+
cfg = LazyConfig.load(cfg_file)
|
| 171 |
+
if trained:
|
| 172 |
+
url = get_checkpoint_url(config_path)
|
| 173 |
+
if "train" in cfg and "init_checkpoint" in cfg.train:
|
| 174 |
+
cfg.train.init_checkpoint = url
|
| 175 |
+
else:
|
| 176 |
+
raise NotImplementedError
|
| 177 |
+
return cfg
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def get(config_path, trained: bool = False, device: Optional[str] = None):
|
| 181 |
+
"""
|
| 182 |
+
Get a model specified by relative path under Detectron2's official ``configs/`` directory.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
config_path (str): config file name relative to detectron2's "configs/"
|
| 186 |
+
directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml"
|
| 187 |
+
trained (bool): see :func:`get_config`.
|
| 188 |
+
device (str or None): overwrite the device in config, if given.
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
nn.Module: a detectron2 model. Will be in training mode.
|
| 192 |
+
|
| 193 |
+
Example:
|
| 194 |
+
::
|
| 195 |
+
from annotator.oneformer.detectron2 import model_zoo
|
| 196 |
+
model = model_zoo.get("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml", trained=True)
|
| 197 |
+
"""
|
| 198 |
+
cfg = get_config(config_path, trained)
|
| 199 |
+
if device is None and not torch.cuda.is_available():
|
| 200 |
+
device = "cpu"
|
| 201 |
+
if device is not None and isinstance(cfg, CfgNode):
|
| 202 |
+
cfg.MODEL.DEVICE = device
|
| 203 |
+
|
| 204 |
+
if isinstance(cfg, CfgNode):
|
| 205 |
+
model = build_model(cfg)
|
| 206 |
+
DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS)
|
| 207 |
+
else:
|
| 208 |
+
model = instantiate(cfg.model)
|
| 209 |
+
if device is not None:
|
| 210 |
+
model = model.to(device)
|
| 211 |
+
if "train" in cfg and "init_checkpoint" in cfg.train:
|
| 212 |
+
DetectionCheckpointer(model).load(cfg.train.init_checkpoint)
|
| 213 |
+
return model
|
RAVE-main/annotator/oneformer/detectron2/projects/README.md
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Projects live in the [`projects` directory](../../projects) under the root of this repository, but not here.
|
RAVE-main/annotator/oneformer/detectron2/projects/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import importlib.abc
|
| 3 |
+
import importlib.util
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
__all__ = []
|
| 7 |
+
|
| 8 |
+
_PROJECTS = {
|
| 9 |
+
"point_rend": "PointRend",
|
| 10 |
+
"deeplab": "DeepLab",
|
| 11 |
+
"panoptic_deeplab": "Panoptic-DeepLab",
|
| 12 |
+
}
|
| 13 |
+
_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects"
|
| 14 |
+
|
| 15 |
+
if _PROJECT_ROOT.is_dir():
|
| 16 |
+
# This is true only for in-place installation (pip install -e, setup.py develop),
|
| 17 |
+
# where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230
|
| 18 |
+
|
| 19 |
+
class _D2ProjectsFinder(importlib.abc.MetaPathFinder):
|
| 20 |
+
def find_spec(self, name, path, target=None):
|
| 21 |
+
if not name.startswith("detectron2.projects."):
|
| 22 |
+
return
|
| 23 |
+
project_name = name.split(".")[-1]
|
| 24 |
+
project_dir = _PROJECTS.get(project_name)
|
| 25 |
+
if not project_dir:
|
| 26 |
+
return
|
| 27 |
+
target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py"
|
| 28 |
+
if not target_file.is_file():
|
| 29 |
+
return
|
| 30 |
+
return importlib.util.spec_from_file_location(name, target_file)
|
| 31 |
+
|
| 32 |
+
import sys
|
| 33 |
+
|
| 34 |
+
sys.meta_path.append(_D2ProjectsFinder())
|
RAVE-main/annotator/oneformer/detectron2/projects/deeplab/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
from .build_solver import build_lr_scheduler
|
| 3 |
+
from .config import add_deeplab_config
|
| 4 |
+
from .resnet import build_resnet_deeplab_backbone
|
| 5 |
+
from .semantic_seg import DeepLabV3Head, DeepLabV3PlusHead
|
RAVE-main/annotator/oneformer/detectron2/projects/deeplab/build_solver.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from annotator.oneformer.detectron2.config import CfgNode
|
| 5 |
+
from annotator.oneformer.detectron2.solver import LRScheduler
|
| 6 |
+
from annotator.oneformer.detectron2.solver import build_lr_scheduler as build_d2_lr_scheduler
|
| 7 |
+
|
| 8 |
+
from .lr_scheduler import WarmupPolyLR
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def build_lr_scheduler(cfg: CfgNode, optimizer: torch.optim.Optimizer) -> LRScheduler:
|
| 12 |
+
"""
|
| 13 |
+
Build a LR scheduler from config.
|
| 14 |
+
"""
|
| 15 |
+
name = cfg.SOLVER.LR_SCHEDULER_NAME
|
| 16 |
+
if name == "WarmupPolyLR":
|
| 17 |
+
return WarmupPolyLR(
|
| 18 |
+
optimizer,
|
| 19 |
+
cfg.SOLVER.MAX_ITER,
|
| 20 |
+
warmup_factor=cfg.SOLVER.WARMUP_FACTOR,
|
| 21 |
+
warmup_iters=cfg.SOLVER.WARMUP_ITERS,
|
| 22 |
+
warmup_method=cfg.SOLVER.WARMUP_METHOD,
|
| 23 |
+
power=cfg.SOLVER.POLY_LR_POWER,
|
| 24 |
+
constant_ending=cfg.SOLVER.POLY_LR_CONSTANT_ENDING,
|
| 25 |
+
)
|
| 26 |
+
else:
|
| 27 |
+
return build_d2_lr_scheduler(cfg, optimizer)
|
RAVE-main/annotator/oneformer/detectron2/projects/deeplab/config.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def add_deeplab_config(cfg):
|
| 6 |
+
"""
|
| 7 |
+
Add config for DeepLab.
|
| 8 |
+
"""
|
| 9 |
+
# We retry random cropping until no single category in semantic segmentation GT occupies more
|
| 10 |
+
# than `SINGLE_CATEGORY_MAX_AREA` part of the crop.
|
| 11 |
+
cfg.INPUT.CROP.SINGLE_CATEGORY_MAX_AREA = 1.0
|
| 12 |
+
# Used for `poly` learning rate schedule.
|
| 13 |
+
cfg.SOLVER.POLY_LR_POWER = 0.9
|
| 14 |
+
cfg.SOLVER.POLY_LR_CONSTANT_ENDING = 0.0
|
| 15 |
+
# Loss type, choose from `cross_entropy`, `hard_pixel_mining`.
|
| 16 |
+
cfg.MODEL.SEM_SEG_HEAD.LOSS_TYPE = "hard_pixel_mining"
|
| 17 |
+
# DeepLab settings
|
| 18 |
+
cfg.MODEL.SEM_SEG_HEAD.PROJECT_FEATURES = ["res2"]
|
| 19 |
+
cfg.MODEL.SEM_SEG_HEAD.PROJECT_CHANNELS = [48]
|
| 20 |
+
cfg.MODEL.SEM_SEG_HEAD.ASPP_CHANNELS = 256
|
| 21 |
+
cfg.MODEL.SEM_SEG_HEAD.ASPP_DILATIONS = [6, 12, 18]
|
| 22 |
+
cfg.MODEL.SEM_SEG_HEAD.ASPP_DROPOUT = 0.1
|
| 23 |
+
cfg.MODEL.SEM_SEG_HEAD.USE_DEPTHWISE_SEPARABLE_CONV = False
|
| 24 |
+
# Backbone new configs
|
| 25 |
+
cfg.MODEL.RESNETS.RES4_DILATION = 1
|
| 26 |
+
cfg.MODEL.RESNETS.RES5_MULTI_GRID = [1, 2, 4]
|
| 27 |
+
# ResNet stem type from: `basic`, `deeplab`
|
| 28 |
+
cfg.MODEL.RESNETS.STEM_TYPE = "deeplab"
|
RAVE-main/annotator/oneformer/detectron2/projects/deeplab/loss.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DeepLabCE(nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
Hard pixel mining with cross entropy loss, for semantic segmentation.
|
| 9 |
+
This is used in TensorFlow DeepLab frameworks.
|
| 10 |
+
Paper: DeeperLab: Single-Shot Image Parser
|
| 11 |
+
Reference: https://github.com/tensorflow/models/blob/bd488858d610e44df69da6f89277e9de8a03722c/research/deeplab/utils/train_utils.py#L33 # noqa
|
| 12 |
+
Arguments:
|
| 13 |
+
ignore_label: Integer, label to ignore.
|
| 14 |
+
top_k_percent_pixels: Float, the value lies in [0.0, 1.0]. When its
|
| 15 |
+
value < 1.0, only compute the loss for the top k percent pixels
|
| 16 |
+
(e.g., the top 20% pixels). This is useful for hard pixel mining.
|
| 17 |
+
weight: Tensor, a manual rescaling weight given to each class.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, ignore_label=-1, top_k_percent_pixels=1.0, weight=None):
|
| 21 |
+
super(DeepLabCE, self).__init__()
|
| 22 |
+
self.top_k_percent_pixels = top_k_percent_pixels
|
| 23 |
+
self.ignore_label = ignore_label
|
| 24 |
+
self.criterion = nn.CrossEntropyLoss(
|
| 25 |
+
weight=weight, ignore_index=ignore_label, reduction="none"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
def forward(self, logits, labels, weights=None):
|
| 29 |
+
if weights is None:
|
| 30 |
+
pixel_losses = self.criterion(logits, labels).contiguous().view(-1)
|
| 31 |
+
else:
|
| 32 |
+
# Apply per-pixel loss weights.
|
| 33 |
+
pixel_losses = self.criterion(logits, labels) * weights
|
| 34 |
+
pixel_losses = pixel_losses.contiguous().view(-1)
|
| 35 |
+
if self.top_k_percent_pixels == 1.0:
|
| 36 |
+
return pixel_losses.mean()
|
| 37 |
+
|
| 38 |
+
top_k_pixels = int(self.top_k_percent_pixels * pixel_losses.numel())
|
| 39 |
+
pixel_losses, _ = torch.topk(pixel_losses, top_k_pixels)
|
| 40 |
+
return pixel_losses.mean()
|
RAVE-main/annotator/oneformer/detectron2/projects/deeplab/lr_scheduler.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import math
|
| 3 |
+
from typing import List
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from annotator.oneformer.detectron2.solver.lr_scheduler import LRScheduler, _get_warmup_factor_at_iter
|
| 7 |
+
|
| 8 |
+
# NOTE: PyTorch's LR scheduler interface uses names that assume the LR changes
|
| 9 |
+
# only on epoch boundaries. We typically use iteration based schedules instead.
|
| 10 |
+
# As a result, "epoch" (e.g., as in self.last_epoch) should be understood to mean
|
| 11 |
+
# "iteration" instead.
|
| 12 |
+
|
| 13 |
+
# FIXME: ideally this would be achieved with a CombinedLRScheduler, separating
|
| 14 |
+
# MultiStepLR with WarmupLR but the current LRScheduler design doesn't allow it.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class WarmupPolyLR(LRScheduler):
|
| 18 |
+
"""
|
| 19 |
+
Poly learning rate schedule used to train DeepLab.
|
| 20 |
+
Paper: DeepLab: Semantic Image Segmentation with Deep Convolutional Nets,
|
| 21 |
+
Atrous Convolution, and Fully Connected CRFs.
|
| 22 |
+
Reference: https://github.com/tensorflow/models/blob/21b73d22f3ed05b650e85ac50849408dd36de32e/research/deeplab/utils/train_utils.py#L337 # noqa
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
optimizer: torch.optim.Optimizer,
|
| 28 |
+
max_iters: int,
|
| 29 |
+
warmup_factor: float = 0.001,
|
| 30 |
+
warmup_iters: int = 1000,
|
| 31 |
+
warmup_method: str = "linear",
|
| 32 |
+
last_epoch: int = -1,
|
| 33 |
+
power: float = 0.9,
|
| 34 |
+
constant_ending: float = 0.0,
|
| 35 |
+
):
|
| 36 |
+
self.max_iters = max_iters
|
| 37 |
+
self.warmup_factor = warmup_factor
|
| 38 |
+
self.warmup_iters = warmup_iters
|
| 39 |
+
self.warmup_method = warmup_method
|
| 40 |
+
self.power = power
|
| 41 |
+
self.constant_ending = constant_ending
|
| 42 |
+
super().__init__(optimizer, last_epoch)
|
| 43 |
+
|
| 44 |
+
def get_lr(self) -> List[float]:
|
| 45 |
+
warmup_factor = _get_warmup_factor_at_iter(
|
| 46 |
+
self.warmup_method, self.last_epoch, self.warmup_iters, self.warmup_factor
|
| 47 |
+
)
|
| 48 |
+
if self.constant_ending > 0 and warmup_factor == 1.0:
|
| 49 |
+
# Constant ending lr.
|
| 50 |
+
if (
|
| 51 |
+
math.pow((1.0 - self.last_epoch / self.max_iters), self.power)
|
| 52 |
+
< self.constant_ending
|
| 53 |
+
):
|
| 54 |
+
return [base_lr * self.constant_ending for base_lr in self.base_lrs]
|
| 55 |
+
return [
|
| 56 |
+
base_lr * warmup_factor * math.pow((1.0 - self.last_epoch / self.max_iters), self.power)
|
| 57 |
+
for base_lr in self.base_lrs
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
def _compute_values(self) -> List[float]:
|
| 61 |
+
# The new interface
|
| 62 |
+
return self.get_lr()
|
RAVE-main/annotator/oneformer/detectron2/projects/deeplab/resnet.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import fvcore.nn.weight_init as weight_init
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
from annotator.oneformer.detectron2.layers import CNNBlockBase, Conv2d, get_norm
|
| 6 |
+
from annotator.oneformer.detectron2.modeling import BACKBONE_REGISTRY
|
| 7 |
+
from annotator.oneformer.detectron2.modeling.backbone.resnet import (
|
| 8 |
+
BasicStem,
|
| 9 |
+
BottleneckBlock,
|
| 10 |
+
DeformBottleneckBlock,
|
| 11 |
+
ResNet,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class DeepLabStem(CNNBlockBase):
|
| 16 |
+
"""
|
| 17 |
+
The DeepLab ResNet stem (layers before the first residual block).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, in_channels=3, out_channels=128, norm="BN"):
|
| 21 |
+
"""
|
| 22 |
+
Args:
|
| 23 |
+
norm (str or callable): norm after the first conv layer.
|
| 24 |
+
See :func:`layers.get_norm` for supported format.
|
| 25 |
+
"""
|
| 26 |
+
super().__init__(in_channels, out_channels, 4)
|
| 27 |
+
self.in_channels = in_channels
|
| 28 |
+
self.conv1 = Conv2d(
|
| 29 |
+
in_channels,
|
| 30 |
+
out_channels // 2,
|
| 31 |
+
kernel_size=3,
|
| 32 |
+
stride=2,
|
| 33 |
+
padding=1,
|
| 34 |
+
bias=False,
|
| 35 |
+
norm=get_norm(norm, out_channels // 2),
|
| 36 |
+
)
|
| 37 |
+
self.conv2 = Conv2d(
|
| 38 |
+
out_channels // 2,
|
| 39 |
+
out_channels // 2,
|
| 40 |
+
kernel_size=3,
|
| 41 |
+
stride=1,
|
| 42 |
+
padding=1,
|
| 43 |
+
bias=False,
|
| 44 |
+
norm=get_norm(norm, out_channels // 2),
|
| 45 |
+
)
|
| 46 |
+
self.conv3 = Conv2d(
|
| 47 |
+
out_channels // 2,
|
| 48 |
+
out_channels,
|
| 49 |
+
kernel_size=3,
|
| 50 |
+
stride=1,
|
| 51 |
+
padding=1,
|
| 52 |
+
bias=False,
|
| 53 |
+
norm=get_norm(norm, out_channels),
|
| 54 |
+
)
|
| 55 |
+
weight_init.c2_msra_fill(self.conv1)
|
| 56 |
+
weight_init.c2_msra_fill(self.conv2)
|
| 57 |
+
weight_init.c2_msra_fill(self.conv3)
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
x = self.conv1(x)
|
| 61 |
+
x = F.relu_(x)
|
| 62 |
+
x = self.conv2(x)
|
| 63 |
+
x = F.relu_(x)
|
| 64 |
+
x = self.conv3(x)
|
| 65 |
+
x = F.relu_(x)
|
| 66 |
+
x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
|
| 67 |
+
return x
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@BACKBONE_REGISTRY.register()
|
| 71 |
+
def build_resnet_deeplab_backbone(cfg, input_shape):
|
| 72 |
+
"""
|
| 73 |
+
Create a ResNet instance from config.
|
| 74 |
+
Returns:
|
| 75 |
+
ResNet: a :class:`ResNet` instance.
|
| 76 |
+
"""
|
| 77 |
+
# need registration of new blocks/stems?
|
| 78 |
+
norm = cfg.MODEL.RESNETS.NORM
|
| 79 |
+
if cfg.MODEL.RESNETS.STEM_TYPE == "basic":
|
| 80 |
+
stem = BasicStem(
|
| 81 |
+
in_channels=input_shape.channels,
|
| 82 |
+
out_channels=cfg.MODEL.RESNETS.STEM_OUT_CHANNELS,
|
| 83 |
+
norm=norm,
|
| 84 |
+
)
|
| 85 |
+
elif cfg.MODEL.RESNETS.STEM_TYPE == "deeplab":
|
| 86 |
+
stem = DeepLabStem(
|
| 87 |
+
in_channels=input_shape.channels,
|
| 88 |
+
out_channels=cfg.MODEL.RESNETS.STEM_OUT_CHANNELS,
|
| 89 |
+
norm=norm,
|
| 90 |
+
)
|
| 91 |
+
else:
|
| 92 |
+
raise ValueError("Unknown stem type: {}".format(cfg.MODEL.RESNETS.STEM_TYPE))
|
| 93 |
+
|
| 94 |
+
# fmt: off
|
| 95 |
+
freeze_at = cfg.MODEL.BACKBONE.FREEZE_AT
|
| 96 |
+
out_features = cfg.MODEL.RESNETS.OUT_FEATURES
|
| 97 |
+
depth = cfg.MODEL.RESNETS.DEPTH
|
| 98 |
+
num_groups = cfg.MODEL.RESNETS.NUM_GROUPS
|
| 99 |
+
width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP
|
| 100 |
+
bottleneck_channels = num_groups * width_per_group
|
| 101 |
+
in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS
|
| 102 |
+
out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS
|
| 103 |
+
stride_in_1x1 = cfg.MODEL.RESNETS.STRIDE_IN_1X1
|
| 104 |
+
res4_dilation = cfg.MODEL.RESNETS.RES4_DILATION
|
| 105 |
+
res5_dilation = cfg.MODEL.RESNETS.RES5_DILATION
|
| 106 |
+
deform_on_per_stage = cfg.MODEL.RESNETS.DEFORM_ON_PER_STAGE
|
| 107 |
+
deform_modulated = cfg.MODEL.RESNETS.DEFORM_MODULATED
|
| 108 |
+
deform_num_groups = cfg.MODEL.RESNETS.DEFORM_NUM_GROUPS
|
| 109 |
+
res5_multi_grid = cfg.MODEL.RESNETS.RES5_MULTI_GRID
|
| 110 |
+
# fmt: on
|
| 111 |
+
assert res4_dilation in {1, 2}, "res4_dilation cannot be {}.".format(res4_dilation)
|
| 112 |
+
assert res5_dilation in {1, 2, 4}, "res5_dilation cannot be {}.".format(res5_dilation)
|
| 113 |
+
if res4_dilation == 2:
|
| 114 |
+
# Always dilate res5 if res4 is dilated.
|
| 115 |
+
assert res5_dilation == 4
|
| 116 |
+
|
| 117 |
+
num_blocks_per_stage = {50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3]}[depth]
|
| 118 |
+
|
| 119 |
+
stages = []
|
| 120 |
+
|
| 121 |
+
# Avoid creating variables without gradients
|
| 122 |
+
# It consumes extra memory and may cause allreduce to fail
|
| 123 |
+
out_stage_idx = [{"res2": 2, "res3": 3, "res4": 4, "res5": 5}[f] for f in out_features]
|
| 124 |
+
max_stage_idx = max(out_stage_idx)
|
| 125 |
+
for idx, stage_idx in enumerate(range(2, max_stage_idx + 1)):
|
| 126 |
+
if stage_idx == 4:
|
| 127 |
+
dilation = res4_dilation
|
| 128 |
+
elif stage_idx == 5:
|
| 129 |
+
dilation = res5_dilation
|
| 130 |
+
else:
|
| 131 |
+
dilation = 1
|
| 132 |
+
first_stride = 1 if idx == 0 or dilation > 1 else 2
|
| 133 |
+
stage_kargs = {
|
| 134 |
+
"num_blocks": num_blocks_per_stage[idx],
|
| 135 |
+
"stride_per_block": [first_stride] + [1] * (num_blocks_per_stage[idx] - 1),
|
| 136 |
+
"in_channels": in_channels,
|
| 137 |
+
"out_channels": out_channels,
|
| 138 |
+
"norm": norm,
|
| 139 |
+
}
|
| 140 |
+
stage_kargs["bottleneck_channels"] = bottleneck_channels
|
| 141 |
+
stage_kargs["stride_in_1x1"] = stride_in_1x1
|
| 142 |
+
stage_kargs["dilation"] = dilation
|
| 143 |
+
stage_kargs["num_groups"] = num_groups
|
| 144 |
+
if deform_on_per_stage[idx]:
|
| 145 |
+
stage_kargs["block_class"] = DeformBottleneckBlock
|
| 146 |
+
stage_kargs["deform_modulated"] = deform_modulated
|
| 147 |
+
stage_kargs["deform_num_groups"] = deform_num_groups
|
| 148 |
+
else:
|
| 149 |
+
stage_kargs["block_class"] = BottleneckBlock
|
| 150 |
+
if stage_idx == 5:
|
| 151 |
+
stage_kargs.pop("dilation")
|
| 152 |
+
stage_kargs["dilation_per_block"] = [dilation * mg for mg in res5_multi_grid]
|
| 153 |
+
blocks = ResNet.make_stage(**stage_kargs)
|
| 154 |
+
in_channels = out_channels
|
| 155 |
+
out_channels *= 2
|
| 156 |
+
bottleneck_channels *= 2
|
| 157 |
+
stages.append(blocks)
|
| 158 |
+
return ResNet(stem, stages, out_features=out_features).freeze(freeze_at)
|
RAVE-main/annotator/oneformer/detectron2/projects/deeplab/semantic_seg.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
from typing import Callable, Dict, List, Optional, Tuple, Union
|
| 3 |
+
import fvcore.nn.weight_init as weight_init
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
|
| 8 |
+
from annotator.oneformer.detectron2.config import configurable
|
| 9 |
+
from annotator.oneformer.detectron2.layers import ASPP, Conv2d, DepthwiseSeparableConv2d, ShapeSpec, get_norm
|
| 10 |
+
from annotator.oneformer.detectron2.modeling import SEM_SEG_HEADS_REGISTRY
|
| 11 |
+
|
| 12 |
+
from .loss import DeepLabCE
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@SEM_SEG_HEADS_REGISTRY.register()
|
| 16 |
+
class DeepLabV3PlusHead(nn.Module):
|
| 17 |
+
"""
|
| 18 |
+
A semantic segmentation head described in :paper:`DeepLabV3+`.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
@configurable
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
input_shape: Dict[str, ShapeSpec],
|
| 25 |
+
*,
|
| 26 |
+
project_channels: List[int],
|
| 27 |
+
aspp_dilations: List[int],
|
| 28 |
+
aspp_dropout: float,
|
| 29 |
+
decoder_channels: List[int],
|
| 30 |
+
common_stride: int,
|
| 31 |
+
norm: Union[str, Callable],
|
| 32 |
+
train_size: Optional[Tuple],
|
| 33 |
+
loss_weight: float = 1.0,
|
| 34 |
+
loss_type: str = "cross_entropy",
|
| 35 |
+
ignore_value: int = -1,
|
| 36 |
+
num_classes: Optional[int] = None,
|
| 37 |
+
use_depthwise_separable_conv: bool = False,
|
| 38 |
+
):
|
| 39 |
+
"""
|
| 40 |
+
NOTE: this interface is experimental.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
input_shape: shape of the input features. They will be ordered by stride
|
| 44 |
+
and the last one (with largest stride) is used as the input to the
|
| 45 |
+
decoder (i.e. the ASPP module); the rest are low-level feature for
|
| 46 |
+
the intermediate levels of decoder.
|
| 47 |
+
project_channels (list[int]): a list of low-level feature channels.
|
| 48 |
+
The length should be len(in_features) - 1.
|
| 49 |
+
aspp_dilations (list(int)): a list of 3 dilations in ASPP.
|
| 50 |
+
aspp_dropout (float): apply dropout on the output of ASPP.
|
| 51 |
+
decoder_channels (list[int]): a list of output channels of each
|
| 52 |
+
decoder stage. It should have the same length as "in_features"
|
| 53 |
+
(each element in "in_features" corresponds to one decoder stage).
|
| 54 |
+
common_stride (int): output stride of decoder.
|
| 55 |
+
norm (str or callable): normalization for all conv layers.
|
| 56 |
+
train_size (tuple): (height, width) of training images.
|
| 57 |
+
loss_weight (float): loss weight.
|
| 58 |
+
loss_type (str): type of loss function, 2 opptions:
|
| 59 |
+
(1) "cross_entropy" is the standard cross entropy loss.
|
| 60 |
+
(2) "hard_pixel_mining" is the loss in DeepLab that samples
|
| 61 |
+
top k% hardest pixels.
|
| 62 |
+
ignore_value (int): category to be ignored during training.
|
| 63 |
+
num_classes (int): number of classes, if set to None, the decoder
|
| 64 |
+
will not construct a predictor.
|
| 65 |
+
use_depthwise_separable_conv (bool): use DepthwiseSeparableConv2d
|
| 66 |
+
in ASPP and decoder.
|
| 67 |
+
"""
|
| 68 |
+
super().__init__()
|
| 69 |
+
input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
|
| 70 |
+
|
| 71 |
+
# fmt: off
|
| 72 |
+
self.in_features = [k for k, v in input_shape] # starting from "res2" to "res5"
|
| 73 |
+
in_channels = [x[1].channels for x in input_shape]
|
| 74 |
+
in_strides = [x[1].stride for x in input_shape]
|
| 75 |
+
aspp_channels = decoder_channels[-1]
|
| 76 |
+
self.ignore_value = ignore_value
|
| 77 |
+
self.common_stride = common_stride # output stride
|
| 78 |
+
self.loss_weight = loss_weight
|
| 79 |
+
self.loss_type = loss_type
|
| 80 |
+
self.decoder_only = num_classes is None
|
| 81 |
+
self.use_depthwise_separable_conv = use_depthwise_separable_conv
|
| 82 |
+
# fmt: on
|
| 83 |
+
|
| 84 |
+
assert (
|
| 85 |
+
len(project_channels) == len(self.in_features) - 1
|
| 86 |
+
), "Expected {} project_channels, got {}".format(
|
| 87 |
+
len(self.in_features) - 1, len(project_channels)
|
| 88 |
+
)
|
| 89 |
+
assert len(decoder_channels) == len(
|
| 90 |
+
self.in_features
|
| 91 |
+
), "Expected {} decoder_channels, got {}".format(
|
| 92 |
+
len(self.in_features), len(decoder_channels)
|
| 93 |
+
)
|
| 94 |
+
self.decoder = nn.ModuleDict()
|
| 95 |
+
|
| 96 |
+
use_bias = norm == ""
|
| 97 |
+
for idx, in_channel in enumerate(in_channels):
|
| 98 |
+
decoder_stage = nn.ModuleDict()
|
| 99 |
+
|
| 100 |
+
if idx == len(self.in_features) - 1:
|
| 101 |
+
# ASPP module
|
| 102 |
+
if train_size is not None:
|
| 103 |
+
train_h, train_w = train_size
|
| 104 |
+
encoder_stride = in_strides[-1]
|
| 105 |
+
if train_h % encoder_stride or train_w % encoder_stride:
|
| 106 |
+
raise ValueError("Crop size need to be divisible by encoder stride.")
|
| 107 |
+
pool_h = train_h // encoder_stride
|
| 108 |
+
pool_w = train_w // encoder_stride
|
| 109 |
+
pool_kernel_size = (pool_h, pool_w)
|
| 110 |
+
else:
|
| 111 |
+
pool_kernel_size = None
|
| 112 |
+
project_conv = ASPP(
|
| 113 |
+
in_channel,
|
| 114 |
+
aspp_channels,
|
| 115 |
+
aspp_dilations,
|
| 116 |
+
norm=norm,
|
| 117 |
+
activation=F.relu,
|
| 118 |
+
pool_kernel_size=pool_kernel_size,
|
| 119 |
+
dropout=aspp_dropout,
|
| 120 |
+
use_depthwise_separable_conv=use_depthwise_separable_conv,
|
| 121 |
+
)
|
| 122 |
+
fuse_conv = None
|
| 123 |
+
else:
|
| 124 |
+
project_conv = Conv2d(
|
| 125 |
+
in_channel,
|
| 126 |
+
project_channels[idx],
|
| 127 |
+
kernel_size=1,
|
| 128 |
+
bias=use_bias,
|
| 129 |
+
norm=get_norm(norm, project_channels[idx]),
|
| 130 |
+
activation=F.relu,
|
| 131 |
+
)
|
| 132 |
+
weight_init.c2_xavier_fill(project_conv)
|
| 133 |
+
if use_depthwise_separable_conv:
|
| 134 |
+
# We use a single 5x5 DepthwiseSeparableConv2d to replace
|
| 135 |
+
# 2 3x3 Conv2d since they have the same receptive field,
|
| 136 |
+
# proposed in :paper:`Panoptic-DeepLab`.
|
| 137 |
+
fuse_conv = DepthwiseSeparableConv2d(
|
| 138 |
+
project_channels[idx] + decoder_channels[idx + 1],
|
| 139 |
+
decoder_channels[idx],
|
| 140 |
+
kernel_size=5,
|
| 141 |
+
padding=2,
|
| 142 |
+
norm1=norm,
|
| 143 |
+
activation1=F.relu,
|
| 144 |
+
norm2=norm,
|
| 145 |
+
activation2=F.relu,
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
fuse_conv = nn.Sequential(
|
| 149 |
+
Conv2d(
|
| 150 |
+
project_channels[idx] + decoder_channels[idx + 1],
|
| 151 |
+
decoder_channels[idx],
|
| 152 |
+
kernel_size=3,
|
| 153 |
+
padding=1,
|
| 154 |
+
bias=use_bias,
|
| 155 |
+
norm=get_norm(norm, decoder_channels[idx]),
|
| 156 |
+
activation=F.relu,
|
| 157 |
+
),
|
| 158 |
+
Conv2d(
|
| 159 |
+
decoder_channels[idx],
|
| 160 |
+
decoder_channels[idx],
|
| 161 |
+
kernel_size=3,
|
| 162 |
+
padding=1,
|
| 163 |
+
bias=use_bias,
|
| 164 |
+
norm=get_norm(norm, decoder_channels[idx]),
|
| 165 |
+
activation=F.relu,
|
| 166 |
+
),
|
| 167 |
+
)
|
| 168 |
+
weight_init.c2_xavier_fill(fuse_conv[0])
|
| 169 |
+
weight_init.c2_xavier_fill(fuse_conv[1])
|
| 170 |
+
|
| 171 |
+
decoder_stage["project_conv"] = project_conv
|
| 172 |
+
decoder_stage["fuse_conv"] = fuse_conv
|
| 173 |
+
|
| 174 |
+
self.decoder[self.in_features[idx]] = decoder_stage
|
| 175 |
+
|
| 176 |
+
if not self.decoder_only:
|
| 177 |
+
self.predictor = Conv2d(
|
| 178 |
+
decoder_channels[0], num_classes, kernel_size=1, stride=1, padding=0
|
| 179 |
+
)
|
| 180 |
+
nn.init.normal_(self.predictor.weight, 0, 0.001)
|
| 181 |
+
nn.init.constant_(self.predictor.bias, 0)
|
| 182 |
+
|
| 183 |
+
if self.loss_type == "cross_entropy":
|
| 184 |
+
self.loss = nn.CrossEntropyLoss(reduction="mean", ignore_index=self.ignore_value)
|
| 185 |
+
elif self.loss_type == "hard_pixel_mining":
|
| 186 |
+
self.loss = DeepLabCE(ignore_label=self.ignore_value, top_k_percent_pixels=0.2)
|
| 187 |
+
else:
|
| 188 |
+
raise ValueError("Unexpected loss type: %s" % self.loss_type)
|
| 189 |
+
|
| 190 |
+
@classmethod
|
| 191 |
+
def from_config(cls, cfg, input_shape):
|
| 192 |
+
if cfg.INPUT.CROP.ENABLED:
|
| 193 |
+
assert cfg.INPUT.CROP.TYPE == "absolute"
|
| 194 |
+
train_size = cfg.INPUT.CROP.SIZE
|
| 195 |
+
else:
|
| 196 |
+
train_size = None
|
| 197 |
+
decoder_channels = [cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM] * (
|
| 198 |
+
len(cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES) - 1
|
| 199 |
+
) + [cfg.MODEL.SEM_SEG_HEAD.ASPP_CHANNELS]
|
| 200 |
+
ret = dict(
|
| 201 |
+
input_shape={
|
| 202 |
+
k: v for k, v in input_shape.items() if k in cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
|
| 203 |
+
},
|
| 204 |
+
project_channels=cfg.MODEL.SEM_SEG_HEAD.PROJECT_CHANNELS,
|
| 205 |
+
aspp_dilations=cfg.MODEL.SEM_SEG_HEAD.ASPP_DILATIONS,
|
| 206 |
+
aspp_dropout=cfg.MODEL.SEM_SEG_HEAD.ASPP_DROPOUT,
|
| 207 |
+
decoder_channels=decoder_channels,
|
| 208 |
+
common_stride=cfg.MODEL.SEM_SEG_HEAD.COMMON_STRIDE,
|
| 209 |
+
norm=cfg.MODEL.SEM_SEG_HEAD.NORM,
|
| 210 |
+
train_size=train_size,
|
| 211 |
+
loss_weight=cfg.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT,
|
| 212 |
+
loss_type=cfg.MODEL.SEM_SEG_HEAD.LOSS_TYPE,
|
| 213 |
+
ignore_value=cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,
|
| 214 |
+
num_classes=cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES,
|
| 215 |
+
use_depthwise_separable_conv=cfg.MODEL.SEM_SEG_HEAD.USE_DEPTHWISE_SEPARABLE_CONV,
|
| 216 |
+
)
|
| 217 |
+
return ret
|
| 218 |
+
|
| 219 |
+
def forward(self, features, targets=None):
|
| 220 |
+
"""
|
| 221 |
+
Returns:
|
| 222 |
+
In training, returns (None, dict of losses)
|
| 223 |
+
In inference, returns (CxHxW logits, {})
|
| 224 |
+
"""
|
| 225 |
+
y = self.layers(features)
|
| 226 |
+
if self.decoder_only:
|
| 227 |
+
# Output from self.layers() only contains decoder feature.
|
| 228 |
+
return y
|
| 229 |
+
if self.training:
|
| 230 |
+
return None, self.losses(y, targets)
|
| 231 |
+
else:
|
| 232 |
+
y = F.interpolate(
|
| 233 |
+
y, scale_factor=self.common_stride, mode="bilinear", align_corners=False
|
| 234 |
+
)
|
| 235 |
+
return y, {}
|
| 236 |
+
|
| 237 |
+
def layers(self, features):
|
| 238 |
+
# Reverse feature maps into top-down order (from low to high resolution)
|
| 239 |
+
for f in self.in_features[::-1]:
|
| 240 |
+
x = features[f]
|
| 241 |
+
proj_x = self.decoder[f]["project_conv"](x)
|
| 242 |
+
if self.decoder[f]["fuse_conv"] is None:
|
| 243 |
+
# This is aspp module
|
| 244 |
+
y = proj_x
|
| 245 |
+
else:
|
| 246 |
+
# Upsample y
|
| 247 |
+
y = F.interpolate(y, size=proj_x.size()[2:], mode="bilinear", align_corners=False)
|
| 248 |
+
y = torch.cat([proj_x, y], dim=1)
|
| 249 |
+
y = self.decoder[f]["fuse_conv"](y)
|
| 250 |
+
if not self.decoder_only:
|
| 251 |
+
y = self.predictor(y)
|
| 252 |
+
return y
|
| 253 |
+
|
| 254 |
+
def losses(self, predictions, targets):
|
| 255 |
+
predictions = F.interpolate(
|
| 256 |
+
predictions, scale_factor=self.common_stride, mode="bilinear", align_corners=False
|
| 257 |
+
)
|
| 258 |
+
loss = self.loss(predictions, targets)
|
| 259 |
+
losses = {"loss_sem_seg": loss * self.loss_weight}
|
| 260 |
+
return losses
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@SEM_SEG_HEADS_REGISTRY.register()
|
| 264 |
+
class DeepLabV3Head(nn.Module):
|
| 265 |
+
"""
|
| 266 |
+
A semantic segmentation head described in :paper:`DeepLabV3`.
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
def __init__(self, cfg, input_shape: Dict[str, ShapeSpec]):
|
| 270 |
+
super().__init__()
|
| 271 |
+
|
| 272 |
+
# fmt: off
|
| 273 |
+
self.in_features = cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
|
| 274 |
+
in_channels = [input_shape[f].channels for f in self.in_features]
|
| 275 |
+
aspp_channels = cfg.MODEL.SEM_SEG_HEAD.ASPP_CHANNELS
|
| 276 |
+
aspp_dilations = cfg.MODEL.SEM_SEG_HEAD.ASPP_DILATIONS
|
| 277 |
+
self.ignore_value = cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE
|
| 278 |
+
num_classes = cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES
|
| 279 |
+
conv_dims = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM
|
| 280 |
+
self.common_stride = cfg.MODEL.SEM_SEG_HEAD.COMMON_STRIDE # output stride
|
| 281 |
+
norm = cfg.MODEL.SEM_SEG_HEAD.NORM
|
| 282 |
+
self.loss_weight = cfg.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT
|
| 283 |
+
self.loss_type = cfg.MODEL.SEM_SEG_HEAD.LOSS_TYPE
|
| 284 |
+
train_crop_size = cfg.INPUT.CROP.SIZE
|
| 285 |
+
aspp_dropout = cfg.MODEL.SEM_SEG_HEAD.ASPP_DROPOUT
|
| 286 |
+
use_depthwise_separable_conv = cfg.MODEL.SEM_SEG_HEAD.USE_DEPTHWISE_SEPARABLE_CONV
|
| 287 |
+
# fmt: on
|
| 288 |
+
|
| 289 |
+
assert len(self.in_features) == 1
|
| 290 |
+
assert len(in_channels) == 1
|
| 291 |
+
|
| 292 |
+
# ASPP module
|
| 293 |
+
if cfg.INPUT.CROP.ENABLED:
|
| 294 |
+
assert cfg.INPUT.CROP.TYPE == "absolute"
|
| 295 |
+
train_crop_h, train_crop_w = train_crop_size
|
| 296 |
+
if train_crop_h % self.common_stride or train_crop_w % self.common_stride:
|
| 297 |
+
raise ValueError("Crop size need to be divisible by output stride.")
|
| 298 |
+
pool_h = train_crop_h // self.common_stride
|
| 299 |
+
pool_w = train_crop_w // self.common_stride
|
| 300 |
+
pool_kernel_size = (pool_h, pool_w)
|
| 301 |
+
else:
|
| 302 |
+
pool_kernel_size = None
|
| 303 |
+
self.aspp = ASPP(
|
| 304 |
+
in_channels[0],
|
| 305 |
+
aspp_channels,
|
| 306 |
+
aspp_dilations,
|
| 307 |
+
norm=norm,
|
| 308 |
+
activation=F.relu,
|
| 309 |
+
pool_kernel_size=pool_kernel_size,
|
| 310 |
+
dropout=aspp_dropout,
|
| 311 |
+
use_depthwise_separable_conv=use_depthwise_separable_conv,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
self.predictor = Conv2d(conv_dims, num_classes, kernel_size=1, stride=1, padding=0)
|
| 315 |
+
nn.init.normal_(self.predictor.weight, 0, 0.001)
|
| 316 |
+
nn.init.constant_(self.predictor.bias, 0)
|
| 317 |
+
|
| 318 |
+
if self.loss_type == "cross_entropy":
|
| 319 |
+
self.loss = nn.CrossEntropyLoss(reduction="mean", ignore_index=self.ignore_value)
|
| 320 |
+
elif self.loss_type == "hard_pixel_mining":
|
| 321 |
+
self.loss = DeepLabCE(ignore_label=self.ignore_value, top_k_percent_pixels=0.2)
|
| 322 |
+
else:
|
| 323 |
+
raise ValueError("Unexpected loss type: %s" % self.loss_type)
|
| 324 |
+
|
| 325 |
+
def forward(self, features, targets=None):
|
| 326 |
+
"""
|
| 327 |
+
Returns:
|
| 328 |
+
In training, returns (None, dict of losses)
|
| 329 |
+
In inference, returns (CxHxW logits, {})
|
| 330 |
+
"""
|
| 331 |
+
x = features[self.in_features[0]]
|
| 332 |
+
x = self.aspp(x)
|
| 333 |
+
x = self.predictor(x)
|
| 334 |
+
if self.training:
|
| 335 |
+
return None, self.losses(x, targets)
|
| 336 |
+
else:
|
| 337 |
+
x = F.interpolate(
|
| 338 |
+
x, scale_factor=self.common_stride, mode="bilinear", align_corners=False
|
| 339 |
+
)
|
| 340 |
+
return x, {}
|
| 341 |
+
|
| 342 |
+
def losses(self, predictions, targets):
|
| 343 |
+
predictions = F.interpolate(
|
| 344 |
+
predictions, scale_factor=self.common_stride, mode="bilinear", align_corners=False
|
| 345 |
+
)
|
| 346 |
+
loss = self.loss(predictions, targets)
|
| 347 |
+
losses = {"loss_sem_seg": loss * self.loss_weight}
|
| 348 |
+
return losses
|
RAVE-main/annotator/oneformer/detectron2/tracking/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
from .base_tracker import ( # noqa
|
| 3 |
+
BaseTracker,
|
| 4 |
+
build_tracker_head,
|
| 5 |
+
TRACKER_HEADS_REGISTRY,
|
| 6 |
+
)
|
| 7 |
+
from .bbox_iou_tracker import BBoxIOUTracker # noqa
|
| 8 |
+
from .hungarian_tracker import BaseHungarianTracker # noqa
|
| 9 |
+
from .iou_weighted_hungarian_bbox_iou_tracker import ( # noqa
|
| 10 |
+
IOUWeightedHungarianBBoxIOUTracker,
|
| 11 |
+
)
|
| 12 |
+
from .utils import create_prediction_pairs # noqa
|
| 13 |
+
from .vanilla_hungarian_bbox_iou_tracker import VanillaHungarianBBoxIOUTracker # noqa
|
| 14 |
+
|
| 15 |
+
__all__ = [k for k in globals().keys() if not k.startswith("_")]
|
RAVE-main/annotator/oneformer/detectron2/tracking/base_tracker.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright 2004-present Facebook. All Rights Reserved.
|
| 3 |
+
from annotator.oneformer.detectron2.config import configurable
|
| 4 |
+
from annotator.oneformer.detectron2.utils.registry import Registry
|
| 5 |
+
|
| 6 |
+
from ..config.config import CfgNode as CfgNode_
|
| 7 |
+
from ..structures import Instances
|
| 8 |
+
|
| 9 |
+
TRACKER_HEADS_REGISTRY = Registry("TRACKER_HEADS")
|
| 10 |
+
TRACKER_HEADS_REGISTRY.__doc__ = """
|
| 11 |
+
Registry for tracking classes.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class BaseTracker(object):
|
| 16 |
+
"""
|
| 17 |
+
A parent class for all trackers
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
@configurable
|
| 21 |
+
def __init__(self, **kwargs):
|
| 22 |
+
self._prev_instances = None # (D2)instances for previous frame
|
| 23 |
+
self._matched_idx = set() # indices in prev_instances found matching
|
| 24 |
+
self._matched_ID = set() # idendities in prev_instances found matching
|
| 25 |
+
self._untracked_prev_idx = set() # indices in prev_instances not found matching
|
| 26 |
+
self._id_count = 0 # used to assign new id
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def from_config(cls, cfg: CfgNode_):
|
| 30 |
+
raise NotImplementedError("Calling BaseTracker::from_config")
|
| 31 |
+
|
| 32 |
+
def update(self, predictions: Instances) -> Instances:
|
| 33 |
+
"""
|
| 34 |
+
Args:
|
| 35 |
+
predictions: D2 Instances for predictions of the current frame
|
| 36 |
+
Return:
|
| 37 |
+
D2 Instances for predictions of the current frame with ID assigned
|
| 38 |
+
|
| 39 |
+
_prev_instances and instances will have the following fields:
|
| 40 |
+
.pred_boxes (shape=[N, 4])
|
| 41 |
+
.scores (shape=[N,])
|
| 42 |
+
.pred_classes (shape=[N,])
|
| 43 |
+
.pred_keypoints (shape=[N, M, 3], Optional)
|
| 44 |
+
.pred_masks (shape=List[2D_MASK], Optional) 2D_MASK: shape=[H, W]
|
| 45 |
+
.ID (shape=[N,])
|
| 46 |
+
|
| 47 |
+
N: # of detected bboxes
|
| 48 |
+
H and W: height and width of 2D mask
|
| 49 |
+
"""
|
| 50 |
+
raise NotImplementedError("Calling BaseTracker::update")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_tracker_head(cfg: CfgNode_) -> BaseTracker:
|
| 54 |
+
"""
|
| 55 |
+
Build a tracker head from `cfg.TRACKER_HEADS.TRACKER_NAME`.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
cfg: D2 CfgNode, config file with tracker information
|
| 59 |
+
Return:
|
| 60 |
+
tracker object
|
| 61 |
+
"""
|
| 62 |
+
name = cfg.TRACKER_HEADS.TRACKER_NAME
|
| 63 |
+
tracker_class = TRACKER_HEADS_REGISTRY.get(name)
|
| 64 |
+
return tracker_class(cfg)
|
RAVE-main/annotator/oneformer/detectron2/tracking/bbox_iou_tracker.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
#!/usr/bin/env python3
|
| 2 |
+
# Copyright 2004-present Facebook. All Rights Reserved.
|
| 3 |
+
import copy
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import List
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from annotator.oneformer.detectron2.config import configurable
|
| 9 |
+
from annotator.oneformer.detectron2.structures import Boxes, Instances
|
| 10 |
+
from annotator.oneformer.detectron2.structures.boxes import pairwise_iou
|
| 11 |
+
|
| 12 |
+
from ..config.config import CfgNode as CfgNode_
|
| 13 |
+
from .base_tracker import TRACKER_HEADS_REGISTRY, BaseTracker
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@TRACKER_HEADS_REGISTRY.register()
|
| 17 |
+
class BBoxIOUTracker(BaseTracker):
|
| 18 |
+
"""
|
| 19 |
+
A bounding box tracker to assign ID based on IoU between current and previous instances
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
@configurable
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
*,
|
| 26 |
+
video_height: int,
|
| 27 |
+
video_width: int,
|
| 28 |
+
max_num_instances: int = 200,
|
| 29 |
+
max_lost_frame_count: int = 0,
|
| 30 |
+
min_box_rel_dim: float = 0.02,
|
| 31 |
+
min_instance_period: int = 1,
|
| 32 |
+
track_iou_threshold: float = 0.5,
|
| 33 |
+
**kwargs,
|
| 34 |
+
):
|
| 35 |
+
"""
|
| 36 |
+
Args:
|
| 37 |
+
video_height: height the video frame
|
| 38 |
+
video_width: width of the video frame
|
| 39 |
+
max_num_instances: maximum number of id allowed to be tracked
|
| 40 |
+
max_lost_frame_count: maximum number of frame an id can lost tracking
|
| 41 |
+
exceed this number, an id is considered as lost
|
| 42 |
+
forever
|
| 43 |
+
min_box_rel_dim: a percentage, smaller than this dimension, a bbox is
|
| 44 |
+
removed from tracking
|
| 45 |
+
min_instance_period: an instance will be shown after this number of period
|
| 46 |
+
since its first showing up in the video
|
| 47 |
+
track_iou_threshold: iou threshold, below this number a bbox pair is removed
|
| 48 |
+
from tracking
|
| 49 |
+
"""
|
| 50 |
+
super().__init__(**kwargs)
|
| 51 |
+
self._video_height = video_height
|
| 52 |
+
self._video_width = video_width
|
| 53 |
+
self._max_num_instances = max_num_instances
|
| 54 |
+
self._max_lost_frame_count = max_lost_frame_count
|
| 55 |
+
self._min_box_rel_dim = min_box_rel_dim
|
| 56 |
+
self._min_instance_period = min_instance_period
|
| 57 |
+
self._track_iou_threshold = track_iou_threshold
|
| 58 |
+
|
| 59 |
+
@classmethod
|
| 60 |
+
def from_config(cls, cfg: CfgNode_):
|
| 61 |
+
"""
|
| 62 |
+
Old style initialization using CfgNode
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
cfg: D2 CfgNode, config file
|
| 66 |
+
Return:
|
| 67 |
+
dictionary storing arguments for __init__ method
|
| 68 |
+
"""
|
| 69 |
+
assert "VIDEO_HEIGHT" in cfg.TRACKER_HEADS
|
| 70 |
+
assert "VIDEO_WIDTH" in cfg.TRACKER_HEADS
|
| 71 |
+
video_height = cfg.TRACKER_HEADS.get("VIDEO_HEIGHT")
|
| 72 |
+
video_width = cfg.TRACKER_HEADS.get("VIDEO_WIDTH")
|
| 73 |
+
max_num_instances = cfg.TRACKER_HEADS.get("MAX_NUM_INSTANCES", 200)
|
| 74 |
+
max_lost_frame_count = cfg.TRACKER_HEADS.get("MAX_LOST_FRAME_COUNT", 0)
|
| 75 |
+
min_box_rel_dim = cfg.TRACKER_HEADS.get("MIN_BOX_REL_DIM", 0.02)
|
| 76 |
+
min_instance_period = cfg.TRACKER_HEADS.get("MIN_INSTANCE_PERIOD", 1)
|
| 77 |
+
track_iou_threshold = cfg.TRACKER_HEADS.get("TRACK_IOU_THRESHOLD", 0.5)
|
| 78 |
+
return {
|
| 79 |
+
"_target_": "detectron2.tracking.bbox_iou_tracker.BBoxIOUTracker",
|
| 80 |
+
"video_height": video_height,
|
| 81 |
+
"video_width": video_width,
|
| 82 |
+
"max_num_instances": max_num_instances,
|
| 83 |
+
"max_lost_frame_count": max_lost_frame_count,
|
| 84 |
+
"min_box_rel_dim": min_box_rel_dim,
|
| 85 |
+
"min_instance_period": min_instance_period,
|
| 86 |
+
"track_iou_threshold": track_iou_threshold,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def update(self, instances: Instances) -> Instances:
|
| 90 |
+
"""
|
| 91 |
+
See BaseTracker description
|
| 92 |
+
"""
|
| 93 |
+
instances = self._initialize_extra_fields(instances)
|
| 94 |
+
if self._prev_instances is not None:
|
| 95 |
+
# calculate IoU of all bbox pairs
|
| 96 |
+
iou_all = pairwise_iou(
|
| 97 |
+
boxes1=instances.pred_boxes,
|
| 98 |
+
boxes2=self._prev_instances.pred_boxes,
|
| 99 |
+
)
|
| 100 |
+
# sort IoU in descending order
|
| 101 |
+
bbox_pairs = self._create_prediction_pairs(instances, iou_all)
|
| 102 |
+
# assign previous ID to current bbox if IoU > track_iou_threshold
|
| 103 |
+
self._reset_fields()
|
| 104 |
+
for bbox_pair in bbox_pairs:
|
| 105 |
+
idx = bbox_pair["idx"]
|
| 106 |
+
prev_id = bbox_pair["prev_id"]
|
| 107 |
+
if (
|
| 108 |
+
idx in self._matched_idx
|
| 109 |
+
or prev_id in self._matched_ID
|
| 110 |
+
or bbox_pair["IoU"] < self._track_iou_threshold
|
| 111 |
+
):
|
| 112 |
+
continue
|
| 113 |
+
instances.ID[idx] = prev_id
|
| 114 |
+
instances.ID_period[idx] = bbox_pair["prev_period"] + 1
|
| 115 |
+
instances.lost_frame_count[idx] = 0
|
| 116 |
+
self._matched_idx.add(idx)
|
| 117 |
+
self._matched_ID.add(prev_id)
|
| 118 |
+
self._untracked_prev_idx.remove(bbox_pair["prev_idx"])
|
| 119 |
+
instances = self._assign_new_id(instances)
|
| 120 |
+
instances = self._merge_untracked_instances(instances)
|
| 121 |
+
self._prev_instances = copy.deepcopy(instances)
|
| 122 |
+
return instances
|
| 123 |
+
|
| 124 |
+
def _create_prediction_pairs(self, instances: Instances, iou_all: np.ndarray) -> List:
|
| 125 |
+
"""
|
| 126 |
+
For all instances in previous and current frames, create pairs. For each
|
| 127 |
+
pair, store index of the instance in current frame predcitions, index in
|
| 128 |
+
previous predictions, ID in previous predictions, IoU of the bboxes in this
|
| 129 |
+
pair, period in previous predictions.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
instances: D2 Instances, for predictions of the current frame
|
| 133 |
+
iou_all: IoU for all bboxes pairs
|
| 134 |
+
Return:
|
| 135 |
+
A list of IoU for all pairs
|
| 136 |
+
"""
|
| 137 |
+
bbox_pairs = []
|
| 138 |
+
for i in range(len(instances)):
|
| 139 |
+
for j in range(len(self._prev_instances)):
|
| 140 |
+
bbox_pairs.append(
|
| 141 |
+
{
|
| 142 |
+
"idx": i,
|
| 143 |
+
"prev_idx": j,
|
| 144 |
+
"prev_id": self._prev_instances.ID[j],
|
| 145 |
+
"IoU": iou_all[i, j],
|
| 146 |
+
"prev_period": self._prev_instances.ID_period[j],
|
| 147 |
+
}
|
| 148 |
+
)
|
| 149 |
+
return bbox_pairs
|
| 150 |
+
|
| 151 |
+
def _initialize_extra_fields(self, instances: Instances) -> Instances:
|
| 152 |
+
"""
|
| 153 |
+
If input instances don't have ID, ID_period, lost_frame_count fields,
|
| 154 |
+
this method is used to initialize these fields.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
instances: D2 Instances, for predictions of the current frame
|
| 158 |
+
Return:
|
| 159 |
+
D2 Instances with extra fields added
|
| 160 |
+
"""
|
| 161 |
+
if not instances.has("ID"):
|
| 162 |
+
instances.set("ID", [None] * len(instances))
|
| 163 |
+
if not instances.has("ID_period"):
|
| 164 |
+
instances.set("ID_period", [None] * len(instances))
|
| 165 |
+
if not instances.has("lost_frame_count"):
|
| 166 |
+
instances.set("lost_frame_count", [None] * len(instances))
|
| 167 |
+
if self._prev_instances is None:
|
| 168 |
+
instances.ID = list(range(len(instances)))
|
| 169 |
+
self._id_count += len(instances)
|
| 170 |
+
instances.ID_period = [1] * len(instances)
|
| 171 |
+
instances.lost_frame_count = [0] * len(instances)
|
| 172 |
+
return instances
|
| 173 |
+
|
| 174 |
+
def _reset_fields(self):
|
| 175 |
+
"""
|
| 176 |
+
Before each uodate call, reset fields first
|
| 177 |
+
"""
|
| 178 |
+
self._matched_idx = set()
|
| 179 |
+
self._matched_ID = set()
|
| 180 |
+
self._untracked_prev_idx = set(range(len(self._prev_instances)))
|
| 181 |
+
|
| 182 |
+
def _assign_new_id(self, instances: Instances) -> Instances:
|
| 183 |
+
"""
|
| 184 |
+
For each untracked instance, assign a new id
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
instances: D2 Instances, for predictions of the current frame
|
| 188 |
+
Return:
|
| 189 |
+
D2 Instances with new ID assigned
|
| 190 |
+
"""
|
| 191 |
+
untracked_idx = set(range(len(instances))).difference(self._matched_idx)
|
| 192 |
+
for idx in untracked_idx:
|
| 193 |
+
instances.ID[idx] = self._id_count
|
| 194 |
+
self._id_count += 1
|
| 195 |
+
instances.ID_period[idx] = 1
|
| 196 |
+
instances.lost_frame_count[idx] = 0
|
| 197 |
+
return instances
|
| 198 |
+
|
| 199 |
+
def _merge_untracked_instances(self, instances: Instances) -> Instances:
|
| 200 |
+
"""
|
| 201 |
+
For untracked previous instances, under certain condition, still keep them
|
| 202 |
+
in tracking and merge with the current instances.
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
instances: D2 Instances, for predictions of the current frame
|
| 206 |
+
Return:
|
| 207 |
+
D2 Instances merging current instances and instances from previous
|
| 208 |
+
frame decided to keep tracking
|
| 209 |
+
"""
|
| 210 |
+
untracked_instances = Instances(
|
| 211 |
+
image_size=instances.image_size,
|
| 212 |
+
pred_boxes=[],
|
| 213 |
+
pred_classes=[],
|
| 214 |
+
scores=[],
|
| 215 |
+
ID=[],
|
| 216 |
+
ID_period=[],
|
| 217 |
+
lost_frame_count=[],
|
| 218 |
+
)
|
| 219 |
+
prev_bboxes = list(self._prev_instances.pred_boxes)
|
| 220 |
+
prev_classes = list(self._prev_instances.pred_classes)
|
| 221 |
+
prev_scores = list(self._prev_instances.scores)
|
| 222 |
+
prev_ID_period = self._prev_instances.ID_period
|
| 223 |
+
if instances.has("pred_masks"):
|
| 224 |
+
untracked_instances.set("pred_masks", [])
|
| 225 |
+
prev_masks = list(self._prev_instances.pred_masks)
|
| 226 |
+
if instances.has("pred_keypoints"):
|
| 227 |
+
untracked_instances.set("pred_keypoints", [])
|
| 228 |
+
prev_keypoints = list(self._prev_instances.pred_keypoints)
|
| 229 |
+
if instances.has("pred_keypoint_heatmaps"):
|
| 230 |
+
untracked_instances.set("pred_keypoint_heatmaps", [])
|
| 231 |
+
prev_keypoint_heatmaps = list(self._prev_instances.pred_keypoint_heatmaps)
|
| 232 |
+
for idx in self._untracked_prev_idx:
|
| 233 |
+
x_left, y_top, x_right, y_bot = prev_bboxes[idx]
|
| 234 |
+
if (
|
| 235 |
+
(1.0 * (x_right - x_left) / self._video_width < self._min_box_rel_dim)
|
| 236 |
+
or (1.0 * (y_bot - y_top) / self._video_height < self._min_box_rel_dim)
|
| 237 |
+
or self._prev_instances.lost_frame_count[idx] >= self._max_lost_frame_count
|
| 238 |
+
or prev_ID_period[idx] <= self._min_instance_period
|
| 239 |
+
):
|
| 240 |
+
continue
|
| 241 |
+
untracked_instances.pred_boxes.append(list(prev_bboxes[idx].numpy()))
|
| 242 |
+
untracked_instances.pred_classes.append(int(prev_classes[idx]))
|
| 243 |
+
untracked_instances.scores.append(float(prev_scores[idx]))
|
| 244 |
+
untracked_instances.ID.append(self._prev_instances.ID[idx])
|
| 245 |
+
untracked_instances.ID_period.append(self._prev_instances.ID_period[idx])
|
| 246 |
+
untracked_instances.lost_frame_count.append(
|
| 247 |
+
self._prev_instances.lost_frame_count[idx] + 1
|
| 248 |
+
)
|
| 249 |
+
if instances.has("pred_masks"):
|
| 250 |
+
untracked_instances.pred_masks.append(prev_masks[idx].numpy().astype(np.uint8))
|
| 251 |
+
if instances.has("pred_keypoints"):
|
| 252 |
+
untracked_instances.pred_keypoints.append(
|
| 253 |
+
prev_keypoints[idx].numpy().astype(np.uint8)
|
| 254 |
+
)
|
| 255 |
+
if instances.has("pred_keypoint_heatmaps"):
|
| 256 |
+
untracked_instances.pred_keypoint_heatmaps.append(
|
| 257 |
+
prev_keypoint_heatmaps[idx].numpy().astype(np.float32)
|
| 258 |
+
)
|
| 259 |
+
untracked_instances.pred_boxes = Boxes(torch.FloatTensor(untracked_instances.pred_boxes))
|
| 260 |
+
untracked_instances.pred_classes = torch.IntTensor(untracked_instances.pred_classes)
|
| 261 |
+
untracked_instances.scores = torch.FloatTensor(untracked_instances.scores)
|
| 262 |
+
if instances.has("pred_masks"):
|
| 263 |
+
untracked_instances.pred_masks = torch.IntTensor(untracked_instances.pred_masks)
|
| 264 |
+
if instances.has("pred_keypoints"):
|
| 265 |
+
untracked_instances.pred_keypoints = torch.IntTensor(untracked_instances.pred_keypoints)
|
| 266 |
+
if instances.has("pred_keypoint_heatmaps"):
|
| 267 |
+
untracked_instances.pred_keypoint_heatmaps = torch.FloatTensor(
|
| 268 |
+
untracked_instances.pred_keypoint_heatmaps
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
return Instances.cat(
|
| 272 |
+
[
|
| 273 |
+
instances,
|
| 274 |
+
untracked_instances,
|
| 275 |
+
]
|
| 276 |
+
)
|
RAVE-main/annotator/oneformer/detectron2/tracking/hungarian_tracker.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright 2004-present Facebook. All Rights Reserved.
|
| 3 |
+
import copy
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import Dict
|
| 6 |
+
import torch
|
| 7 |
+
from scipy.optimize import linear_sum_assignment
|
| 8 |
+
|
| 9 |
+
from annotator.oneformer.detectron2.config import configurable
|
| 10 |
+
from annotator.oneformer.detectron2.structures import Boxes, Instances
|
| 11 |
+
|
| 12 |
+
from ..config.config import CfgNode as CfgNode_
|
| 13 |
+
from .base_tracker import BaseTracker
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BaseHungarianTracker(BaseTracker):
|
| 17 |
+
"""
|
| 18 |
+
A base class for all Hungarian trackers
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
@configurable
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
video_height: int,
|
| 25 |
+
video_width: int,
|
| 26 |
+
max_num_instances: int = 200,
|
| 27 |
+
max_lost_frame_count: int = 0,
|
| 28 |
+
min_box_rel_dim: float = 0.02,
|
| 29 |
+
min_instance_period: int = 1,
|
| 30 |
+
**kwargs
|
| 31 |
+
):
|
| 32 |
+
"""
|
| 33 |
+
Args:
|
| 34 |
+
video_height: height the video frame
|
| 35 |
+
video_width: width of the video frame
|
| 36 |
+
max_num_instances: maximum number of id allowed to be tracked
|
| 37 |
+
max_lost_frame_count: maximum number of frame an id can lost tracking
|
| 38 |
+
exceed this number, an id is considered as lost
|
| 39 |
+
forever
|
| 40 |
+
min_box_rel_dim: a percentage, smaller than this dimension, a bbox is
|
| 41 |
+
removed from tracking
|
| 42 |
+
min_instance_period: an instance will be shown after this number of period
|
| 43 |
+
since its first showing up in the video
|
| 44 |
+
"""
|
| 45 |
+
super().__init__(**kwargs)
|
| 46 |
+
self._video_height = video_height
|
| 47 |
+
self._video_width = video_width
|
| 48 |
+
self._max_num_instances = max_num_instances
|
| 49 |
+
self._max_lost_frame_count = max_lost_frame_count
|
| 50 |
+
self._min_box_rel_dim = min_box_rel_dim
|
| 51 |
+
self._min_instance_period = min_instance_period
|
| 52 |
+
|
| 53 |
+
@classmethod
|
| 54 |
+
def from_config(cls, cfg: CfgNode_) -> Dict:
|
| 55 |
+
raise NotImplementedError("Calling HungarianTracker::from_config")
|
| 56 |
+
|
| 57 |
+
def build_cost_matrix(self, instances: Instances, prev_instances: Instances) -> np.ndarray:
|
| 58 |
+
raise NotImplementedError("Calling HungarianTracker::build_matrix")
|
| 59 |
+
|
| 60 |
+
def update(self, instances: Instances) -> Instances:
|
| 61 |
+
if instances.has("pred_keypoints"):
|
| 62 |
+
raise NotImplementedError("Need to add support for keypoints")
|
| 63 |
+
instances = self._initialize_extra_fields(instances)
|
| 64 |
+
if self._prev_instances is not None:
|
| 65 |
+
self._untracked_prev_idx = set(range(len(self._prev_instances)))
|
| 66 |
+
cost_matrix = self.build_cost_matrix(instances, self._prev_instances)
|
| 67 |
+
matched_idx, matched_prev_idx = linear_sum_assignment(cost_matrix)
|
| 68 |
+
instances = self._process_matched_idx(instances, matched_idx, matched_prev_idx)
|
| 69 |
+
instances = self._process_unmatched_idx(instances, matched_idx)
|
| 70 |
+
instances = self._process_unmatched_prev_idx(instances, matched_prev_idx)
|
| 71 |
+
self._prev_instances = copy.deepcopy(instances)
|
| 72 |
+
return instances
|
| 73 |
+
|
| 74 |
+
def _initialize_extra_fields(self, instances: Instances) -> Instances:
|
| 75 |
+
"""
|
| 76 |
+
If input instances don't have ID, ID_period, lost_frame_count fields,
|
| 77 |
+
this method is used to initialize these fields.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
instances: D2 Instances, for predictions of the current frame
|
| 81 |
+
Return:
|
| 82 |
+
D2 Instances with extra fields added
|
| 83 |
+
"""
|
| 84 |
+
if not instances.has("ID"):
|
| 85 |
+
instances.set("ID", [None] * len(instances))
|
| 86 |
+
if not instances.has("ID_period"):
|
| 87 |
+
instances.set("ID_period", [None] * len(instances))
|
| 88 |
+
if not instances.has("lost_frame_count"):
|
| 89 |
+
instances.set("lost_frame_count", [None] * len(instances))
|
| 90 |
+
if self._prev_instances is None:
|
| 91 |
+
instances.ID = list(range(len(instances)))
|
| 92 |
+
self._id_count += len(instances)
|
| 93 |
+
instances.ID_period = [1] * len(instances)
|
| 94 |
+
instances.lost_frame_count = [0] * len(instances)
|
| 95 |
+
return instances
|
| 96 |
+
|
| 97 |
+
def _process_matched_idx(
|
| 98 |
+
self, instances: Instances, matched_idx: np.ndarray, matched_prev_idx: np.ndarray
|
| 99 |
+
) -> Instances:
|
| 100 |
+
assert matched_idx.size == matched_prev_idx.size
|
| 101 |
+
for i in range(matched_idx.size):
|
| 102 |
+
instances.ID[matched_idx[i]] = self._prev_instances.ID[matched_prev_idx[i]]
|
| 103 |
+
instances.ID_period[matched_idx[i]] = (
|
| 104 |
+
self._prev_instances.ID_period[matched_prev_idx[i]] + 1
|
| 105 |
+
)
|
| 106 |
+
instances.lost_frame_count[matched_idx[i]] = 0
|
| 107 |
+
return instances
|
| 108 |
+
|
| 109 |
+
def _process_unmatched_idx(self, instances: Instances, matched_idx: np.ndarray) -> Instances:
|
| 110 |
+
untracked_idx = set(range(len(instances))).difference(set(matched_idx))
|
| 111 |
+
for idx in untracked_idx:
|
| 112 |
+
instances.ID[idx] = self._id_count
|
| 113 |
+
self._id_count += 1
|
| 114 |
+
instances.ID_period[idx] = 1
|
| 115 |
+
instances.lost_frame_count[idx] = 0
|
| 116 |
+
return instances
|
| 117 |
+
|
| 118 |
+
def _process_unmatched_prev_idx(
|
| 119 |
+
self, instances: Instances, matched_prev_idx: np.ndarray
|
| 120 |
+
) -> Instances:
|
| 121 |
+
untracked_instances = Instances(
|
| 122 |
+
image_size=instances.image_size,
|
| 123 |
+
pred_boxes=[],
|
| 124 |
+
pred_masks=[],
|
| 125 |
+
pred_classes=[],
|
| 126 |
+
scores=[],
|
| 127 |
+
ID=[],
|
| 128 |
+
ID_period=[],
|
| 129 |
+
lost_frame_count=[],
|
| 130 |
+
)
|
| 131 |
+
prev_bboxes = list(self._prev_instances.pred_boxes)
|
| 132 |
+
prev_classes = list(self._prev_instances.pred_classes)
|
| 133 |
+
prev_scores = list(self._prev_instances.scores)
|
| 134 |
+
prev_ID_period = self._prev_instances.ID_period
|
| 135 |
+
if instances.has("pred_masks"):
|
| 136 |
+
prev_masks = list(self._prev_instances.pred_masks)
|
| 137 |
+
untracked_prev_idx = set(range(len(self._prev_instances))).difference(set(matched_prev_idx))
|
| 138 |
+
for idx in untracked_prev_idx:
|
| 139 |
+
x_left, y_top, x_right, y_bot = prev_bboxes[idx]
|
| 140 |
+
if (
|
| 141 |
+
(1.0 * (x_right - x_left) / self._video_width < self._min_box_rel_dim)
|
| 142 |
+
or (1.0 * (y_bot - y_top) / self._video_height < self._min_box_rel_dim)
|
| 143 |
+
or self._prev_instances.lost_frame_count[idx] >= self._max_lost_frame_count
|
| 144 |
+
or prev_ID_period[idx] <= self._min_instance_period
|
| 145 |
+
):
|
| 146 |
+
continue
|
| 147 |
+
untracked_instances.pred_boxes.append(list(prev_bboxes[idx].numpy()))
|
| 148 |
+
untracked_instances.pred_classes.append(int(prev_classes[idx]))
|
| 149 |
+
untracked_instances.scores.append(float(prev_scores[idx]))
|
| 150 |
+
untracked_instances.ID.append(self._prev_instances.ID[idx])
|
| 151 |
+
untracked_instances.ID_period.append(self._prev_instances.ID_period[idx])
|
| 152 |
+
untracked_instances.lost_frame_count.append(
|
| 153 |
+
self._prev_instances.lost_frame_count[idx] + 1
|
| 154 |
+
)
|
| 155 |
+
if instances.has("pred_masks"):
|
| 156 |
+
untracked_instances.pred_masks.append(prev_masks[idx].numpy().astype(np.uint8))
|
| 157 |
+
|
| 158 |
+
untracked_instances.pred_boxes = Boxes(torch.FloatTensor(untracked_instances.pred_boxes))
|
| 159 |
+
untracked_instances.pred_classes = torch.IntTensor(untracked_instances.pred_classes)
|
| 160 |
+
untracked_instances.scores = torch.FloatTensor(untracked_instances.scores)
|
| 161 |
+
if instances.has("pred_masks"):
|
| 162 |
+
untracked_instances.pred_masks = torch.IntTensor(untracked_instances.pred_masks)
|
| 163 |
+
else:
|
| 164 |
+
untracked_instances.remove("pred_masks")
|
| 165 |
+
|
| 166 |
+
return Instances.cat(
|
| 167 |
+
[
|
| 168 |
+
instances,
|
| 169 |
+
untracked_instances,
|
| 170 |
+
]
|
| 171 |
+
)
|
RAVE-main/annotator/oneformer/detectron2/tracking/iou_weighted_hungarian_bbox_iou_tracker.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright 2004-present Facebook. All Rights Reserved.
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
from annotator.oneformer.detectron2.config import CfgNode as CfgNode_
|
| 8 |
+
from annotator.oneformer.detectron2.config import configurable
|
| 9 |
+
|
| 10 |
+
from .base_tracker import TRACKER_HEADS_REGISTRY
|
| 11 |
+
from .vanilla_hungarian_bbox_iou_tracker import VanillaHungarianBBoxIOUTracker
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@TRACKER_HEADS_REGISTRY.register()
|
| 15 |
+
class IOUWeightedHungarianBBoxIOUTracker(VanillaHungarianBBoxIOUTracker):
|
| 16 |
+
"""
|
| 17 |
+
A tracker using IoU as weight in Hungarian algorithm, also known
|
| 18 |
+
as Munkres or Kuhn-Munkres algorithm
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
@configurable
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
*,
|
| 25 |
+
video_height: int,
|
| 26 |
+
video_width: int,
|
| 27 |
+
max_num_instances: int = 200,
|
| 28 |
+
max_lost_frame_count: int = 0,
|
| 29 |
+
min_box_rel_dim: float = 0.02,
|
| 30 |
+
min_instance_period: int = 1,
|
| 31 |
+
track_iou_threshold: float = 0.5,
|
| 32 |
+
**kwargs,
|
| 33 |
+
):
|
| 34 |
+
"""
|
| 35 |
+
Args:
|
| 36 |
+
video_height: height the video frame
|
| 37 |
+
video_width: width of the video frame
|
| 38 |
+
max_num_instances: maximum number of id allowed to be tracked
|
| 39 |
+
max_lost_frame_count: maximum number of frame an id can lost tracking
|
| 40 |
+
exceed this number, an id is considered as lost
|
| 41 |
+
forever
|
| 42 |
+
min_box_rel_dim: a percentage, smaller than this dimension, a bbox is
|
| 43 |
+
removed from tracking
|
| 44 |
+
min_instance_period: an instance will be shown after this number of period
|
| 45 |
+
since its first showing up in the video
|
| 46 |
+
track_iou_threshold: iou threshold, below this number a bbox pair is removed
|
| 47 |
+
from tracking
|
| 48 |
+
"""
|
| 49 |
+
super().__init__(
|
| 50 |
+
video_height=video_height,
|
| 51 |
+
video_width=video_width,
|
| 52 |
+
max_num_instances=max_num_instances,
|
| 53 |
+
max_lost_frame_count=max_lost_frame_count,
|
| 54 |
+
min_box_rel_dim=min_box_rel_dim,
|
| 55 |
+
min_instance_period=min_instance_period,
|
| 56 |
+
track_iou_threshold=track_iou_threshold,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
@classmethod
|
| 60 |
+
def from_config(cls, cfg: CfgNode_):
|
| 61 |
+
"""
|
| 62 |
+
Old style initialization using CfgNode
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
cfg: D2 CfgNode, config file
|
| 66 |
+
Return:
|
| 67 |
+
dictionary storing arguments for __init__ method
|
| 68 |
+
"""
|
| 69 |
+
assert "VIDEO_HEIGHT" in cfg.TRACKER_HEADS
|
| 70 |
+
assert "VIDEO_WIDTH" in cfg.TRACKER_HEADS
|
| 71 |
+
video_height = cfg.TRACKER_HEADS.get("VIDEO_HEIGHT")
|
| 72 |
+
video_width = cfg.TRACKER_HEADS.get("VIDEO_WIDTH")
|
| 73 |
+
max_num_instances = cfg.TRACKER_HEADS.get("MAX_NUM_INSTANCES", 200)
|
| 74 |
+
max_lost_frame_count = cfg.TRACKER_HEADS.get("MAX_LOST_FRAME_COUNT", 0)
|
| 75 |
+
min_box_rel_dim = cfg.TRACKER_HEADS.get("MIN_BOX_REL_DIM", 0.02)
|
| 76 |
+
min_instance_period = cfg.TRACKER_HEADS.get("MIN_INSTANCE_PERIOD", 1)
|
| 77 |
+
track_iou_threshold = cfg.TRACKER_HEADS.get("TRACK_IOU_THRESHOLD", 0.5)
|
| 78 |
+
return {
|
| 79 |
+
"_target_": "detectron2.tracking.iou_weighted_hungarian_bbox_iou_tracker.IOUWeightedHungarianBBoxIOUTracker", # noqa
|
| 80 |
+
"video_height": video_height,
|
| 81 |
+
"video_width": video_width,
|
| 82 |
+
"max_num_instances": max_num_instances,
|
| 83 |
+
"max_lost_frame_count": max_lost_frame_count,
|
| 84 |
+
"min_box_rel_dim": min_box_rel_dim,
|
| 85 |
+
"min_instance_period": min_instance_period,
|
| 86 |
+
"track_iou_threshold": track_iou_threshold,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def assign_cost_matrix_values(self, cost_matrix: np.ndarray, bbox_pairs: List) -> np.ndarray:
|
| 90 |
+
"""
|
| 91 |
+
Based on IoU for each pair of bbox, assign the associated value in cost matrix
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
cost_matrix: np.ndarray, initialized 2D array with target dimensions
|
| 95 |
+
bbox_pairs: list of bbox pair, in each pair, iou value is stored
|
| 96 |
+
Return:
|
| 97 |
+
np.ndarray, cost_matrix with assigned values
|
| 98 |
+
"""
|
| 99 |
+
for pair in bbox_pairs:
|
| 100 |
+
# assign (-1 * IoU) for above threshold pairs, algorithms will minimize cost
|
| 101 |
+
cost_matrix[pair["idx"]][pair["prev_idx"]] = -1 * pair["IoU"]
|
| 102 |
+
return cost_matrix
|
RAVE-main/annotator/oneformer/detectron2/tracking/utils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import numpy as np
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from annotator.oneformer.detectron2.structures import Instances
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def create_prediction_pairs(
|
| 9 |
+
instances: Instances,
|
| 10 |
+
prev_instances: Instances,
|
| 11 |
+
iou_all: np.ndarray,
|
| 12 |
+
threshold: float = 0.5,
|
| 13 |
+
) -> List:
|
| 14 |
+
"""
|
| 15 |
+
Args:
|
| 16 |
+
instances: predictions from current frame
|
| 17 |
+
prev_instances: predictions from previous frame
|
| 18 |
+
iou_all: 2D numpy array containing iou for each bbox pair
|
| 19 |
+
threshold: below the threshold, doesn't consider the pair of bbox is valid
|
| 20 |
+
Return:
|
| 21 |
+
List of bbox pairs
|
| 22 |
+
"""
|
| 23 |
+
bbox_pairs = []
|
| 24 |
+
for i in range(len(instances)):
|
| 25 |
+
for j in range(len(prev_instances)):
|
| 26 |
+
if iou_all[i, j] < threshold:
|
| 27 |
+
continue
|
| 28 |
+
bbox_pairs.append(
|
| 29 |
+
{
|
| 30 |
+
"idx": i,
|
| 31 |
+
"prev_idx": j,
|
| 32 |
+
"prev_id": prev_instances.ID[j],
|
| 33 |
+
"IoU": iou_all[i, j],
|
| 34 |
+
"prev_period": prev_instances.ID_period[j],
|
| 35 |
+
}
|
| 36 |
+
)
|
| 37 |
+
return bbox_pairs
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
LARGE_COST_VALUE = 100000
|
RAVE-main/annotator/oneformer/detectron2/tracking/vanilla_hungarian_bbox_iou_tracker.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright 2004-present Facebook. All Rights Reserved.
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
from annotator.oneformer.detectron2.config import CfgNode as CfgNode_
|
| 8 |
+
from annotator.oneformer.detectron2.config import configurable
|
| 9 |
+
from annotator.oneformer.detectron2.structures import Instances
|
| 10 |
+
from annotator.oneformer.detectron2.structures.boxes import pairwise_iou
|
| 11 |
+
from annotator.oneformer.detectron2.tracking.utils import LARGE_COST_VALUE, create_prediction_pairs
|
| 12 |
+
|
| 13 |
+
from .base_tracker import TRACKER_HEADS_REGISTRY
|
| 14 |
+
from .hungarian_tracker import BaseHungarianTracker
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@TRACKER_HEADS_REGISTRY.register()
|
| 18 |
+
class VanillaHungarianBBoxIOUTracker(BaseHungarianTracker):
|
| 19 |
+
"""
|
| 20 |
+
Hungarian algo based tracker using bbox iou as metric
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
@configurable
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
*,
|
| 27 |
+
video_height: int,
|
| 28 |
+
video_width: int,
|
| 29 |
+
max_num_instances: int = 200,
|
| 30 |
+
max_lost_frame_count: int = 0,
|
| 31 |
+
min_box_rel_dim: float = 0.02,
|
| 32 |
+
min_instance_period: int = 1,
|
| 33 |
+
track_iou_threshold: float = 0.5,
|
| 34 |
+
**kwargs,
|
| 35 |
+
):
|
| 36 |
+
"""
|
| 37 |
+
Args:
|
| 38 |
+
video_height: height the video frame
|
| 39 |
+
video_width: width of the video frame
|
| 40 |
+
max_num_instances: maximum number of id allowed to be tracked
|
| 41 |
+
max_lost_frame_count: maximum number of frame an id can lost tracking
|
| 42 |
+
exceed this number, an id is considered as lost
|
| 43 |
+
forever
|
| 44 |
+
min_box_rel_dim: a percentage, smaller than this dimension, a bbox is
|
| 45 |
+
removed from tracking
|
| 46 |
+
min_instance_period: an instance will be shown after this number of period
|
| 47 |
+
since its first showing up in the video
|
| 48 |
+
track_iou_threshold: iou threshold, below this number a bbox pair is removed
|
| 49 |
+
from tracking
|
| 50 |
+
"""
|
| 51 |
+
super().__init__(
|
| 52 |
+
video_height=video_height,
|
| 53 |
+
video_width=video_width,
|
| 54 |
+
max_num_instances=max_num_instances,
|
| 55 |
+
max_lost_frame_count=max_lost_frame_count,
|
| 56 |
+
min_box_rel_dim=min_box_rel_dim,
|
| 57 |
+
min_instance_period=min_instance_period,
|
| 58 |
+
)
|
| 59 |
+
self._track_iou_threshold = track_iou_threshold
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def from_config(cls, cfg: CfgNode_):
|
| 63 |
+
"""
|
| 64 |
+
Old style initialization using CfgNode
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
cfg: D2 CfgNode, config file
|
| 68 |
+
Return:
|
| 69 |
+
dictionary storing arguments for __init__ method
|
| 70 |
+
"""
|
| 71 |
+
assert "VIDEO_HEIGHT" in cfg.TRACKER_HEADS
|
| 72 |
+
assert "VIDEO_WIDTH" in cfg.TRACKER_HEADS
|
| 73 |
+
video_height = cfg.TRACKER_HEADS.get("VIDEO_HEIGHT")
|
| 74 |
+
video_width = cfg.TRACKER_HEADS.get("VIDEO_WIDTH")
|
| 75 |
+
max_num_instances = cfg.TRACKER_HEADS.get("MAX_NUM_INSTANCES", 200)
|
| 76 |
+
max_lost_frame_count = cfg.TRACKER_HEADS.get("MAX_LOST_FRAME_COUNT", 0)
|
| 77 |
+
min_box_rel_dim = cfg.TRACKER_HEADS.get("MIN_BOX_REL_DIM", 0.02)
|
| 78 |
+
min_instance_period = cfg.TRACKER_HEADS.get("MIN_INSTANCE_PERIOD", 1)
|
| 79 |
+
track_iou_threshold = cfg.TRACKER_HEADS.get("TRACK_IOU_THRESHOLD", 0.5)
|
| 80 |
+
return {
|
| 81 |
+
"_target_": "detectron2.tracking.vanilla_hungarian_bbox_iou_tracker.VanillaHungarianBBoxIOUTracker", # noqa
|
| 82 |
+
"video_height": video_height,
|
| 83 |
+
"video_width": video_width,
|
| 84 |
+
"max_num_instances": max_num_instances,
|
| 85 |
+
"max_lost_frame_count": max_lost_frame_count,
|
| 86 |
+
"min_box_rel_dim": min_box_rel_dim,
|
| 87 |
+
"min_instance_period": min_instance_period,
|
| 88 |
+
"track_iou_threshold": track_iou_threshold,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
def build_cost_matrix(self, instances: Instances, prev_instances: Instances) -> np.ndarray:
|
| 92 |
+
"""
|
| 93 |
+
Build the cost matrix for assignment problem
|
| 94 |
+
(https://en.wikipedia.org/wiki/Assignment_problem)
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
instances: D2 Instances, for current frame predictions
|
| 98 |
+
prev_instances: D2 Instances, for previous frame predictions
|
| 99 |
+
|
| 100 |
+
Return:
|
| 101 |
+
the cost matrix in numpy array
|
| 102 |
+
"""
|
| 103 |
+
assert instances is not None and prev_instances is not None
|
| 104 |
+
# calculate IoU of all bbox pairs
|
| 105 |
+
iou_all = pairwise_iou(
|
| 106 |
+
boxes1=instances.pred_boxes,
|
| 107 |
+
boxes2=self._prev_instances.pred_boxes,
|
| 108 |
+
)
|
| 109 |
+
bbox_pairs = create_prediction_pairs(
|
| 110 |
+
instances, self._prev_instances, iou_all, threshold=self._track_iou_threshold
|
| 111 |
+
)
|
| 112 |
+
# assign large cost value to make sure pair below IoU threshold won't be matched
|
| 113 |
+
cost_matrix = np.full((len(instances), len(prev_instances)), LARGE_COST_VALUE)
|
| 114 |
+
return self.assign_cost_matrix_values(cost_matrix, bbox_pairs)
|
| 115 |
+
|
| 116 |
+
def assign_cost_matrix_values(self, cost_matrix: np.ndarray, bbox_pairs: List) -> np.ndarray:
|
| 117 |
+
"""
|
| 118 |
+
Based on IoU for each pair of bbox, assign the associated value in cost matrix
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
cost_matrix: np.ndarray, initialized 2D array with target dimensions
|
| 122 |
+
bbox_pairs: list of bbox pair, in each pair, iou value is stored
|
| 123 |
+
Return:
|
| 124 |
+
np.ndarray, cost_matrix with assigned values
|
| 125 |
+
"""
|
| 126 |
+
for pair in bbox_pairs:
|
| 127 |
+
# assign -1 for IoU above threshold pairs, algorithms will minimize cost
|
| 128 |
+
cost_matrix[pair["idx"]][pair["prev_idx"]] = -1
|
| 129 |
+
return cost_matrix
|
RAVE-main/annotator/oneformer/detectron2/utils/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Utility functions
|
| 2 |
+
|
| 3 |
+
This folder contain utility functions that are not used in the
|
| 4 |
+
core library, but are useful for building models or training
|
| 5 |
+
code using the config system.
|
RAVE-main/annotator/oneformer/detectron2/utils/colormap.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
An awesome colormap for really neat visualizations.
|
| 5 |
+
Copied from Detectron, and removed gray colors.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import random
|
| 10 |
+
|
| 11 |
+
__all__ = ["colormap", "random_color", "random_colors"]
|
| 12 |
+
|
| 13 |
+
# fmt: off
|
| 14 |
+
# RGB:
|
| 15 |
+
_COLORS = np.array(
|
| 16 |
+
[
|
| 17 |
+
0.000, 0.447, 0.741,
|
| 18 |
+
0.850, 0.325, 0.098,
|
| 19 |
+
0.929, 0.694, 0.125,
|
| 20 |
+
0.494, 0.184, 0.556,
|
| 21 |
+
0.466, 0.674, 0.188,
|
| 22 |
+
0.301, 0.745, 0.933,
|
| 23 |
+
0.635, 0.078, 0.184,
|
| 24 |
+
0.300, 0.300, 0.300,
|
| 25 |
+
0.600, 0.600, 0.600,
|
| 26 |
+
1.000, 0.000, 0.000,
|
| 27 |
+
1.000, 0.500, 0.000,
|
| 28 |
+
0.749, 0.749, 0.000,
|
| 29 |
+
0.000, 1.000, 0.000,
|
| 30 |
+
0.000, 0.000, 1.000,
|
| 31 |
+
0.667, 0.000, 1.000,
|
| 32 |
+
0.333, 0.333, 0.000,
|
| 33 |
+
0.333, 0.667, 0.000,
|
| 34 |
+
0.333, 1.000, 0.000,
|
| 35 |
+
0.667, 0.333, 0.000,
|
| 36 |
+
0.667, 0.667, 0.000,
|
| 37 |
+
0.667, 1.000, 0.000,
|
| 38 |
+
1.000, 0.333, 0.000,
|
| 39 |
+
1.000, 0.667, 0.000,
|
| 40 |
+
1.000, 1.000, 0.000,
|
| 41 |
+
0.000, 0.333, 0.500,
|
| 42 |
+
0.000, 0.667, 0.500,
|
| 43 |
+
0.000, 1.000, 0.500,
|
| 44 |
+
0.333, 0.000, 0.500,
|
| 45 |
+
0.333, 0.333, 0.500,
|
| 46 |
+
0.333, 0.667, 0.500,
|
| 47 |
+
0.333, 1.000, 0.500,
|
| 48 |
+
0.667, 0.000, 0.500,
|
| 49 |
+
0.667, 0.333, 0.500,
|
| 50 |
+
0.667, 0.667, 0.500,
|
| 51 |
+
0.667, 1.000, 0.500,
|
| 52 |
+
1.000, 0.000, 0.500,
|
| 53 |
+
1.000, 0.333, 0.500,
|
| 54 |
+
1.000, 0.667, 0.500,
|
| 55 |
+
1.000, 1.000, 0.500,
|
| 56 |
+
0.000, 0.333, 1.000,
|
| 57 |
+
0.000, 0.667, 1.000,
|
| 58 |
+
0.000, 1.000, 1.000,
|
| 59 |
+
0.333, 0.000, 1.000,
|
| 60 |
+
0.333, 0.333, 1.000,
|
| 61 |
+
0.333, 0.667, 1.000,
|
| 62 |
+
0.333, 1.000, 1.000,
|
| 63 |
+
0.667, 0.000, 1.000,
|
| 64 |
+
0.667, 0.333, 1.000,
|
| 65 |
+
0.667, 0.667, 1.000,
|
| 66 |
+
0.667, 1.000, 1.000,
|
| 67 |
+
1.000, 0.000, 1.000,
|
| 68 |
+
1.000, 0.333, 1.000,
|
| 69 |
+
1.000, 0.667, 1.000,
|
| 70 |
+
0.333, 0.000, 0.000,
|
| 71 |
+
0.500, 0.000, 0.000,
|
| 72 |
+
0.667, 0.000, 0.000,
|
| 73 |
+
0.833, 0.000, 0.000,
|
| 74 |
+
1.000, 0.000, 0.000,
|
| 75 |
+
0.000, 0.167, 0.000,
|
| 76 |
+
0.000, 0.333, 0.000,
|
| 77 |
+
0.000, 0.500, 0.000,
|
| 78 |
+
0.000, 0.667, 0.000,
|
| 79 |
+
0.000, 0.833, 0.000,
|
| 80 |
+
0.000, 1.000, 0.000,
|
| 81 |
+
0.000, 0.000, 0.167,
|
| 82 |
+
0.000, 0.000, 0.333,
|
| 83 |
+
0.000, 0.000, 0.500,
|
| 84 |
+
0.000, 0.000, 0.667,
|
| 85 |
+
0.000, 0.000, 0.833,
|
| 86 |
+
0.000, 0.000, 1.000,
|
| 87 |
+
0.000, 0.000, 0.000,
|
| 88 |
+
0.143, 0.143, 0.143,
|
| 89 |
+
0.857, 0.857, 0.857,
|
| 90 |
+
1.000, 1.000, 1.000
|
| 91 |
+
]
|
| 92 |
+
).astype(np.float32).reshape(-1, 3)
|
| 93 |
+
# fmt: on
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def colormap(rgb=False, maximum=255):
|
| 97 |
+
"""
|
| 98 |
+
Args:
|
| 99 |
+
rgb (bool): whether to return RGB colors or BGR colors.
|
| 100 |
+
maximum (int): either 255 or 1
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
ndarray: a float32 array of Nx3 colors, in range [0, 255] or [0, 1]
|
| 104 |
+
"""
|
| 105 |
+
assert maximum in [255, 1], maximum
|
| 106 |
+
c = _COLORS * maximum
|
| 107 |
+
if not rgb:
|
| 108 |
+
c = c[:, ::-1]
|
| 109 |
+
return c
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def random_color(rgb=False, maximum=255):
|
| 113 |
+
"""
|
| 114 |
+
Args:
|
| 115 |
+
rgb (bool): whether to return RGB colors or BGR colors.
|
| 116 |
+
maximum (int): either 255 or 1
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
ndarray: a vector of 3 numbers
|
| 120 |
+
"""
|
| 121 |
+
idx = np.random.randint(0, len(_COLORS))
|
| 122 |
+
ret = _COLORS[idx] * maximum
|
| 123 |
+
if not rgb:
|
| 124 |
+
ret = ret[::-1]
|
| 125 |
+
return ret
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def random_colors(N, rgb=False, maximum=255):
|
| 129 |
+
"""
|
| 130 |
+
Args:
|
| 131 |
+
N (int): number of unique colors needed
|
| 132 |
+
rgb (bool): whether to return RGB colors or BGR colors.
|
| 133 |
+
maximum (int): either 255 or 1
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
ndarray: a list of random_color
|
| 137 |
+
"""
|
| 138 |
+
indices = random.sample(range(len(_COLORS)), N)
|
| 139 |
+
ret = [_COLORS[i] * maximum for i in indices]
|
| 140 |
+
if not rgb:
|
| 141 |
+
ret = [x[::-1] for x in ret]
|
| 142 |
+
return ret
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
import cv2
|
| 147 |
+
|
| 148 |
+
size = 100
|
| 149 |
+
H, W = 10, 10
|
| 150 |
+
canvas = np.random.rand(H * size, W * size, 3).astype("float32")
|
| 151 |
+
for h in range(H):
|
| 152 |
+
for w in range(W):
|
| 153 |
+
idx = h * W + w
|
| 154 |
+
if idx >= len(_COLORS):
|
| 155 |
+
break
|
| 156 |
+
canvas[h * size : (h + 1) * size, w * size : (w + 1) * size] = _COLORS[idx]
|
| 157 |
+
cv2.imshow("a", canvas)
|
| 158 |
+
cv2.waitKey(0)
|
RAVE-main/annotator/oneformer/detectron2/utils/env.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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4 |
+
import logging
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
+
import random
|
| 8 |
+
import sys
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
__all__ = ["seed_all_rng"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
TORCH_VERSION = tuple(int(x) for x in torch.__version__.split(".")[:2])
|
| 16 |
+
"""
|
| 17 |
+
PyTorch version as a tuple of 2 ints. Useful for comparison.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
DOC_BUILDING = os.getenv("_DOC_BUILDING", False) # set in docs/conf.py
|
| 22 |
+
"""
|
| 23 |
+
Whether we're building documentation.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def seed_all_rng(seed=None):
|
| 28 |
+
"""
|
| 29 |
+
Set the random seed for the RNG in torch, numpy and python.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
seed (int): if None, will use a strong random seed.
|
| 33 |
+
"""
|
| 34 |
+
if seed is None:
|
| 35 |
+
seed = (
|
| 36 |
+
os.getpid()
|
| 37 |
+
+ int(datetime.now().strftime("%S%f"))
|
| 38 |
+
+ int.from_bytes(os.urandom(2), "big")
|
| 39 |
+
)
|
| 40 |
+
logger = logging.getLogger(__name__)
|
| 41 |
+
logger.info("Using a generated random seed {}".format(seed))
|
| 42 |
+
np.random.seed(seed)
|
| 43 |
+
torch.manual_seed(seed)
|
| 44 |
+
random.seed(seed)
|
| 45 |
+
os.environ["PYTHONHASHSEED"] = str(seed)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# from https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
|
| 49 |
+
def _import_file(module_name, file_path, make_importable=False):
|
| 50 |
+
spec = importlib.util.spec_from_file_location(module_name, file_path)
|
| 51 |
+
module = importlib.util.module_from_spec(spec)
|
| 52 |
+
spec.loader.exec_module(module)
|
| 53 |
+
if make_importable:
|
| 54 |
+
sys.modules[module_name] = module
|
| 55 |
+
return module
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _configure_libraries():
|
| 59 |
+
"""
|
| 60 |
+
Configurations for some libraries.
|
| 61 |
+
"""
|
| 62 |
+
# An environment option to disable `import cv2` globally,
|
| 63 |
+
# in case it leads to negative performance impact
|
| 64 |
+
disable_cv2 = int(os.environ.get("DETECTRON2_DISABLE_CV2", False))
|
| 65 |
+
if disable_cv2:
|
| 66 |
+
sys.modules["cv2"] = None
|
| 67 |
+
else:
|
| 68 |
+
# Disable opencl in opencv since its interaction with cuda often has negative effects
|
| 69 |
+
# This envvar is supported after OpenCV 3.4.0
|
| 70 |
+
os.environ["OPENCV_OPENCL_RUNTIME"] = "disabled"
|
| 71 |
+
try:
|
| 72 |
+
import cv2
|
| 73 |
+
|
| 74 |
+
if int(cv2.__version__.split(".")[0]) >= 3:
|
| 75 |
+
cv2.ocl.setUseOpenCL(False)
|
| 76 |
+
except ModuleNotFoundError:
|
| 77 |
+
# Other types of ImportError, if happened, should not be ignored.
|
| 78 |
+
# Because a failed opencv import could mess up address space
|
| 79 |
+
# https://github.com/skvark/opencv-python/issues/381
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
def get_version(module, digit=2):
|
| 83 |
+
return tuple(map(int, module.__version__.split(".")[:digit]))
|
| 84 |
+
|
| 85 |
+
# fmt: off
|
| 86 |
+
assert get_version(torch) >= (1, 4), "Requires torch>=1.4"
|
| 87 |
+
import fvcore
|
| 88 |
+
assert get_version(fvcore, 3) >= (0, 1, 2), "Requires fvcore>=0.1.2"
|
| 89 |
+
import yaml
|
| 90 |
+
assert get_version(yaml) >= (5, 1), "Requires pyyaml>=5.1"
|
| 91 |
+
# fmt: on
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
_ENV_SETUP_DONE = False
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def setup_environment():
|
| 98 |
+
"""Perform environment setup work. The default setup is a no-op, but this
|
| 99 |
+
function allows the user to specify a Python source file or a module in
|
| 100 |
+
the $DETECTRON2_ENV_MODULE environment variable, that performs
|
| 101 |
+
custom setup work that may be necessary to their computing environment.
|
| 102 |
+
"""
|
| 103 |
+
global _ENV_SETUP_DONE
|
| 104 |
+
if _ENV_SETUP_DONE:
|
| 105 |
+
return
|
| 106 |
+
_ENV_SETUP_DONE = True
|
| 107 |
+
|
| 108 |
+
_configure_libraries()
|
| 109 |
+
|
| 110 |
+
custom_module_path = os.environ.get("DETECTRON2_ENV_MODULE")
|
| 111 |
+
|
| 112 |
+
if custom_module_path:
|
| 113 |
+
setup_custom_environment(custom_module_path)
|
| 114 |
+
else:
|
| 115 |
+
# The default setup is a no-op
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def setup_custom_environment(custom_module):
|
| 120 |
+
"""
|
| 121 |
+
Load custom environment setup by importing a Python source file or a
|
| 122 |
+
module, and run the setup function.
|
| 123 |
+
"""
|
| 124 |
+
if custom_module.endswith(".py"):
|
| 125 |
+
module = _import_file("detectron2.utils.env.custom_module", custom_module)
|
| 126 |
+
else:
|
| 127 |
+
module = importlib.import_module(custom_module)
|
| 128 |
+
assert hasattr(module, "setup_environment") and callable(module.setup_environment), (
|
| 129 |
+
"Custom environment module defined in {} does not have the "
|
| 130 |
+
"required callable attribute 'setup_environment'."
|
| 131 |
+
).format(custom_module)
|
| 132 |
+
module.setup_environment()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def fixup_module_metadata(module_name, namespace, keys=None):
|
| 136 |
+
"""
|
| 137 |
+
Fix the __qualname__ of module members to be their exported api name, so
|
| 138 |
+
when they are referenced in docs, sphinx can find them. Reference:
|
| 139 |
+
https://github.com/python-trio/trio/blob/6754c74eacfad9cc5c92d5c24727a2f3b620624e/trio/_util.py#L216-L241
|
| 140 |
+
"""
|
| 141 |
+
if not DOC_BUILDING:
|
| 142 |
+
return
|
| 143 |
+
seen_ids = set()
|
| 144 |
+
|
| 145 |
+
def fix_one(qualname, name, obj):
|
| 146 |
+
# avoid infinite recursion (relevant when using
|
| 147 |
+
# typing.Generic, for example)
|
| 148 |
+
if id(obj) in seen_ids:
|
| 149 |
+
return
|
| 150 |
+
seen_ids.add(id(obj))
|
| 151 |
+
|
| 152 |
+
mod = getattr(obj, "__module__", None)
|
| 153 |
+
if mod is not None and (mod.startswith(module_name) or mod.startswith("fvcore.")):
|
| 154 |
+
obj.__module__ = module_name
|
| 155 |
+
# Modules, unlike everything else in Python, put fully-qualitied
|
| 156 |
+
# names into their __name__ attribute. We check for "." to avoid
|
| 157 |
+
# rewriting these.
|
| 158 |
+
if hasattr(obj, "__name__") and "." not in obj.__name__:
|
| 159 |
+
obj.__name__ = name
|
| 160 |
+
obj.__qualname__ = qualname
|
| 161 |
+
if isinstance(obj, type):
|
| 162 |
+
for attr_name, attr_value in obj.__dict__.items():
|
| 163 |
+
fix_one(objname + "." + attr_name, attr_name, attr_value)
|
| 164 |
+
|
| 165 |
+
if keys is None:
|
| 166 |
+
keys = namespace.keys()
|
| 167 |
+
for objname in keys:
|
| 168 |
+
if not objname.startswith("_"):
|
| 169 |
+
obj = namespace[objname]
|
| 170 |
+
fix_one(objname, objname, obj)
|
RAVE-main/annotator/oneformer/detectron2/utils/events.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
import datetime
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
from typing import Optional
|
| 10 |
+
import torch
|
| 11 |
+
from fvcore.common.history_buffer import HistoryBuffer
|
| 12 |
+
|
| 13 |
+
from annotator.oneformer.detectron2.utils.file_io import PathManager
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"get_event_storage",
|
| 17 |
+
"JSONWriter",
|
| 18 |
+
"TensorboardXWriter",
|
| 19 |
+
"CommonMetricPrinter",
|
| 20 |
+
"EventStorage",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
_CURRENT_STORAGE_STACK = []
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_event_storage():
|
| 27 |
+
"""
|
| 28 |
+
Returns:
|
| 29 |
+
The :class:`EventStorage` object that's currently being used.
|
| 30 |
+
Throws an error if no :class:`EventStorage` is currently enabled.
|
| 31 |
+
"""
|
| 32 |
+
assert len(
|
| 33 |
+
_CURRENT_STORAGE_STACK
|
| 34 |
+
), "get_event_storage() has to be called inside a 'with EventStorage(...)' context!"
|
| 35 |
+
return _CURRENT_STORAGE_STACK[-1]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class EventWriter:
|
| 39 |
+
"""
|
| 40 |
+
Base class for writers that obtain events from :class:`EventStorage` and process them.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def write(self):
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
def close(self):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class JSONWriter(EventWriter):
|
| 51 |
+
"""
|
| 52 |
+
Write scalars to a json file.
|
| 53 |
+
|
| 54 |
+
It saves scalars as one json per line (instead of a big json) for easy parsing.
|
| 55 |
+
|
| 56 |
+
Examples parsing such a json file:
|
| 57 |
+
::
|
| 58 |
+
$ cat metrics.json | jq -s '.[0:2]'
|
| 59 |
+
[
|
| 60 |
+
{
|
| 61 |
+
"data_time": 0.008433341979980469,
|
| 62 |
+
"iteration": 19,
|
| 63 |
+
"loss": 1.9228371381759644,
|
| 64 |
+
"loss_box_reg": 0.050025828182697296,
|
| 65 |
+
"loss_classifier": 0.5316952466964722,
|
| 66 |
+
"loss_mask": 0.7236229181289673,
|
| 67 |
+
"loss_rpn_box": 0.0856662318110466,
|
| 68 |
+
"loss_rpn_cls": 0.48198649287223816,
|
| 69 |
+
"lr": 0.007173333333333333,
|
| 70 |
+
"time": 0.25401854515075684
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"data_time": 0.007216215133666992,
|
| 74 |
+
"iteration": 39,
|
| 75 |
+
"loss": 1.282649278640747,
|
| 76 |
+
"loss_box_reg": 0.06222952902317047,
|
| 77 |
+
"loss_classifier": 0.30682939291000366,
|
| 78 |
+
"loss_mask": 0.6970193982124329,
|
| 79 |
+
"loss_rpn_box": 0.038663312792778015,
|
| 80 |
+
"loss_rpn_cls": 0.1471673548221588,
|
| 81 |
+
"lr": 0.007706666666666667,
|
| 82 |
+
"time": 0.2490077018737793
|
| 83 |
+
}
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
$ cat metrics.json | jq '.loss_mask'
|
| 87 |
+
0.7126231789588928
|
| 88 |
+
0.689423680305481
|
| 89 |
+
0.6776131987571716
|
| 90 |
+
...
|
| 91 |
+
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, json_file, window_size=20):
|
| 95 |
+
"""
|
| 96 |
+
Args:
|
| 97 |
+
json_file (str): path to the json file. New data will be appended if the file exists.
|
| 98 |
+
window_size (int): the window size of median smoothing for the scalars whose
|
| 99 |
+
`smoothing_hint` are True.
|
| 100 |
+
"""
|
| 101 |
+
self._file_handle = PathManager.open(json_file, "a")
|
| 102 |
+
self._window_size = window_size
|
| 103 |
+
self._last_write = -1
|
| 104 |
+
|
| 105 |
+
def write(self):
|
| 106 |
+
storage = get_event_storage()
|
| 107 |
+
to_save = defaultdict(dict)
|
| 108 |
+
|
| 109 |
+
for k, (v, iter) in storage.latest_with_smoothing_hint(self._window_size).items():
|
| 110 |
+
# keep scalars that have not been written
|
| 111 |
+
if iter <= self._last_write:
|
| 112 |
+
continue
|
| 113 |
+
to_save[iter][k] = v
|
| 114 |
+
if len(to_save):
|
| 115 |
+
all_iters = sorted(to_save.keys())
|
| 116 |
+
self._last_write = max(all_iters)
|
| 117 |
+
|
| 118 |
+
for itr, scalars_per_iter in to_save.items():
|
| 119 |
+
scalars_per_iter["iteration"] = itr
|
| 120 |
+
self._file_handle.write(json.dumps(scalars_per_iter, sort_keys=True) + "\n")
|
| 121 |
+
self._file_handle.flush()
|
| 122 |
+
try:
|
| 123 |
+
os.fsync(self._file_handle.fileno())
|
| 124 |
+
except AttributeError:
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
def close(self):
|
| 128 |
+
self._file_handle.close()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class TensorboardXWriter(EventWriter):
|
| 132 |
+
"""
|
| 133 |
+
Write all scalars to a tensorboard file.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
def __init__(self, log_dir: str, window_size: int = 20, **kwargs):
|
| 137 |
+
"""
|
| 138 |
+
Args:
|
| 139 |
+
log_dir (str): the directory to save the output events
|
| 140 |
+
window_size (int): the scalars will be median-smoothed by this window size
|
| 141 |
+
|
| 142 |
+
kwargs: other arguments passed to `torch.utils.tensorboard.SummaryWriter(...)`
|
| 143 |
+
"""
|
| 144 |
+
self._window_size = window_size
|
| 145 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 146 |
+
|
| 147 |
+
self._writer = SummaryWriter(log_dir, **kwargs)
|
| 148 |
+
self._last_write = -1
|
| 149 |
+
|
| 150 |
+
def write(self):
|
| 151 |
+
storage = get_event_storage()
|
| 152 |
+
new_last_write = self._last_write
|
| 153 |
+
for k, (v, iter) in storage.latest_with_smoothing_hint(self._window_size).items():
|
| 154 |
+
if iter > self._last_write:
|
| 155 |
+
self._writer.add_scalar(k, v, iter)
|
| 156 |
+
new_last_write = max(new_last_write, iter)
|
| 157 |
+
self._last_write = new_last_write
|
| 158 |
+
|
| 159 |
+
# storage.put_{image,histogram} is only meant to be used by
|
| 160 |
+
# tensorboard writer. So we access its internal fields directly from here.
|
| 161 |
+
if len(storage._vis_data) >= 1:
|
| 162 |
+
for img_name, img, step_num in storage._vis_data:
|
| 163 |
+
self._writer.add_image(img_name, img, step_num)
|
| 164 |
+
# Storage stores all image data and rely on this writer to clear them.
|
| 165 |
+
# As a result it assumes only one writer will use its image data.
|
| 166 |
+
# An alternative design is to let storage store limited recent
|
| 167 |
+
# data (e.g. only the most recent image) that all writers can access.
|
| 168 |
+
# In that case a writer may not see all image data if its period is long.
|
| 169 |
+
storage.clear_images()
|
| 170 |
+
|
| 171 |
+
if len(storage._histograms) >= 1:
|
| 172 |
+
for params in storage._histograms:
|
| 173 |
+
self._writer.add_histogram_raw(**params)
|
| 174 |
+
storage.clear_histograms()
|
| 175 |
+
|
| 176 |
+
def close(self):
|
| 177 |
+
if hasattr(self, "_writer"): # doesn't exist when the code fails at import
|
| 178 |
+
self._writer.close()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class CommonMetricPrinter(EventWriter):
|
| 182 |
+
"""
|
| 183 |
+
Print **common** metrics to the terminal, including
|
| 184 |
+
iteration time, ETA, memory, all losses, and the learning rate.
|
| 185 |
+
It also applies smoothing using a window of 20 elements.
|
| 186 |
+
|
| 187 |
+
It's meant to print common metrics in common ways.
|
| 188 |
+
To print something in more customized ways, please implement a similar printer by yourself.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
def __init__(self, max_iter: Optional[int] = None, window_size: int = 20):
|
| 192 |
+
"""
|
| 193 |
+
Args:
|
| 194 |
+
max_iter: the maximum number of iterations to train.
|
| 195 |
+
Used to compute ETA. If not given, ETA will not be printed.
|
| 196 |
+
window_size (int): the losses will be median-smoothed by this window size
|
| 197 |
+
"""
|
| 198 |
+
self.logger = logging.getLogger(__name__)
|
| 199 |
+
self._max_iter = max_iter
|
| 200 |
+
self._window_size = window_size
|
| 201 |
+
self._last_write = None # (step, time) of last call to write(). Used to compute ETA
|
| 202 |
+
|
| 203 |
+
def _get_eta(self, storage) -> Optional[str]:
|
| 204 |
+
if self._max_iter is None:
|
| 205 |
+
return ""
|
| 206 |
+
iteration = storage.iter
|
| 207 |
+
try:
|
| 208 |
+
eta_seconds = storage.history("time").median(1000) * (self._max_iter - iteration - 1)
|
| 209 |
+
storage.put_scalar("eta_seconds", eta_seconds, smoothing_hint=False)
|
| 210 |
+
return str(datetime.timedelta(seconds=int(eta_seconds)))
|
| 211 |
+
except KeyError:
|
| 212 |
+
# estimate eta on our own - more noisy
|
| 213 |
+
eta_string = None
|
| 214 |
+
if self._last_write is not None:
|
| 215 |
+
estimate_iter_time = (time.perf_counter() - self._last_write[1]) / (
|
| 216 |
+
iteration - self._last_write[0]
|
| 217 |
+
)
|
| 218 |
+
eta_seconds = estimate_iter_time * (self._max_iter - iteration - 1)
|
| 219 |
+
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
| 220 |
+
self._last_write = (iteration, time.perf_counter())
|
| 221 |
+
return eta_string
|
| 222 |
+
|
| 223 |
+
def write(self):
|
| 224 |
+
storage = get_event_storage()
|
| 225 |
+
iteration = storage.iter
|
| 226 |
+
if iteration == self._max_iter:
|
| 227 |
+
# This hook only reports training progress (loss, ETA, etc) but not other data,
|
| 228 |
+
# therefore do not write anything after training succeeds, even if this method
|
| 229 |
+
# is called.
|
| 230 |
+
return
|
| 231 |
+
|
| 232 |
+
try:
|
| 233 |
+
avg_data_time = storage.history("data_time").avg(
|
| 234 |
+
storage.count_samples("data_time", self._window_size)
|
| 235 |
+
)
|
| 236 |
+
last_data_time = storage.history("data_time").latest()
|
| 237 |
+
except KeyError:
|
| 238 |
+
# they may not exist in the first few iterations (due to warmup)
|
| 239 |
+
# or when SimpleTrainer is not used
|
| 240 |
+
avg_data_time = None
|
| 241 |
+
last_data_time = None
|
| 242 |
+
try:
|
| 243 |
+
avg_iter_time = storage.history("time").global_avg()
|
| 244 |
+
last_iter_time = storage.history("time").latest()
|
| 245 |
+
except KeyError:
|
| 246 |
+
avg_iter_time = None
|
| 247 |
+
last_iter_time = None
|
| 248 |
+
try:
|
| 249 |
+
lr = "{:.5g}".format(storage.history("lr").latest())
|
| 250 |
+
except KeyError:
|
| 251 |
+
lr = "N/A"
|
| 252 |
+
|
| 253 |
+
eta_string = self._get_eta(storage)
|
| 254 |
+
|
| 255 |
+
if torch.cuda.is_available():
|
| 256 |
+
max_mem_mb = torch.cuda.max_memory_allocated() / 1024.0 / 1024.0
|
| 257 |
+
else:
|
| 258 |
+
max_mem_mb = None
|
| 259 |
+
|
| 260 |
+
# NOTE: max_mem is parsed by grep in "dev/parse_results.sh"
|
| 261 |
+
self.logger.info(
|
| 262 |
+
str.format(
|
| 263 |
+
" {eta}iter: {iter} {losses} {non_losses} {avg_time}{last_time}"
|
| 264 |
+
+ "{avg_data_time}{last_data_time} lr: {lr} {memory}",
|
| 265 |
+
eta=f"eta: {eta_string} " if eta_string else "",
|
| 266 |
+
iter=iteration,
|
| 267 |
+
losses=" ".join(
|
| 268 |
+
[
|
| 269 |
+
"{}: {:.4g}".format(
|
| 270 |
+
k, v.median(storage.count_samples(k, self._window_size))
|
| 271 |
+
)
|
| 272 |
+
for k, v in storage.histories().items()
|
| 273 |
+
if "loss" in k
|
| 274 |
+
]
|
| 275 |
+
),
|
| 276 |
+
non_losses=" ".join(
|
| 277 |
+
[
|
| 278 |
+
"{}: {:.4g}".format(
|
| 279 |
+
k, v.median(storage.count_samples(k, self._window_size))
|
| 280 |
+
)
|
| 281 |
+
for k, v in storage.histories().items()
|
| 282 |
+
if "[metric]" in k
|
| 283 |
+
]
|
| 284 |
+
),
|
| 285 |
+
avg_time="time: {:.4f} ".format(avg_iter_time)
|
| 286 |
+
if avg_iter_time is not None
|
| 287 |
+
else "",
|
| 288 |
+
last_time="last_time: {:.4f} ".format(last_iter_time)
|
| 289 |
+
if last_iter_time is not None
|
| 290 |
+
else "",
|
| 291 |
+
avg_data_time="data_time: {:.4f} ".format(avg_data_time)
|
| 292 |
+
if avg_data_time is not None
|
| 293 |
+
else "",
|
| 294 |
+
last_data_time="last_data_time: {:.4f} ".format(last_data_time)
|
| 295 |
+
if last_data_time is not None
|
| 296 |
+
else "",
|
| 297 |
+
lr=lr,
|
| 298 |
+
memory="max_mem: {:.0f}M".format(max_mem_mb) if max_mem_mb is not None else "",
|
| 299 |
+
)
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class EventStorage:
|
| 304 |
+
"""
|
| 305 |
+
The user-facing class that provides metric storage functionalities.
|
| 306 |
+
|
| 307 |
+
In the future we may add support for storing / logging other types of data if needed.
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __init__(self, start_iter=0):
|
| 311 |
+
"""
|
| 312 |
+
Args:
|
| 313 |
+
start_iter (int): the iteration number to start with
|
| 314 |
+
"""
|
| 315 |
+
self._history = defaultdict(HistoryBuffer)
|
| 316 |
+
self._smoothing_hints = {}
|
| 317 |
+
self._latest_scalars = {}
|
| 318 |
+
self._iter = start_iter
|
| 319 |
+
self._current_prefix = ""
|
| 320 |
+
self._vis_data = []
|
| 321 |
+
self._histograms = []
|
| 322 |
+
|
| 323 |
+
def put_image(self, img_name, img_tensor):
|
| 324 |
+
"""
|
| 325 |
+
Add an `img_tensor` associated with `img_name`, to be shown on
|
| 326 |
+
tensorboard.
|
| 327 |
+
|
| 328 |
+
Args:
|
| 329 |
+
img_name (str): The name of the image to put into tensorboard.
|
| 330 |
+
img_tensor (torch.Tensor or numpy.array): An `uint8` or `float`
|
| 331 |
+
Tensor of shape `[channel, height, width]` where `channel` is
|
| 332 |
+
3. The image format should be RGB. The elements in img_tensor
|
| 333 |
+
can either have values in [0, 1] (float32) or [0, 255] (uint8).
|
| 334 |
+
The `img_tensor` will be visualized in tensorboard.
|
| 335 |
+
"""
|
| 336 |
+
self._vis_data.append((img_name, img_tensor, self._iter))
|
| 337 |
+
|
| 338 |
+
def put_scalar(self, name, value, smoothing_hint=True):
|
| 339 |
+
"""
|
| 340 |
+
Add a scalar `value` to the `HistoryBuffer` associated with `name`.
|
| 341 |
+
|
| 342 |
+
Args:
|
| 343 |
+
smoothing_hint (bool): a 'hint' on whether this scalar is noisy and should be
|
| 344 |
+
smoothed when logged. The hint will be accessible through
|
| 345 |
+
:meth:`EventStorage.smoothing_hints`. A writer may ignore the hint
|
| 346 |
+
and apply custom smoothing rule.
|
| 347 |
+
|
| 348 |
+
It defaults to True because most scalars we save need to be smoothed to
|
| 349 |
+
provide any useful signal.
|
| 350 |
+
"""
|
| 351 |
+
name = self._current_prefix + name
|
| 352 |
+
history = self._history[name]
|
| 353 |
+
value = float(value)
|
| 354 |
+
history.update(value, self._iter)
|
| 355 |
+
self._latest_scalars[name] = (value, self._iter)
|
| 356 |
+
|
| 357 |
+
existing_hint = self._smoothing_hints.get(name)
|
| 358 |
+
if existing_hint is not None:
|
| 359 |
+
assert (
|
| 360 |
+
existing_hint == smoothing_hint
|
| 361 |
+
), "Scalar {} was put with a different smoothing_hint!".format(name)
|
| 362 |
+
else:
|
| 363 |
+
self._smoothing_hints[name] = smoothing_hint
|
| 364 |
+
|
| 365 |
+
def put_scalars(self, *, smoothing_hint=True, **kwargs):
|
| 366 |
+
"""
|
| 367 |
+
Put multiple scalars from keyword arguments.
|
| 368 |
+
|
| 369 |
+
Examples:
|
| 370 |
+
|
| 371 |
+
storage.put_scalars(loss=my_loss, accuracy=my_accuracy, smoothing_hint=True)
|
| 372 |
+
"""
|
| 373 |
+
for k, v in kwargs.items():
|
| 374 |
+
self.put_scalar(k, v, smoothing_hint=smoothing_hint)
|
| 375 |
+
|
| 376 |
+
def put_histogram(self, hist_name, hist_tensor, bins=1000):
|
| 377 |
+
"""
|
| 378 |
+
Create a histogram from a tensor.
|
| 379 |
+
|
| 380 |
+
Args:
|
| 381 |
+
hist_name (str): The name of the histogram to put into tensorboard.
|
| 382 |
+
hist_tensor (torch.Tensor): A Tensor of arbitrary shape to be converted
|
| 383 |
+
into a histogram.
|
| 384 |
+
bins (int): Number of histogram bins.
|
| 385 |
+
"""
|
| 386 |
+
ht_min, ht_max = hist_tensor.min().item(), hist_tensor.max().item()
|
| 387 |
+
|
| 388 |
+
# Create a histogram with PyTorch
|
| 389 |
+
hist_counts = torch.histc(hist_tensor, bins=bins)
|
| 390 |
+
hist_edges = torch.linspace(start=ht_min, end=ht_max, steps=bins + 1, dtype=torch.float32)
|
| 391 |
+
|
| 392 |
+
# Parameter for the add_histogram_raw function of SummaryWriter
|
| 393 |
+
hist_params = dict(
|
| 394 |
+
tag=hist_name,
|
| 395 |
+
min=ht_min,
|
| 396 |
+
max=ht_max,
|
| 397 |
+
num=len(hist_tensor),
|
| 398 |
+
sum=float(hist_tensor.sum()),
|
| 399 |
+
sum_squares=float(torch.sum(hist_tensor**2)),
|
| 400 |
+
bucket_limits=hist_edges[1:].tolist(),
|
| 401 |
+
bucket_counts=hist_counts.tolist(),
|
| 402 |
+
global_step=self._iter,
|
| 403 |
+
)
|
| 404 |
+
self._histograms.append(hist_params)
|
| 405 |
+
|
| 406 |
+
def history(self, name):
|
| 407 |
+
"""
|
| 408 |
+
Returns:
|
| 409 |
+
HistoryBuffer: the scalar history for name
|
| 410 |
+
"""
|
| 411 |
+
ret = self._history.get(name, None)
|
| 412 |
+
if ret is None:
|
| 413 |
+
raise KeyError("No history metric available for {}!".format(name))
|
| 414 |
+
return ret
|
| 415 |
+
|
| 416 |
+
def histories(self):
|
| 417 |
+
"""
|
| 418 |
+
Returns:
|
| 419 |
+
dict[name -> HistoryBuffer]: the HistoryBuffer for all scalars
|
| 420 |
+
"""
|
| 421 |
+
return self._history
|
| 422 |
+
|
| 423 |
+
def latest(self):
|
| 424 |
+
"""
|
| 425 |
+
Returns:
|
| 426 |
+
dict[str -> (float, int)]: mapping from the name of each scalar to the most
|
| 427 |
+
recent value and the iteration number its added.
|
| 428 |
+
"""
|
| 429 |
+
return self._latest_scalars
|
| 430 |
+
|
| 431 |
+
def latest_with_smoothing_hint(self, window_size=20):
|
| 432 |
+
"""
|
| 433 |
+
Similar to :meth:`latest`, but the returned values
|
| 434 |
+
are either the un-smoothed original latest value,
|
| 435 |
+
or a median of the given window_size,
|
| 436 |
+
depend on whether the smoothing_hint is True.
|
| 437 |
+
|
| 438 |
+
This provides a default behavior that other writers can use.
|
| 439 |
+
|
| 440 |
+
Note: All scalars saved in the past `window_size` iterations are used for smoothing.
|
| 441 |
+
This is different from the `window_size` definition in HistoryBuffer.
|
| 442 |
+
Use :meth:`get_history_window_size` to get the `window_size` used in HistoryBuffer.
|
| 443 |
+
"""
|
| 444 |
+
result = {}
|
| 445 |
+
for k, (v, itr) in self._latest_scalars.items():
|
| 446 |
+
result[k] = (
|
| 447 |
+
self._history[k].median(self.count_samples(k, window_size))
|
| 448 |
+
if self._smoothing_hints[k]
|
| 449 |
+
else v,
|
| 450 |
+
itr,
|
| 451 |
+
)
|
| 452 |
+
return result
|
| 453 |
+
|
| 454 |
+
def count_samples(self, name, window_size=20):
|
| 455 |
+
"""
|
| 456 |
+
Return the number of samples logged in the past `window_size` iterations.
|
| 457 |
+
"""
|
| 458 |
+
samples = 0
|
| 459 |
+
data = self._history[name].values()
|
| 460 |
+
for _, iter_ in reversed(data):
|
| 461 |
+
if iter_ > data[-1][1] - window_size:
|
| 462 |
+
samples += 1
|
| 463 |
+
else:
|
| 464 |
+
break
|
| 465 |
+
return samples
|
| 466 |
+
|
| 467 |
+
def smoothing_hints(self):
|
| 468 |
+
"""
|
| 469 |
+
Returns:
|
| 470 |
+
dict[name -> bool]: the user-provided hint on whether the scalar
|
| 471 |
+
is noisy and needs smoothing.
|
| 472 |
+
"""
|
| 473 |
+
return self._smoothing_hints
|
| 474 |
+
|
| 475 |
+
def step(self):
|
| 476 |
+
"""
|
| 477 |
+
User should either: (1) Call this function to increment storage.iter when needed. Or
|
| 478 |
+
(2) Set `storage.iter` to the correct iteration number before each iteration.
|
| 479 |
+
|
| 480 |
+
The storage will then be able to associate the new data with an iteration number.
|
| 481 |
+
"""
|
| 482 |
+
self._iter += 1
|
| 483 |
+
|
| 484 |
+
@property
|
| 485 |
+
def iter(self):
|
| 486 |
+
"""
|
| 487 |
+
Returns:
|
| 488 |
+
int: The current iteration number. When used together with a trainer,
|
| 489 |
+
this is ensured to be the same as trainer.iter.
|
| 490 |
+
"""
|
| 491 |
+
return self._iter
|
| 492 |
+
|
| 493 |
+
@iter.setter
|
| 494 |
+
def iter(self, val):
|
| 495 |
+
self._iter = int(val)
|
| 496 |
+
|
| 497 |
+
@property
|
| 498 |
+
def iteration(self):
|
| 499 |
+
# for backward compatibility
|
| 500 |
+
return self._iter
|
| 501 |
+
|
| 502 |
+
def __enter__(self):
|
| 503 |
+
_CURRENT_STORAGE_STACK.append(self)
|
| 504 |
+
return self
|
| 505 |
+
|
| 506 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 507 |
+
assert _CURRENT_STORAGE_STACK[-1] == self
|
| 508 |
+
_CURRENT_STORAGE_STACK.pop()
|
| 509 |
+
|
| 510 |
+
@contextmanager
|
| 511 |
+
def name_scope(self, name):
|
| 512 |
+
"""
|
| 513 |
+
Yields:
|
| 514 |
+
A context within which all the events added to this storage
|
| 515 |
+
will be prefixed by the name scope.
|
| 516 |
+
"""
|
| 517 |
+
old_prefix = self._current_prefix
|
| 518 |
+
self._current_prefix = name.rstrip("/") + "/"
|
| 519 |
+
yield
|
| 520 |
+
self._current_prefix = old_prefix
|
| 521 |
+
|
| 522 |
+
def clear_images(self):
|
| 523 |
+
"""
|
| 524 |
+
Delete all the stored images for visualization. This should be called
|
| 525 |
+
after images are written to tensorboard.
|
| 526 |
+
"""
|
| 527 |
+
self._vis_data = []
|
| 528 |
+
|
| 529 |
+
def clear_histograms(self):
|
| 530 |
+
"""
|
| 531 |
+
Delete all the stored histograms for visualization.
|
| 532 |
+
This should be called after histograms are written to tensorboard.
|
| 533 |
+
"""
|
| 534 |
+
self._histograms = []
|
RAVE-main/annotator/oneformer/detectron2/utils/file_io.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
from iopath.common.file_io import HTTPURLHandler, OneDrivePathHandler, PathHandler
|
| 3 |
+
from iopath.common.file_io import PathManager as PathManagerBase
|
| 4 |
+
|
| 5 |
+
__all__ = ["PathManager", "PathHandler"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
PathManager = PathManagerBase()
|
| 9 |
+
"""
|
| 10 |
+
This is a detectron2 project-specific PathManager.
|
| 11 |
+
We try to stay away from global PathManager in fvcore as it
|
| 12 |
+
introduces potential conflicts among other libraries.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Detectron2Handler(PathHandler):
|
| 17 |
+
"""
|
| 18 |
+
Resolve anything that's hosted under detectron2's namespace.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
PREFIX = "detectron2://"
|
| 22 |
+
S3_DETECTRON2_PREFIX = "https://dl.fbaipublicfiles.com/detectron2/"
|
| 23 |
+
|
| 24 |
+
def _get_supported_prefixes(self):
|
| 25 |
+
return [self.PREFIX]
|
| 26 |
+
|
| 27 |
+
def _get_local_path(self, path, **kwargs):
|
| 28 |
+
name = path[len(self.PREFIX) :]
|
| 29 |
+
return PathManager.get_local_path(self.S3_DETECTRON2_PREFIX + name, **kwargs)
|
| 30 |
+
|
| 31 |
+
def _open(self, path, mode="r", **kwargs):
|
| 32 |
+
return PathManager.open(
|
| 33 |
+
self.S3_DETECTRON2_PREFIX + path[len(self.PREFIX) :], mode, **kwargs
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
PathManager.register_handler(HTTPURLHandler())
|
| 38 |
+
PathManager.register_handler(OneDrivePathHandler())
|
| 39 |
+
PathManager.register_handler(Detectron2Handler())
|