Skip to content

Commit 36ad4dc

Browse files
committed
Enhance ONNX export and inference capabilities with output class filtering
- Added `output_classes` configuration to allow post-NMS class filtering in `production` settings, enabling users to specify which classes to keep after inference. - Updated relevant functions and documentation to support the new output class feature, ensuring excluded classes still compete during NMS. - Enhanced `README.md` and `config.schema.json` to reflect the new `output_classes` functionality and its usage. - Improved test coverage for output class filtering to validate behavior during inference and ONNX export. This update aims to provide more flexibility in managing class outputs.
1 parent 0d2bb01 commit 36ad4dc

29 files changed

Lines changed: 399 additions & 15 deletions

‎configs/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ All options, types, and defaults: **[config.schema.json](config.schema.json)** (
133133
| `model` | backbone, fpn_*, anchor_*, target_means/stds, roi_* (loss, batch, iou, schedule, **roi_proj_xy**), rpn_*, use_hbb_for_matching, add_gt_as_proposals, **rpn_nms_threshold** (proposal NMS), **final_nms_iou_threshold** / **final_nms_iou_schedule_*** (post–ROI-head NMS), **final_nms_use_cpu** (exact polygon final NMS on CPU), nms_class_agnostic, max_detections_per_image, inference_pre_nms_score_threshold |
134134
| `training` | **lr_scheduler_type** first, then lr_scheduler_*, lr_warmup_steps, lr_scaling_*, use_lr_param_groups, lr_mult_*, then num_epochs, learning_rate, momentum, weight_decay, use_amp, gradient_accumulation_steps, max_grad_norm, loss_weights. See [Training — Learning rate scheduling](../docs/user-guide/training.md#learning-rate-scheduling) and [_base_/schedules/README.md](_base_/schedules/README.md). |
135135
| `evaluation` | **`val_score_threshold`** (periodic val / `make eval-val` / `best_mAP`), **`test_score_threshold`** for **`test_map` / `make eval-test`** (null → **0.05**), iou_threshold, compute_map_*; **`final_nms_iou_threshold`** for eval-val NMS only (DOTA+HRSC: **0.1**, MMRotate test parity) |
136-
| `production` | Optional **deploy / `image_demo`** overrides: `score_threshold` via `resolve_inference_score_threshold` (does **not** override train-val mAP; `odet preds` ignores it). DOTA 1× recipes set this to eval-val global F1 − **0.05** (Oriented R-CNN **0.55**, Faster R-CNN **0.6**, RetinaNet OBB **0.25** / HBB **0.35**, FCOS **0.2**); 3× inherits those floors. HRSC 1× recipes do the same (Oriented R-CNN / Faster R-CNN **0.85**, FCOS **0.2**). `per_class_score_threshold` merges on top of `evaluation` for preds/deploy only (`merge_per_class_score_thresholds`; mAP IoU is `evaluation.iou_threshold` only). **Decode (deploy / `image_demo`)** — RPN/NMS/threshold fields patch the loaded model via `apply_inference_config_to_model` (DOTA+HRSC+FAIR1M: final NMS **0.1**). **`odet preds`** prefers `evaluation.final_nms_iou_threshold` when set. Not applied during `tools/train.py` (training uses `model.*`, final NMS **0.1**). **Deploy / tiling** — `overlap_pixels`, `ignore_margin_pixels`, canvas flags (see **config.schema.json**). |
136+
| `production` | Optional **deploy / `image_demo`** overrides: `score_threshold` via `resolve_inference_score_threshold` (does **not** override train-val mAP; `odet preds` ignores it). DOTA 1× recipes set this to eval-val global F1 − **0.05** (Oriented R-CNN **0.55**, Faster R-CNN **0.6**, RetinaNet OBB **0.25** / HBB **0.35**, FCOS **0.2**); 3× inherits those floors. HRSC 1× recipes do the same (Oriented R-CNN / Faster R-CNN **0.85**, FCOS **0.2**). `per_class_score_threshold` merges on top of `evaluation` for preds/deploy only (`merge_per_class_score_thresholds`; mAP IoU is `evaluation.iou_threshold` only). **`output_classes`**: post-NMS allowlist for preds / image_demo / deploy / ONNX export (excluded classes still compete in NMS). **Decode (deploy / `image_demo`)** — RPN/NMS/threshold fields patch the loaded model via `apply_inference_config_to_model` (DOTA+HRSC+FAIR1M: final NMS **0.1**). **`odet preds`** prefers `evaluation.final_nms_iou_threshold` when set. Not applied during `tools/train.py` (training uses `model.*`, final NMS **0.1**). **Deploy / tiling** — `overlap_pixels`, `ignore_margin_pixels`, canvas flags (see **config.schema.json**). |
137137
| `checkpoint` | load_from_checkpoint, load_from_experiment, **discover_previous_run**, resume_from_checkpoint_epoch, load_optimizer_state, load_scheduler_state, load_include_prefixes, load_exclude_prefixes, start_epoch, best_metric, higher_is_better |
138138
| `loss` | loss_type (`focal_weighted` now also scales FCOS/RetinaNet sigmoid focal per class; `background_weight` is ROI-only), class_weight_method, background_weight, focal_alpha, focal_gamma, label_smoothing, **roi_grouped_ce_*** (coarse-to-fine ROI classifier curriculum in one run) |
139139
| `preprocessing` | resize_mode, target_size, window_size, normalize_mean, normalize_std, pad_size_divisor, enable_flip_horizontal, enable_flip_vertical, enable_flip_diagonal, enable_random_rotate, random_rotate_prob, random_rotate_angle_range |

‎configs/config.schema.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,11 @@
427427
"additionalProperties": { "type": "number" },
428428
"description": "Per-class floors for preds/deploy only (merge_per_class_score_thresholds: evaluation then production). Does not affect train-val mAP."
429429
},
430+
"output_classes": {
431+
"type": ["array", "null"],
432+
"items": { "type": "string" },
433+
"description": "Post-NMS class allowlist for odet preds, image_demo, deploy/Docker, and ONNX export (case-insensitive). Null = keep all. Prefer this over impossible score floors (e.g. 1.1) when hiding classes for a client — excluded classes still compete in NMS."
434+
},
430435
"final_nms_iou_threshold": { "type": ["number", "null"], "default": null, "description": "Deploy / image_demo final detection NMS IoU; when set, patches the live model after checkpoint load. odet preds / make eval-val use evaluation.final_nms_iou_threshold when that field is set." },
431436
"final_nms_use_cpu": { "type": ["boolean", "null"], "default": null, "description": "When set, patches model.final_nms_use_cpu (exact polygon NMS on CPU)." },
432437
"inference_pre_nms_score_threshold": { "type": ["number", "null"], "default": null, "description": "Decoder pre-NMS score floor; when set, patches model.inference_pre_nms_score_threshold (or RetinaNet score_threshold)." },

‎deploy/example/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,4 @@ curl -fsS http://127.0.0.1:8080/api/v1/health # OK
5050

5151
`POST /api/v1/process` body: `{"resolution": <meters per pixel>, "tiles": [<base64 JPEG or PNG>]}`. Response: GeoJSON FeatureCollection (category, confidence, length/width in meters). One request at a time (HTTP 429 if busy).
5252

53-
Inference knobs come from `config.production.*` (score floor, NMS, sliding-window overlap, canvas flags). DOTA Hub Oriented R-CNN 1× uses score 0.55 and NMS 0.1.
53+
Inference knobs come from `config.production.*` (score floor, NMS, sliding-window overlap, canvas flags, optional `output_classes` post-NMS allowlist). DOTA Hub Oriented R-CNN 1× uses score 0.55 and NMS 0.1.

‎deploy/example/app/inference.py‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,14 @@
2727
get_preprocessing_params,
2828
resolve_inference_score_threshold,
2929
resolve_inference_sliding_window_overlap_pixels,
30+
resolve_output_classes,
31+
)
32+
from oriented_det.runtime.inference import (
33+
apply_nms_to_detections,
34+
filter_detections_by_output_classes,
35+
get_model_size,
36+
run_inference_auto,
3037
)
31-
from oriented_det.runtime.inference import apply_nms_to_detections, get_model_size, run_inference_auto
3238
from oriented_det.runtime.checkpoint import load_model_from_checkpoint
3339

