Repository navigation
feat(matching): opt-in required_match for physical AI object lists - #539
Conversation
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Report generated by Automated Security Helper (ASH) at 2026-11-30T22:27:46+00:00 |
vawsgit
left a comment
There was a problem hiding this comment.
✅ LGTM!
Verified at head 046559f:
- Off by default, no change. The full output for 1,200 random documents hashes identically on
devand this PR withrequired_match=False. - #538's own example, one coordinate off by 1.0: with
required_match=False, the pair scores 0.75 and counts as a true positive, the same asdev. Withrequired_match=True, it scores 0.0 and counts as one false negative plus one false alarm. - Matching is optimal. The new pairing equals brute force in all 3,000 checks.
- Tests pin it. All 7 deliberate code breaks made tests fail. The 30 new tests pass. In the full suite, one timing test failed under parallel load and passes alone.
Maintainer decision, not a blocker: #538 has two open design questions, and nobody has commented on them yet. (1) When some pairs are blocked, should matching maximise the number of matched pairs first, or similarity first? (2) Should the setting live on each field or on the whole model class? This PR answers (2) with the field-level API that #538 proposes, and it is opt-in. Please settle both in #538 before merge, because merging ships this as public API.
Merge note: CHANGELOG.md conflicts with dev. Keeping both sections resolves it.
sromoam
left a comment
There was a problem hiding this comment.
Thanks Diego, this is a really useful feature, and the validation against a separate detection F1 on 2,515 cases is great. The core veto is correct for List[StructuredModel]. Every pairing path we found goes through HungarianHelper and honours it, compare() agrees with compare_with(), and a brute-force check found the optimal assignment in 3,000 of 3,000 random cases with scores in [0, 1]. Requesting changes for gaps in coverage, docs and a few corner cases. Everything below was run against this branch.
Design: cardinality first is the right call
To answer the open question in #538: keep cardinality first. It matches gating in detection and tracking evaluation, and your validation. In practice it differs from similarity first less than it looks. With cls and x required and color/label free, both rules swap two nearby totes, because the cross pairs outscore the one strong match.
What decides the outcome is which fields are required. If every field that identifies an object is required, every wrong pairing is vetoed and both rules report 1 TP, 1 FN, 1 FA. That held even with a fuzzy label required at 0.6. Please say this in the docs (see below), since it's the thing users will get wrong.
Must fix
- A required field inside a nested model in a list item is silently ignored. In
List[Obj]whereObj.pos: PosandPos.xisrequired_match=True,xoff by 1.0 still gives a TP at 0.875, becauseObj._required_match_fields == ('cls',). Either recurse into nestedStructuredModelfields infails_required_match, or raise in_collect_required_match_fieldswhen a nested model declares a required field. - Mixed classes in one list are asymmetric. Only the ground-truth class's flags are read. Gold
Detvs predLooseDetis vetoed; swap them and it's a TP at 0.75. Please pick a rule (we'd suggest the union of both sides' required fields) and test it. - The exclusion cost assumes scores in [0, 1].
BaseComparatordoesn't clamp, so a custom comparator scoring outside [0, 1] breaks themax(m, n) + 1bound: 138 of 3,000 random assignments with scores in [-3, 5] weren't cardinality first. Either clamp similarities before building the cost matrix, or derive the sentinel from the actual cost range. Add a brute-force property test at theHungarianMatcherlevel, with m and n up to 4 and scores both inside and outside [0, 1]. - Docs that now contradict the feature:
docs/docs/Advanced/hungarian-matching.mdsays the assignment "maximizes total similarity" and that only partnerless items become FN or FA. Add the exclusion step, and qualify the FN plus FA rule.classification-logic.md: add one Lists rule for the veto.model-export.mdsays comparison is identical after a round trip. It isn't forrequired_match.src/stickler/algorithms/README.mdsaysk"is always min(m, n)" and that only one of fn and fa can be non-zero. One vetoed pair gives fn 1 and fa 1.- The comment in
hungarian.py(around:353) says the counts "cover max(m, n) items once each". With exclusions, it's m + n − k.
- The README paragraph needs an example and the key rule. Rewrite it as a few bullets with the Det example from #538. Cover:
- when to use
required_matchinstead ofweight; - that a vetoed pair counts as FN plus FA and adds nothing to the list score (0.75 becomes 0.0);
- "mark every field that identifies an object as required; fields that aren't can be traded off by the matcher, so similar objects may be paired with each other".
- when to use
Tests to add
All 30 tests assert counts through one path. Please add one case with one vetoed pair and one matched pair, asserting:
overall_score;non_matches: thedets[0]object-level FALSE_NEGATIVE and FALSE_ALARM;- the
aggregatematrix. Today it's{tp 4, fn 0, fa 0}, so the vetoed objects disappear fromaggregate. That's the existing rule for unmatched objects, but the veto now triggers it for wrong objects, so please document it; evaluator_format=True;BulkStructuredModelEvaluator;compare() == compare_with()["overall_score"].
Also:
""and NaN as null on one side;- every pair excluded for 2x2 and 2x3;
- a direct
HungarianMatcher(is_pair_excluded=...)test; - parametrize the rejected types:
Literal,Enum,date,Decimal,Union[int, str].
Smaller
EnumandLiteralare rejected, but they're the natural types for a class label, andcompare_field_rawalready scores them like primitives. Consider accepting them.threshold=0.0on a required field means the veto never fires. Warn, or document it.- Export:
to_json_schema()andto_stickler_config()drop the flag silently. Warn when a field sets it, until export supports it. List[Union[str, Det]]with a str first goes through_match_non_structured_listsand skips the veto. Raise or document.explain()and the HTML report never show the flag.- Shape:
fails_required_matchre-scores the required fields that the pair's similarity already compared, and repeats the null rulecompare_field_rawapplies. Computing the veto once while scoring each pair would remove the duplicate pass. It would also let vetoed cells skip the full recursive score, which accounts for most of the +21% at 120x120. Resolve the thresholds once per class, in_collect_required_match_fields, rather than per cell. Moving the post-assignment drop into the list comparator would keepHungarianMatchergeneral-purpose. These are optional, but they'd keep a single source of truth.
Happy to pair on any of this.
- a required field below its threshold excludes the pair from the list assignment, so both objects stay unmatched (fn 1, fa 1, no fd) - the exclusion is a cost above every allowed total, so a better allowed pairing is found and vetoed pairs are minimised first - only primitive fields may be required, anything else raises when the class is defined - default False leaves counts and scores unchanged
- states that a veto takes priority over similarity - states that a single nested object has no pairing step to veto
…h classes - a nested object is not paired, so its required fields never vetoed - the veto reads the fields required by either class, so swapping ground truth and prediction gives the same result
- a comparator may score outside [0, 1], which broke the fixed bound - the cost is now above any sum of allowed costs for the matrix at hand
- one veto and one match through compare_with, non_matches, evaluator_format and the bulk evaluator - classes with different required fields, nulls and rejected types - the matcher against a brute force, with scores inside and outside [0, 1]
- add the exclusion phase and the FN plus FA rule for a vetoed pair - state that export drops the flag and that aggregate omits vetoed objects - add an example and the rule to mark every identifying field as required
046559f to
8d60ce5
Compare
|
pushed the review fixes at
not changed: export warnings, |
…atch # Conflicts: # CHANGELOG.md # docs/docs/Advanced/classification-logic.md # docs/docs/Guides/Evaluation/README.md # src/stickler/structured_object_evaluator/models/structured_model.py
|
@sromoam pushed
all five must-fix items and the tests you listed are in. not in this PR:
for the last one, do you prefer that I document it here or raise a |
| required.append(field_name) | ||
| cls._required_match_fields = tuple(required) | ||
|
|
||
| # a nested object is not paired, so its required fields would never |
There was a problem hiding this comment.
Optional, not a blocker. This check runs once, when the class is defined, so it misses a nested class that is defined later. I measured this on this head: pos: "PosF" declared before class PosF (with x required_match=True), then ObjF.model_rebuild(), raises nothing, and ObjF._required_match_fields == ('cls',). So PosF.x is ignored without a warning, which is the silent case the check was added to stop. A module using from __future__ import annotations reaches the same state whenever the nested class comes after the parent. A one-line note beside the Dict/Union limit in the Evaluation guide would cover it. Rechecking the nested fields once the class is complete would also fix it.
There was a problem hiding this comment.
+1 to vawsgit, and this is Must fix 2 in my review. pydantic's automatic rebuild goes through model_rebuild, so this catches the forward reference. I checked it raises your error on first instantiation, with a string annotation and under from __future__ import annotations:
@classmethod
def model_rebuild(cls, *args, **kwargs):
rebuilt = super().model_rebuild(*args, **kwargs)
if rebuilt:
cls._collect_required_match_fields()
return rebuiltThere was a problem hiding this comment.
Fixed. StructuredModel.model_rebuild now runs _collect_required_match_fields() again after pydantic rebuilds the class, so pos: "Pos" declared before class Pos, and the same under from __future__ import annotations, raise the nested ValueError on first instantiation. Tests: test_a_nested_model_defined_further_down_is_refused_on_first_use in test_required_match_review.py and in the new test_required_match_future_annotations.py.
One change from the sketch: the override passes _parent_namespace_depth + 1 to super().model_rebuild(). pydantic reads the caller's frame at a fixed depth, so with the extra frame it looked in the override and lost names local to the caller. With the sketch as written, Holder.model_rebuild() on a class whose "LaterPosition" is defined in the same function raises PydanticUndefinedAnnotation, and tests/decisions/test_review_regressions.py::test_forward_reference_is_not_cached_empty (from #540) fails. test_model_rebuild_still_resolves_names_local_to_its_caller pins it.
Limit: the error comes from the rebuild, so it is raised once. If a caller catches it, a second instantiation succeeds, because the class is complete by then.
…atch # Conflicts: # docs/docs/Advanced/classification-logic.md
…atch # Conflicts: # CHANGELOG.md
sromoam
left a comment
There was a problem hiding this comment.
Thanks Diego. The merge is clean (it also merges cleanly with today's dev), CI is green, and the ground-truth-first fix is right: I reproduced the relative_tolerance over-veto on the commit before it, and your new test pins it. With the option off, the full output is byte-identical to dev on 390 list scenarios and four bulk runs, and the matcher agreed with brute force on 18,000 random cases. Two fixes are left, both small. The inline suggestions are committable.
Must fix
- A veto removes a candidate pair. It doesn't make that pair's two objects an FN plus an FA. They become an FN or an FA only when no allowed partner is left. With
labelrequired, gt[a, b]vs pred[b, a]vetoes (0,0) and (1,1) and gives 2 TP. gt[a]vs pred[b, a]vetoes (0,0) and gives 1 TP and 1 FA. The per-pair wording is in seven places: the list contract Counts row (classification-logic.md:47),hungarian-matching.md:47-48, the Evaluation README:99,src/stickler/algorithms/README.md:49, thehungarian.py:366comment, therequired_matchdocstring (comparable_field.py:162-164) and the CHANGELOG. Your newaggregatesentence in the CHANGELOG is right. Two more README lines: the example at:95gives the list's score, since aDetagainst aDetscores 0.5 with or without the flag. And since 649ad4a,:101's "swapping gives the same result" doesn't hold with an asymmetric comparator: gtR(x=100)vs predR2(x=90)is a TP, gtR2(x=90)vs predR(x=100)is vetoed. The same fields are checked whichever class is ground truth, which is the part worth saying. - The nested refusal misses a class defined further down (vawsgit's inline comment).
pos: "Pos"declared beforeclass Pos, orfrom __future__ import annotationswithPosbelow, defines fine.Pos.xis then ignored, andxwrong gives FD 0.5, while README:102says a direct nested field is refused. Please re-run_collect_required_match_fields()from amodel_rebuildoverride and add a test. The sketch is on vawsgit's thread; I checked it raises your error on first instantiation, with a string annotation and under the future import.
Also please
- Rename
fails_required_matchto_fails_required_matchunless you mean it as public API. As written it becomes a public method on everyStructuredModelin 1.1.0, and renaming it now is cheaper than after the release. - The CHANGELOG should name
HungarianMatcher(is_pair_excluded=...). It's in the CHANGELOG suggestion. - The PR description is stale: the sentinel, the test count, and the nested case, which now raises.
Your question
For List[List[Det]] and lists that mix primitives with objects, please document them here, in the :103 bullet (suggestion inline). Refusing or warning on them, and on the Dict and Union arms, is #678.
Follow-ups
Filed so they don't block this PR: #678 (shapes the veto doesn't reach), #679 (export and import), #680 (explain() and the HTML report), #681 (single-pass veto), #682 (Enum and Literal), #683 (the "Meeting a Threshold" docs). Two dev bugs I hit along the way, not caused by this PR: #684 (matching hangs on a non-finite score) and #685 (List[Union[str, Model]] raises).
The field-level and cardinality-first questions from #538 are settled there.
| | Pairing | A list field's elements are paired one-to-one by the [Hungarian algorithm](hungarian-matching.md), maximising total similarity, so their order does not matter: `["a", "b"]` vs `["b", "a"]` scores `1.0`. An element that is itself a list (`List[List[str]]`) is compared as one whole value, so order inside it does count. On the zero-config path (`stickler.evaluate()` on a plain pydantic class) that inner list, and a list held in an `Any` field, must match exactly, order included. `None` and `NaN` elements are removed first ([`None` elements in a list](#none-elements-in-a-list)); reports keep original indices. Pair similarity is the field's comparator, or `GT[i].compare(Pred[j])` for `List[StructuredModel]` (fields absent on both sides excluded). A list the field's comparator reads as one value is not paired: under `BBoxIoUComparator`, a box `[x1, y1, x2, y2]` or `[[x1, y1], [x2, y2]]` in a field whose elements are scalars (`List[float]`, `Sequence[float]`) is scored whole, with one count and one report row, so it is one FN or FA against a null list (`None`, `[]`, all `None` or NaN) and one FD against a malformed value. A field whose elements are sequences (`List[List[float]]`, or a union or alias with a sequence arm) stays paired; a bare `list` or `List[Any]` is decided by the ground-truth value. A pair that a `required_match` field vetoes is never paired, and the assignment pairs as many allowed pairs as it can before it maximises similarity. | | ||
| | Bar | `List[StructuredModel]`: the element class's `match_threshold`; a runtime `match_threshold` does not change it. A field `threshold` there raises `ValueError` in Python, and JSON Schema ignores it. Primitive, dict and plain-model lists on a `StructuredModel` declared in Python: the field's `threshold`, else a threshold named on the comparator, else `0.5` when declared with `ComparableField()`, or the class `match_threshold` (`0.7` unless set) when declared without it (`tags: List[str]`). JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../Getting-Started/thresholds-and-metrics.md#4-runtime-match-threshold)). A pair that [meets](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold) the bar is a TP. | | ||
| | Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). | | ||
| | Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. The two elements of a vetoed pair are unpaired, so one FN and one FA, never an FD. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). | |
There was a problem hiding this comment.
A veto removes a pair, not its two objects: gt [a, b] vs pred [b, a] with label required vetoes (0,0) and (1,1) and gives 2 TP. Maybe replace "The two elements of a vetoed pair are unpaired, so one FN and one FA, never an FD." with:
"A vetoed pair is never paired, so an element left with no allowed partner is unpaired: an FN or an FA, never an FD."
There was a problem hiding this comment.
Applied as suggested.
| become FN or FA. An excluded pair is never assigned, so its two items each | ||
| have no partner: one FN and one FA, never an FD. This holds identically for a one-item list and a hundred-item |
There was a problem hiding this comment.
| become FN or FA. An excluded pair is never assigned, so its two items each | |
| have no partner: one FN and one FA, never an FD. This holds identically for a one-item list and a hundred-item | |
| become FN or FA. An excluded pair is never assigned, so an item left with no | |
| allowed partner is an FN or an FA, never an FD. Both items of an excluded pair | |
| can still be paired with someone else. This holds identically for a one-item list and a hundred-item |
There was a problem hiding this comment.
Applied as suggested.
| x: float = ComparableField(threshold=0.9) | ||
| ``` | ||
|
|
||
| A `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` scores `0.0` and counts as one FN plus one FA. Without `required_match` the same pair scores `0.5` and is a TP. |
There was a problem hiding this comment.
| A `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` scores `0.0` and counts as one FN plus one FA. Without `required_match` the same pair scores `0.5` and is a TP. | |
| In a `List[Det]`, a `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` counts as one FN plus one FA, and the list scores `0.0`. Without `required_match` the pair is a TP and the list scores `0.5`. |
There was a problem hiding this comment.
Applied as suggested. Measured: the pair scores the same either way, and the list scores 0.5 without the flag and 0.0 with it (1 FN, 1 FA).
|
|
||
| - A required field that is not at or above its resolved threshold (the field's `threshold`, else one named on the comparator, else `0.5`) vetoes the pair before the Hungarian assignment. A threshold of `0.0` never vetoes a pair whose values are both present. | ||
| - A veto takes priority over similarity: the assignment keeps as many allowed pairs as it can, even at lower scores. Mark every field that identifies an object as required. A field that is not required can be traded off by the matcher, so similar objects may be paired with each other. | ||
| - The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score. |
There was a problem hiding this comment.
| - The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score. | |
| - An object left with no allowed partner counts as a False Negative (ground truth) or a False Alarm (prediction), never as a False Discovery, and adds nothing to the list score. The two objects of a vetoed pair can still pair with others: with `label` required, `[a, b]` against `[b, a]` is 2 TP. |
There was a problem hiding this comment.
Applied as suggested. Measured: [a, b] against [b, a] is 2 TP, and [a] against [b, a] is 1 TP and 1 FA.
| - A veto takes priority over similarity: the assignment keeps as many allowed pairs as it can, even at lower scores. Mark every field that identifies an object as required. A field that is not required can be traded off by the matcher, so similar objects may be paired with each other. | ||
| - The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score. | ||
| - A value that is null on one side fails; null on both sides passes. | ||
| - When the two objects have different classes, a field required by either class can veto the pair, so swapping ground truth and prediction gives the same result. |
There was a problem hiding this comment.
Since 649ad4a, each field is scored ground truth first, so with an asymmetric comparator swapping can change the result (gt R(x=100) vs pred R2(x=90) is a TP, gt R2(x=90) vs pred R(x=100) is vetoed, with relative_tolerance=0.1). That's right, it's how the field itself scores. Only the sentence needs to change:
| - When the two objects have different classes, a field required by either class can veto the pair, so swapping ground truth and prediction gives the same result. | |
| - When the two objects have different classes, a field required by either class can veto the pair, whichever of them is the ground truth. Each required field is scored ground truth first, as the field itself is. |
There was a problem hiding this comment.
Applied as suggested. Measured with NumericComparator(relative_tolerance=0.1) on a required x: gt R(x=100) against pred R2(x=90) is 1 TP, gt R2(x=90) against pred R(x=100) is 1 FN and 1 FA.
| twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one | ||
| of `fn` and `fa` can be non zero; one vetoed pair leaves `fn` 1 and `fa` 1. |
There was a problem hiding this comment.
| twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one | |
| of `fn` and `fa` can be non zero; one vetoed pair leaves `fn` 1 and `fa` 1. | |
| twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one | |
| of `fn` and `fa` can be non zero. With exclusions both can be: a 1 x 1 input | |
| whose pair is vetoed gives `fn` 1 and `fa` 1. |
There was a problem hiding this comment.
Applied as suggested. Measured: a 1 x 1 input whose pair is vetoed gives fn 1 and fa 1.
| # match() assigns exactly min(m, n) pairs unless pairs are excluded. The | ||
| # four counts below cover m + n - k items, so a vetoed pair leaves one | ||
| # item in fn and one in fa. The threshold splits the pairs into tp and |
There was a problem hiding this comment.
| # match() assigns exactly min(m, n) pairs unless pairs are excluded. The | |
| # four counts below cover m + n - k items, so a vetoed pair leaves one | |
| # item in fn and one in fa. The threshold splits the pairs into tp and | |
| # match() assigns exactly min(m, n) pairs unless pairs are excluded. The | |
| # four counts below cover m + n - k items, so an item left without an | |
| # allowed partner lands in fn or fa. The threshold splits the pairs into tp and |
There was a problem hiding this comment.
Applied, rewrapped to the comment's width.
| list of objects (default: False). A vetoed pair is excluded | ||
| before the assignment, so its two objects are left | ||
| unmatched, one false negative and one false alarm. A |
There was a problem hiding this comment.
| list of objects (default: False). A vetoed pair is excluded | |
| before the assignment, so its two objects are left | |
| unmatched, one false negative and one false alarm. A | |
| list of objects (default: False). A vetoed pair is excluded | |
| before the assignment. An object left with no allowed | |
| partner is a false negative or a false alarm, never a false discovery. A |
There was a problem hiding this comment.
Applied, rewrapped to the docstring's width.
| - `ComparableField(required_match=True)` makes a primitive field a veto when | ||
| objects are paired in a list: a pair whose required field is not at or above | ||
| its threshold is excluded before the assignment and counts as one false | ||
| negative and one false alarm, never a false discovery. Off by default; scores | ||
| and counts do not change unless a field sets it. Only `str`, `int`, `float` | ||
| and `bool` fields may be required, and a class may not hold a single nested | ||
| model that has required fields (`ValueError` when the class is defined). When | ||
| the two objects have different classes, a field required by either one vetoes | ||
| the pair. The vetoed objects follow the `aggregate` rule for any FN or FA | ||
| item: left out when a sibling was accepted, in the list's own counts when | ||
| none was. Python only: `to_json_schema()` and `to_stickler_config()` do not | ||
| write it, and `model_from_json()` and `from_json_schema()` do not read it. |
There was a problem hiding this comment.
The per-pair clause (Must fix 1), plus the new matcher keyword. Your aggregate sentence stays:
| - `ComparableField(required_match=True)` makes a primitive field a veto when | |
| objects are paired in a list: a pair whose required field is not at or above | |
| its threshold is excluded before the assignment and counts as one false | |
| negative and one false alarm, never a false discovery. Off by default; scores | |
| and counts do not change unless a field sets it. Only `str`, `int`, `float` | |
| and `bool` fields may be required, and a class may not hold a single nested | |
| model that has required fields (`ValueError` when the class is defined). When | |
| the two objects have different classes, a field required by either one vetoes | |
| the pair. The vetoed objects follow the `aggregate` rule for any FN or FA | |
| item: left out when a sibling was accepted, in the list's own counts when | |
| none was. Python only: `to_json_schema()` and `to_stickler_config()` do not | |
| write it, and `model_from_json()` and `from_json_schema()` do not read it. | |
| - `ComparableField(required_match=True)` makes a primitive field a veto when | |
| objects are paired in a list: a pair whose required field is not at or above | |
| its threshold is excluded before the assignment, which keeps as many allowed | |
| pairs as it can. An object left with no allowed partner counts as a false | |
| negative or a false alarm, never a false discovery. Off by default; scores | |
| and counts do not change unless a field sets it. Only `str`, `int`, `float` | |
| and `bool` fields may be required, and a class may not hold a single nested | |
| model that has required fields (`ValueError` when the class is defined). When | |
| the two objects have different classes, a field required by either one vetoes | |
| the pair. The unmatched objects follow the `aggregate` rule for any FN or FA | |
| item: left out when a sibling was accepted, in the list's own counts when | |
| none was. `HungarianMatcher` takes a new `is_pair_excluded` keyword for this. | |
| Python only: `to_json_schema()` and `to_stickler_config()` do not write it, | |
| and `model_from_json()` and `from_json_schema()` do not read it. |
There was a problem hiding this comment.
Applied, with one addition: the nested refusal now says ValueError when the class is defined, or on first use for a nested class defined further down.
| ``self`` is the ground truth. Both classes' required fields are read, so | ||
| swapping ground truth and prediction gives the same answer when their | ||
| classes differ. Every field is scored ground truth first, as the field |
There was a problem hiding this comment.
Optional, same point as README :101: with an asymmetric comparator, swapping can change the answer. "Both classes' required fields are read, so the same fields are checked whichever class is ground truth" would be exact.
There was a problem hiding this comment.
Applied: "Both classes' required fields are read, so the same fields are checked whichever class is ground truth."
…atch # Conflicts: # CHANGELOG.md # src/stickler/structured_object_evaluator/models/structured_model.py
- a vetoed pair's objects can still pair with others: with `label` required, `[a, b]` against `[b, a]` is 2 TP, and `[a]` against `[b, a]` is 1 TP and 1 FA - only an object left with no allowed partner is an FN or an FA - the Evaluation example gives the list score: the pair scores 0.5 either way, the list 0.5 without the flag and 0.0 with it - swapping ground truth and prediction can change the result with an asymmetric comparator, so state what holds instead: the same fields are checked whichever class is ground truth - document that a `List[List[Det]]` is not vetoed, and that a mixed list is vetoed only when the ground truth list's first present element is an object
- a nested class named before it is defined (`pos: "Pos"`, or under `from __future__ import annotations`) is a string when the parent is defined, so the nested refusal missed it and `Pos.x` was ignored - `model_rebuild` now runs `_collect_required_match_fields()` again; pydantic calls it on first instantiation, so the `ValueError` comes then at the latest - the override passes one more frame of `_parent_namespace_depth`, so a forward reference to a class local to the caller still resolves
- it is only called by the Hungarian helper, so it should not ship as a public method on every `StructuredModel` in 1.1.0 - renaming it before the release costs nothing; after it, it would be a breaking change
- a veto removes a candidate pair; only an object left with no allowed partner is an FN or an FA - name the new `HungarianMatcher(is_pair_excluded=...)` keyword - the nested refusal also covers a nested class defined further down, on first use
|
Both must-fixes and the three asks are done, and current
|
…e-detection-notebook
sromoam
left a comment
There was a problem hiding this comment.
Thanks Diego, approving. I checked each fix on 2e1986ad: the per-pair FN plus FA wording is gone everywhere, _fails_required_match is private, and the forward-referenced nested class now raises on direct instantiation. CI is green, and the diff against dev touches no CI or build files.
Two small things, not blocking. Either land them here or I'll take them in a follow-up:
_collect_required_match_fieldshas the "unwrapOptional/Annotateduntil stable" loop twice.ConfigurationHelper.strip_annotation_wrappersalready does this and the file uses it elsewhere, and hand-rolled copies of this check have caused bugs before.- The
ComparableField(...)parameter block insrc/stickler/structured_object_evaluator/README.md(around:333) doesn't listrequired_matchyet.
I've added a few narrow shapes to #678: a forward-referenced nested class whose holder is only ever built through a parent's list (the refusal doesn't fire there), mixed lists whose first ground-truth element isn't a model, cross-class pairs where only the prediction's class declares the required field, and a class holding both a single nested Det and a List[Det].
…abs#539 ref - awslabs#539 merged, so required_match ships in 1.1.0; the badge, install line, warning and preflight error pointed at refs/pull/539/head - until 1.1.0 is released the install is git+...@dev, then stickler-eval>=1.1.0 - outputs unchanged: a clean python:3.12-slim run on this tree gives the same results sha256 and the same tables; only timings differ
- a wrong class is now FN plus FA through required_match on cls, so cm_recall reads 0.5 without recall_with_fd; match_threshold stays only for the IoU bar, which required_match cannot express - Hungarian never makes a vetoed pair, and every printed count, the bulk metrics and the Use-Cases table row match dev with awslabs#539
Issue Reference
Closes #538
Description of Changes
this adds an opt-in
ComparableField(required_match=True). when objects are paired inside aList[StructuredModel], a pair whose required field is not at or above its resolved threshold is excluded before the Hungarian assignment. a vetoed pair is never paired, so an object left with no allowed partner counts as a false negative or a false alarm, never astporfd. the two objects of a vetoed pair can still pair with others: withlabelrequired,[a, b]against[b, a]is 2 TP. the default isFalse, so nothing changes unless a field sets it. #538 has the reasoning, including whyweightcannot cover this.Changes Made
comparable_field.py: newrequired_match: bool = Falseparameter, stored onjson_schema_extranext tothresholdandweight.structured_model.py:_collect_required_match_fieldsrecords the required fields when the class is defined, and raisesValueErrorfor any annotation other thanstr,int,float,bool(optionallyOptional), and for a single nested model that has required fields. amodel_rebuildoverride runs it again, so a nested class defined further down (pos: "Pos", or underfrom __future__ import annotations) raises too, at the latest on first instantiation._fails_required_match(other)applies the rule: a field fails whenThresholdHelper.is_above_thresholdis false for its resolved threshold. null on one side fails, null on both sides passes.hungarian.py:HungarianMatchertakes an optionalis_pair_excludedcallback. an excluded pair costs more than any sum of allowed costs (the highest allowed cost plusmin(m, n)times the spread of allowed costs, plus 1), derived from the allowed costs because a comparator may score outside [0, 1], so the solver uses it only when nothing allowed is left. it is then dropped from the matches.hungarian_helper.py: passesis_pair_excludedforStructuredModellists.CHANGELOG.md: entry under[Unreleased]### Added, naming the newHungarianMatcher(is_pair_excluded=...)keyword.docs/docs/Guides/Evaluation/README.md: the parameter in theComparableFieldtable, plus its semantics and limits.Why These Changes Are Needed
physical AI evaluation scores lists of objects a physical agent perceives, and a detection metric needs "any wrong field means not the same object". weights cannot express that for more than three fields at the default
match_threshold0.7, since each field would need over 30% of the total weight. see #538.Testing
tests/structured_object_evaluator/: 30 intest_required_match.py, 38 intest_required_match_review.pyand 1 intest_required_match_future_annotations.py. they cover default off (counts and score unchanged), one failing axis (1 fn, 1 fa, 0 fd), wrong class, all required fields passing, null on one side and on both, a threshold on the field and one on the comparator, a partial score at and just under its threshold, a non-primitive required field raising, a nested list, empty lists, an inherited required field, wrapped primitives, a better pairing found once a pair is excluded, the reporting paths, a veto across two classes, the nested refusal (including a nested class defined further down), andHungarianMatcherwith exclusions against a brute force.uv run pyteston this branch, withdev3378fe9 merged, gives 7152 passed, 13 skipped, 1 xfailed on Python 3.12 and 3.14, and 7147 passed, 18 skipped, 1 xfailed on 3.10, where 5 more tests skip, gated on the PEP 695typestatement or on extras not installed there.tests/integrationsgives 690 passed, 1 skipped.uv run ruff checkon the changed files passes.cost, one machine, 120 x 120 list, four primitive fields, median of 7 runs, three rounds each (not a benchmark):
dev: 0.30 to 0.37 s.dev._fails_required_matchin the cost matrix pass.Reviewers
@sromoam
Checklist
CHANGELOG.mdentry added under[Unreleased]Additional Notes
Det,overall_scoregoes from 0.75 to 0.0, andnon_matches(withdocument_non_matches=True) reports one object-levelFALSE_NEGATIVEand oneFALSE_ALARMinstead of a fieldFALSE_DISCOVERY.ValueErrorinstead of being ignored. aList[List[Det]]is not vetoed, and a list that mixes objects with primitives is vetoed only when the ground truth list's first element that is notNoneis an object. required_match: warn for nested shapes the veto doesn't reach #678 tracks refusing or warning on these and on theDictandUnionarms. the flag is Python only:to_json_schema()andto_stickler_config()do not write it, andmodel_from_json()andfrom_json_schema()do not read it. a subclass that redeclares the field without it drops the veto.By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.