Skip to content

postprocess= — Raw Output to Final Output

postprocess= declares the processing between the model's raw output and its final output.

If the model call already returns the final detections, you do not need it. Declare it — together with raw_output= — in either of these cases:

Case Why it is needed
The post-processing prunes candidates (an NMS, where only some candidates survive as final detections) So each final detection can be traced back to the candidate it came from
The post-processing lives outside the model (your own function turns the raw output into final detections after inference) Its internals are opaque to MLdebugger, so it needs the shape of what goes in (the raw output) and what comes out (the final output)

The second case applies equally to post-processing that restores coordinates, rescales, or reshapes irreversibly. Your code still runs as-is; MLdebugger only receives the shape at each end.

Not needed for classification

Classification has no candidate pruning, so postprocess= is not declared (declaring it raises at construction time). The classification equivalent — the activation (softmax / sigmoid) — is given on S.ClassConfs(activation=...).

A single stage only

postprocess= accepts exactly one of NMS / TopK / a custom function. For models needing multiple stages, contact support@adansons.ai.


Choosing a declaration

Pick one of four, based on the shape of your model's post-processing.

Your model's post-processing Declaration Section
(1) Returns the indices it kept (keep index) An S.KeepIndex() leaf keep index
(2) No keep index, but a generic NMS postprocess=NMS(...) NMS
(3) A custom post-processing / extraction function postprocess=<fn> custom function
(4) No NMS; takes the top-K scores (query head) postprocess=TopK(...) TopK

(1) Post-processing returns a keep index

If the indices of the kept candidates are part of the output, declare their location with an S.KeepIndex() leaf. That settles the mapping, so no postprocess= is needed.

Because the indices need something to point at, declare raw_output= together with it (declaring only one of the two raises at construction time).

from ml_debugger.spec import LabelSchema, LayerHook, ModelSpec, RawOutputSchema
from ml_debugger.spec import schema as S

spec = ModelSpec(
    labels=LabelSchema(n_class=3, ground_truth=gt),
    output=S.BatchAxis[
        S.Dict(
            boxes=S.DetAxis[S.Coords("xyxy", "pixel")],
            scores=S.DetAxis[S.Score("raw")],
            labels=S.DetAxis[S.LabelId(0)],
            keep_idx=S.DetAxis[S.KeepIndex()],           # row indices of the kept candidates
        )
    ],
    raw_output=RawOutputSchema(hook=LayerHook("cls_head")),
)

S.KeepIndex can be placed in two spots: the model's final output (output=) and the returns= of an InModelNMS.


(2) A generic NMS

If the post-processing is a generic NMS, declare postprocess=NMS(...). When the thresholds live in model attributes, declare those attribute paths as well.

from ml_debugger.spec import NMS

spec = ModelSpec(
    labels=LabelSchema(n_class=2, ground_truth=gt),
    output=S.BatchAxis[
        S.Dict(
            boxes=S.DetAxis[S.Coords("xyxy", "pixel")],
            scores=S.DetAxis[S.Score("raw")],
            labels=S.DetAxis[S.LabelId(1)],
            cls_logits=S.DetAxis[S.ClassConfs(2, "raw", "index0")],
        )
    ],
    postprocess=NMS(
        score_thresh_attr="roi_heads.score_thresh",
        iou_thresh_attr="roi_heads.nms_thresh",
        max_det_attr="roi_heads.detections_per_img",
    ),
)

NMS fields

Field Default Contents
score_thresh_attr None Model attribute path holding the score threshold
iou_thresh_attr None Model attribute path holding the IoU threshold
max_det_attr None Model attribute path holding the detection cap
score_thresh / iou_thresh / max_det None The threshold values themselves, for an NMS whose thresholds are not held by the model. A value and the matching *_attr path cannot both be declared
apply_func None For models whose thresholds are not reachable as attributes; called as apply_func(model, config)
custom None Where a non-standard NMS lives: an InModelNMS, or your own selection function
decode None Conversion from raw output into candidates (→ Decode)
min_box_edge_px None Minimum candidate box edge in pixels; smaller boxes are dropped before selection
prenms_topk_per_class None Per-class candidate cap (score-descending) applied before the NMS
clip_boxes_to_image True Clip candidate boxes into the image bounds before selection
nms_mode None (= "flatten") What one candidate may become. "flatten" = one row per candidate × class (models that score each class independently); "per_candidate" = one row per candidate at its strongest class (single-stage detectors)