3440

@@ -125,6 +131,7 @@ def __init__(
125131
self._preprocessing = None
126132
self._device_str = "cuda:0" if torch.cuda.is_available() else "cpu"
127133
self._score_threshold = 0.5
134+
self._output_classes = None
128135
self._per_class_threshold: dict | None = None
129136
self._nms_threshold = 0.5
130137
self._overlap_pixels: int = 200
@@ -246,6 +253,7 @@ def _load_model(self, image_height: int | None = None, image_width: int | None =
246253

247254
self._score_threshold = resolve_inference_score_threshold(cfg)
248255
self._per_class_threshold = self._merge_per_class_score_thresholds(cfg)
256+
self._output_classes = resolve_output_classes(cfg)
249257

250258
if hasattr(self._model, "final_nms_iou_threshold"):
251259
self._nms_threshold = float(self._model.final_nms_iou_threshold)
@@ -275,7 +283,8 @@ def _load_model(self, image_height: int | None = None, image_width: int | None =
275283
f"Inference thresholds: score={self._score_threshold}, "
276284
f"nms={self._nms_threshold} (from loaded model after production.* decode patch), "
277285
f"per_class={self._per_class_threshold} "
278-
"(evaluation → production; class names match case-insensitively)"
286+
"(evaluation → production; class names match case-insensitively), "
287+
f"output_classes={self._output_classes!r}"
279288
)
280289
logger.info(
281290
"Deploy edge margin: dataset.overlap=%s px, ignore_margin_pixels=%s px (centroid filter; "
@@ -361,6 +370,10 @@ def predict_single(self, image: np.ndarray, resolution: float):
361370
window_margin_pixels=0.0,
362371
)
363372
detections = apply_nms_to_detections(detections, iou_threshold=self._nms_threshold)
373+
# After merge NMS so excluded classes still compete there.
374+
detections = filter_detections_by_output_classes(
375+
detections, self._output_classes, self._class_names
376+
)
364377

365378
before = len(detections)
366379
detections = _filter_detections_by_image_margin(

‎export/PARITY.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ The delivered graph is **ONNX pre-NMS** (`rotated_fcos_pre_nms` for FCOS). Prepr
1010
| Backbone + FCOS head + DistanceAnglePointCoder decode | Same weights/logic as `RotatedFCOS` eval via `rotated_fcos_decode_pre_nms` (includes GroupNorm). |
1111
| Per-level pre-NMS cap | Always `topk(min(nms_pre, H×W))` then score / size / finite filters. Invalid top-k rows are zeroed (`score=0`, `w=h=0`) and left in the padded tensor. |
1212
| Pre-NMS output padding | `pad_pre_nms_detections`. Default `P = nms_pre ×` FPN levels. |
13-
| Final NMS / score floors | `export.postprocess.finalize_detections_numpy` calling `export.nms` (numpy clip, or Shapely if `nms_backend=shapely`). Production `score_threshold` applied **before** NMS. Class-aware vs class-agnostic follows resolved `nms_class_agnostic` (`production` override, else `model`; export unset default is class-agnostic). Small float drift vs Shapely is possible on the `python` backend. |
13+
| Final NMS / score floors | `export.postprocess.finalize_detections_numpy` calling `export.nms` (numpy clip, or Shapely if `nms_backend=shapely`). Production `score_threshold` applied **before** NMS. Optional `production.output_classes` allowlist runs **after** NMS. Class-aware vs class-agnostic follows resolved `nms_class_agnostic` (`production` override, else `model`; export unset default is class-agnostic). Small float drift vs Shapely is possible on the `python` backend. |
1414
| Sliding-window tiling | `detect_image` tiles `fixed` / `crop` images larger than `window_size` (else `target_size`). Same edge-flush grid and `target_size / window_size` box scale as `run_inference_sliding_window`. Overlap default 200 px. Per-window NMS, then a second NMS across windows. Interior overlap margin stays 0. `pad` / `keep_ratio` are a single resize. |
1515
| GeoJSON | Out of scope — PyTorch deploy path. |
1616

‎export/README.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ python -m export demo
1010
python -m export infer --onnx ./onnx_export/model.onnx --images ./tiles --output ./onnx_export/predictions
1111
```
1212

13-
Exporting a new graph from a checkpoint still needs oriented-det. From the repo root:
13+
Exporting a new graph from a checkpoint still needs oriented-det (and `onnx` / `onnxruntime` / `onnxscript` via `.[export]`). Producer export uses the TorchScript ONNX path (`dynamo=False`). From the repo root:
1414

1515
```bash
1616
uv pip install -e ".[export]"
@@ -97,6 +97,18 @@ Rotated NMS runs in Python after the ONNX graph (`export/nms.py`). Both modes ar
9797

9898
At export: `production.nms_class_agnostic` when set, else `model.nms_class_agnostic`, else **class-agnostic**. Re-export after changing the config so the sidecar picks it up. `odet export preds` also overlays the experiment config onto the loaded meta.
9999

100+
## Output class allowlist (post-NMS)
101+
102+
To hide classes for a client without score-floor hacks, set `production.output_classes`. The same field is honored by **PyTorch** (`odet preds`, `image_demo`, deploy/Docker) and **ONNX export** (sidecar / `odet export preds`). After score floors + NMS, only listed names are kept (case-insensitive). Excluded classes still compete in NMS, so a strong aircraft box can suppress a weaker overlapping drone before aircraft is dropped from the output.
103+
104+
```json
105+
"production": {
106+
"output_classes": ["drone", "shahed"]
107+
}
108+
```
109+
110+
`null` / omitted keeps every class. Prefer this over `per_class_score_threshold` values like `1.1`.
111+
100112
## Inference score overrides
101113

102114
The graph is pre-NMS only. It bakes `pre_nms_score_threshold` (0.05 on the current RTMDet export) and has no threshold input. Scores below that floor are already gone; a caller cannot recover them.

‎export/postprocess.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,58 @@ def _score_keep_mask(
110110
return keep
111111

112112

113+
def _normalize_output_classes(
114+
output_classes: Optional[List[str]],
115+
) -> Optional[List[str]]:
116+
"""Return stripped class names, or None when the allowlist is unset."""
117+
if output_classes is None:
118+
return None
119+
return [str(c).strip() for c in output_classes if str(c).strip()]
120+
121+
122+
def _allowed_label_ids(
123+
output_classes: Optional[List[str]],
124+
class_id_to_name: Dict[int, str],
125+
) -> Optional[set]:
126+
"""1-based label ids to keep after NMS, or None to keep all.
127+
128+
Names match ``class_id_to_name`` case-insensitively. Digit strings are label ids.
129+
An empty allowlist keeps nothing.
130+
"""
131+
names = _normalize_output_classes(output_classes)
132+
if names is None:
133+
return None
134+
if not names:
135+
return set()
136+
by_lower = {str(v).lower(): int(k) for k, v in class_id_to_name.items()}
137+
allowed: set = set()
138+
for raw in names:
139+
key = raw.lower()
140+
if key in by_lower:
141+
allowed.add(by_lower[key])
142+
elif raw.isdigit():
143+
allowed.add(int(raw))
144+
return allowed
145+
146+
147+
def _output_class_keep_mask(
148+
labels: np.ndarray,
149+
output_classes: Optional[List[str]],
150+
class_id_to_name: Dict[int, str],
151+
) -> np.ndarray:
152+
"""Boolean mask for the post-NMS class allowlist (None = keep all)."""
153+
n = int(labels.shape[0])
154+
allowed = _allowed_label_ids(output_classes, class_id_to_name)
155+
if allowed is None:
156+
return np.ones(n, dtype=bool)
157+
if n == 0:
158+
return np.zeros((0,), dtype=bool)
159+
keep = np.zeros(n, dtype=bool)
160+
for i in range(n):
161+
keep[i] = int(labels[i]) in allowed
162+
return keep
163+
164+
113165
def finalize_detections_numpy(
114166
pre_nms_boxes: np.ndarray,
115167
pre_nms_scores: np.ndarray,
@@ -125,13 +177,17 @@ def finalize_detections_numpy(
125177
class_id_to_name: Dict[Union[int, str], str],
126178
max_output_slots: int,
127179
nms_backend: str = "python",
180+
output_classes: Optional[List[str]] = None,
128181
) -> Tuple[np.ndarray, int]:
129182
"""Run rotated NMS + production score filter; return padded ``[max_output_slots, 7]``.
130183
131184
Candidates below the production score floor are dropped **before** NMS. For greedy
132185
score-ordered NMS this matches filtering after NMS, and avoids O(n²) NMS on
133186
thousands of sub-threshold boxes.
134187
188+
``output_classes``, when set, keeps only those labels **after** NMS so excluded
189+
classes still suppress overlapping boxes (prefer this over score floors like 1.1).
190+
135191
``final_nms_use_cpu`` is accepted for meta compatibility; NMS is always CPU.
136192
``nms_backend`` is ``python`` (numpy clip), ``shapely``, or ``auto``.
137193
"""
@@ -183,6 +239,7 @@ def finalize_detections_numpy(
183239
)
184240
keep_mask &= boxes[:, 2] >= _MIN_BOX_SIZE
185241
keep_mask &= boxes[:, 3] >= _MIN_BOX_SIZE
242+
keep_mask &= _output_class_keep_mask(labels, output_classes, class_id_to_name_i)
186243
boxes = boxes[keep_mask]
187244
scores = scores[keep_mask]
188245
labels = labels[keep_mask]
@@ -317,6 +374,11 @@ def meta_to_finalize_kwargs(meta: Dict[str, Any]) -> Dict[str, Any]:
317374
prod.get("score_threshold") or post.get("score_threshold") or 0.05
318375
),
319376
"per_class_score_threshold": prod.get("per_class_score_threshold"),
377+
"output_classes": _normalize_output_classes(
378+
prod.get("output_classes")
379+
if prod.get("output_classes") is not None
380+
else post.get("output_classes")
381+
),
320382
"class_id_to_name": build_class_id_to_name(class_names),
321383
"max_output_slots": max_det,
322384
"nms_backend": str(

‎export/requirements-export.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55

66
onnx>=1.14.0,<2
77
onnxruntime>=1.16.0
8+
onnxscript>=0.2.0 # required by torch.onnx.export (PyTorch 2.5+)

‎export/scripts/export_onnx.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,11 @@ def build_export_meta(
279279
"final_nms_use_cpu": bool(prod.get("final_nms_use_cpu", True)),
280280
"pre_nms_score_threshold": pre_nms_score,
281281
"nms_backend": str(prod.get("nms_backend") or "python"),
282+
"output_classes": (
283+
[str(c) for c in prod["output_classes"]]
284+
if prod.get("output_classes") is not None
285+
else None
286+
),
282287
},
283288
"normalize_mean": mean,
284289
"normalize_std": std,
@@ -396,6 +401,7 @@ def main() -> None:
396401
dynamic_axes=dynamic_axes,
397402
opset_version=int(args.opset),
398403
do_constant_folding=True,
404+
dynamo=False,
399405
)
400406

401407
meta = build_export_meta(

‎export/scripts/save_predictions_onnx.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,11 @@ def _inference_meta(
121121
post["nms_class_agnostic"] = nms_ag
122122
prod = dict(meta.get("production") or {})
123123
prod["nms_class_agnostic"] = nms_ag
124+
out_cls = getattr(getattr(config, "production", None), "output_classes", None)
125+
if out_cls is not None:
126+
out_cls_list = [str(c) for c in list(out_cls)]
127+
prod["output_classes"] = out_cls_list
128+
post["output_classes"] = out_cls_list
124129
out = dict(meta)
125130
out["preprocess"] = prep
126131
out["postprocess"] = post

0 commit comments

Comments
 (0)