If the thresholds are not readable/writable as attributes, declare the values directly (NMS(score_thresh=..., iou_thresh=...)), pass them as inference arguments (invoke=Invoke(kwargs=...)), or use apply_func.

How thresholds are resolved (v0.5.0)

Each threshold is resolved on its own, in this order: the Tracer / Logger / DataFilter argument > the value or *_attr path declared here > the value read from the model > the default. When none of these yields a threshold, a warning is shown when the Tracer / Logger / DataFilter is constructed — declare the value your inference code uses.

Reusing the model's own post-processing: InModelNMS

When the post-processing is a method inside the model, NMS(custom=InModelNMS(...)) declares that method and the shape of its return value, and the model's own post-processing is used as-is.

from ml_debugger.spec import InModelNMS, NMS

postprocess=NMS(custom=InModelNMS(
    method="roi_heads.postprocess_detections",   # path to the in-model method
    returns=S.Seq(                               # the shape of what it returns
        S.BatchAxis[S.DetAxis[S.Coords("xyxy", "pixel")]],
        S.BatchAxis[S.DetAxis[S.Score("raw")]],
        S.BatchAxis[S.DetAxis[S.LabelId(1)]],    # torchvision uses 1-based labels
    ),
))
InModelNMS field Default Contents
method (required) Path to the in-model method
returns (required) The structure of that method's return value
kwargs {} Fixed arguments passed to the method
decoder "box_coder.decode" Path to the box decoder
decode "batched" How the decoder is called
activation "softmax" Activation of the candidate scores

Well-known conventions can also be declared by template name. The template fills in the whole convention, and only the fields you state explicitly override it.

postprocess=NMS(custom=InModelNMS("torchvision_roi_heads"))
postprocess=NMS(custom=InModelNMS("torchvision_ssd_head"))

PyTorch only

custom=InModelNMS(...) is available for PyTorch models only. On TensorFlow / Keras it raises at construction time — switch to an S.KeepIndex leaf, NMS(decode=Decode(...)), or NMS(custom=<selection fn>).


(3) A custom post-processing / extraction function

If your post-processing is custom and no keep index is available, hand the logic over as a function. There are two ways to do that.

(3-a) You have a function that selects rows from the candidates

Pass it to postprocess=NMS(custom=<fn>). The signature is fn(candidates, config) -> row indices of the kept candidates.

def my_selection_fn(candidates, config):
    # candidates for a single image arrive in the SDK's standard view:
    #   candidates.boxes  : (N, 4) candidate boxes, pixel xyxy
    #   candidates.scores : (N,)   candidate scores
    #   candidates.labels : (N,)   integer class ids
    #   candidates.confs  : (N, C) per-class confidences (None when not declared)
    #   candidates.raw    : the hooked raw output as-is (None when not declared)
    # config carries score_thresh / iou_thresh / max_detections_per_image.
    keep = []
    for i in candidate_rows_by_descending_score(candidates.scores):
        if candidates.scores[i] < config.score_thresh:
            continue
        if overlaps_a_kept_box(candidates.boxes[i], keep):   # your own overlap criterion
            continue
        keep.append(i)
    return keep[: config.max_detections_per_image]           # in the order the model emitted them

postprocess = NMS(custom=my_selection_fn)

This function requires a declaration of where the candidates live (2D and 3D alike). If the candidates are in the raw output as-is, use raw_output=RawOutputSchema(hook=LayerHook("layer")); if they cannot be read directly, declare the conversion with NMS(decode=Decode(...)). Declaring neither raises at construction time.

The same signature works for 3D detection, with three differences:

  • candidates.boxes holds 7-column boxes in meters
  • The detection cap key is max_detections_per_frame
  • Candidate location is declared with raw_output=RawOutputSchema(hook=LayerHook("layer"))

If the returned row count does not match the detections

Part of that frame's inference log is not recorded, and a warning is emitted.

(3-b) You have a function that builds final detections from the raw output

Pass it to postprocess=<fn> and declare that function's return structure in output=. Regardless of task, it is called as fn(raw_output) -> output container.

spec = ModelSpec(
    labels=LabelSchema(n_class=3, ground_truth=gt),
    raw_output=RawOutputSchema(                          # what goes into the function
        S.Dict(
            cls_logits=S.DetAxis[S.ClassConfs(3, "raw", "none")],
            box_preds=S.DetAxis[S.Coords("cxcywh", "normalized")],
        ),
        hook=LayerHook("cls_head"),
    ),
    postprocess=my_postprocess,                          # fn(raw_output)
    output=S.BatchAxis[S.Dict(                           # what comes out (its return structure)
        boxes=S.DetAxis[S.Coords("xyxy", "pixel")],
        scores=S.DetAxis[S.Score("raw")],
        labels=S.DetAxis[S.LabelId(0)],
        keep_idx=S.DetAxis[S.KeepIndex()],               # when it also returns kept indices
    )],
)

If the function needs values beyond the raw output, declare them with PostProcess. The values are named with role markers.

from ml_debugger.spec import ImageShapes, PostProcess

postprocess=PostProcess(my_postprocess, kwargs={"img_sizes": ImageShapes()})
# → called as my_postprocess(raw_output, img_sizes=[(h, w), ...]) (ImageShapes is 2D detection only)
PostProcess field Contents
fn The post-processing function, called as fn(raw_output, **kwargs)
kwargs Extra values to pass; each value is a role marker (ImageShapes(), …)

(4) A query head that takes the top K

Query-head models — returning (B, Q, C) scores and (B, Q, D) boxes, taking the top-K scores with no duplicate removal — declare their raw-output structure in raw_output= and place postprocess=TopK(...). Since the selection is fully determined by TopK(...), no keep index is needed.

from ml_debugger.spec import TopK

spec = ModelSpec(
    labels=LabelSchema(n_class=3, ground_truth=gt),
    raw_output=S.Dict(
        logits=S.DetAxis[S.ClassConfs(3, "softmax", "last")],     # (B, Q, C)
        pred_boxes=S.DetAxis[S.Coords("cxcywh", "normalized")],   # (B, Q, 4)
    ),
    postprocess=TopK(max_num=100, score_thresh=0.0),
)
TopK field Default Contents
max_num None Maximum number of detections to keep
score_thresh None Lower score bound. None selects by rank only
topk_mode None (task default) "per_query" (best class per query) / "flatten" (top K over query × class)
decode None Conversion from raw output into candidates (→ Decode)

topk_mode defaults to "per_query" for 2D and "flatten" for 3D, and can be set explicitly for either task.

The raw_output= structure must contain an S.ClassConfs leaf and an S.Coords / S.Coords3D leaf (missing either raises at construction time).

If you also declare output=, the trace call returns the final detections in that structure (otherwise it returns the model's output unchanged).


Converting into candidates: Decode

NMS and TopK read the candidates (boxes and scores) they select from out of the raw output. When the raw output is not already in that shape, declare the conversion with decode=.

from ml_debugger.spec import Decode, TopK

postprocess=TopK(
    max_num=100,
    decode=Decode(
        my_decode,                                       # fn(raw_output) -> container
        returns=S.Dict(                                  # the structure it returns
            scores=S.DetAxis[S.ClassConfs(3, "sigmoid", "none")],
            boxes=S.DetAxis[S.Coords("cxcywh", "normalized")],
        ),
    ),
)
Decode field Contents
fn The conversion function, called once per batch as fn(raw_output)
returns The structure of its return value
kwargs Extra values to pass (same form as PostProcess.kwargs)

The leaves required in returns= are:

Post-processing Required leaves in returns=
NMS S.Coords + S.Score (or S.ClassConfs)
TopK S.ClassConfs + S.Coords / S.Coords3D

  • raw_output= — where the candidates live
  • output= — the final output structure
  • Validation — the nms / candidates / postprocess check groups