Repository navigation
feat(matching): opt-in required_match for physical AI object lists #539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 10 commits
25db8d3
966bcc0
d38d9c5
292d282
17b1961
8d60ce5
381b6bb
649ad4a
aacef3f
76683cc
7641529
348d632
f591dc1
8e877b2
2e1986a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -42,9 +42,9 @@ This table is the single statement of how Stickler treats a list field. Other pa | |
|
|
||
| | Aspect | Rule | | ||
| |---|---| | ||
| | 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. | | ||
| | 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`). | | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A veto removes a pair, not its two objects: gt "A vetoed pair is never paired, so an element left with no allowed partner is unpaired: an FN or an FA, never an FD."
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Applied as suggested. |
||
| | Recursion | Only TP pairs of `StructuredModel` items are descended into. FD, FN and FA items are atomic. `aggregate` holds the leaves of TP items only, so FD, FN and FA items are left out of it when any sibling was accepted. With no accepted item it falls back to the list node's own counts ([why](aggregate-metrics.md#aggregate-counts-objects-for-an-all-rejected-list)). | | ||
| | Score | `sum(pair scores) / max(n_gt, n_pred)`, never clipped as a whole against a field threshold. For primitive, dict and plain-model lists the pair score is the element similarity, zeroed below the bar when `clip_under_threshold` is on. On a `StructuredModel` declared in Python it defaults to on for primitive lists and off for dict and plain-model lists. JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../API-Reference/auto.md#inference)). For `List[StructuredModel]` the pair score is `GT[i].compare_with(Pred[j])["overall_score"]`, which applies each field's own threshold and can differ from the pairing similarity. Currently `clip_under_threshold` has no effect there, so an FD pair keeps its score: a known gap. [Worked example](hungarian-matching.md#step-4-list-score). | | ||
| | Reports | `field_comparisons`: one row per element of a primitive, dict or plain-model list, whatever its classification (a dict or plain-model element is not expanded into its keys or fields); for `List[StructuredModel]`, one row per leaf of a TP item and one object row per FD, FN or FA item. `non_matches` has the same rows, but only the FD, FN and FA ones. A `field_comparisons` row's `match` is true when its own classification is TP or TN: a value or object row met its bar; a list row had every element paired as a TP, with no FD, FA or FN at the element level. Failures deeper down get their own rows. | | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -8,23 +8,28 @@ When Stickler compares `List[StructuredModel]` fields, it uses the Hungarian alg | |||||||||||
|
|
||||||||||||
| ## Overview | ||||||||||||
|
|
||||||||||||
| The algorithm has three phases: | ||||||||||||
| The algorithm has four phases: | ||||||||||||
|
|
||||||||||||
| 1. **Pairwise similarity** -- Compute a similarity score for every GT/Pred combination. | ||||||||||||
| 2. **Optimal assignment** -- Use the Hungarian algorithm to find the pairing that maximizes total similarity. | ||||||||||||
| 3. **Threshold-gated classification** -- Classify each pair as TP or FD based on `match_threshold`, then handle unmatched items. | ||||||||||||
| 2. **Exclusion** -- Remove every pair that a `required_match` field vetoes. A no-op when no field sets it. | ||||||||||||
| 3. **Optimal assignment** -- Use the Hungarian algorithm to find the pairing that maximizes total similarity among the allowed pairs. | ||||||||||||
| 4. **Threshold-gated classification** -- Classify each pair as TP or FD based on `match_threshold`, then handle unmatched items. | ||||||||||||
|
|
||||||||||||
| ## Algorithm Steps | ||||||||||||
|
|
||||||||||||
| ### 1. Pairwise Similarity | ||||||||||||
|
|
||||||||||||
| For each (GT[i], Pred[j]) pair, Stickler calls `GT[i].compare(Pred[j])` to obtain a raw weighted similarity score. Fields absent on both sides are excluded because a true negative is not match evidence. If every field is absent, the score is `1.0`. The result is an N x M cost matrix. | ||||||||||||
|
|
||||||||||||
| ### 2. Hungarian Assignment | ||||||||||||
| ### 2. Exclusion | ||||||||||||
|
|
||||||||||||
| The Hungarian algorithm solves the assignment problem in O(n^3) time, producing a one-to-one mapping that maximizes total similarity. When lists differ in length, some items remain unmatched. | ||||||||||||
| A pair is excluded when a field marked `required_match` is null on one side only, or scores below its threshold, on either object's class. The assignment then keeps as many allowed pairs as it can, even at lower similarity. See `required_match` in [Evaluation](../Guides/Evaluation/README.md). | ||||||||||||
|
|
||||||||||||
| ### 3. Threshold-Gated Classification | ||||||||||||
| ### 3. Hungarian Assignment | ||||||||||||
|
|
||||||||||||
| The Hungarian algorithm solves the assignment problem in O(n^3) time, producing a one-to-one mapping that maximizes total similarity over the allowed pairs. When lists differ in length, or pairs were excluded, some items remain unmatched. | ||||||||||||
|
|
||||||||||||
| ### 4. Threshold-Gated Classification | ||||||||||||
|
|
||||||||||||
| Each matched pair is classified using `StructuredModel.match_threshold`, with `>=` as described in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold): | ||||||||||||
|
|
||||||||||||
|
|
@@ -39,7 +44,8 @@ The threshold splits matched pairs into TP and FD; it does not un-match them. | |||||||||||
| A pair the algorithm assigned is a match, so **similarity magnitude never | ||||||||||||
| changes the classification** -- a pair at similarity `0.0` is still an assigned | ||||||||||||
| pair and is therefore FD, not FN + FA. Only items with no partner at all | ||||||||||||
| become FN or FA. This holds identically for a one-item list and a hundred-item | ||||||||||||
| 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 | ||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Applied as suggested. |
||||||||||||
| one; see `tests/common/algorithms/test_hungarian_path_parity.py`. | ||||||||||||
|
|
||||||||||||
| `HungarianMatcher.calculate_metrics` returns these same four counts if you call | ||||||||||||
|
|
||||||||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -52,6 +52,7 @@ When defining a `StructuredModel` subclass in Python, each field is declared wit | |||||
| | `threshold` | `float` (0.0--1.0) | `0.5` | Minimum similarity score required for a field to be classified as a match. | | ||||||
| | `weight` | `float` (> 0.0) | `1.0` | Relative importance of this field when computing aggregate scores. | | ||||||
| | `clip_under_threshold` | `bool` | `True` (`False` on dict and plain-model fields and lists of them) | When `True`, scores below `threshold` are zeroed out before contributing to the weighted average. List fields follow the [Score](../../Advanced/classification-logic.md#list-contract) rule of the list contract. | | ||||||
| | `required_match` | `bool` | `False` | When `True`, a score not at or above `threshold` vetoes the object pair when objects are matched inside a list. | | ||||||
|
|
||||||
| ### How Each Parameter Affects Scoring | ||||||
|
|
||||||
|
|
@@ -82,6 +83,26 @@ Fields with higher weights pull the overall score toward their individual result | |||||
|
|
||||||
| **`clip_under_threshold`** -- When enabled (the default, except on dict and plain-model fields), a field that scores below its threshold contributes 0.0 to the weighted average instead of its partial similarity. This prevents low-confidence matches from inflating the overall score. A list field follows the [Score](../../Advanced/classification-logic.md#list-contract) rule of the list contract instead. | ||||||
|
|
||||||
| **`required_match`** -- Without it, an object with one wrong field still matches when its overall score reaches the element class's `match_threshold`. Use it instead of `weight` when a wrong value must never pair two objects, however well the rest agrees. | ||||||
|
|
||||||
| ```python | ||||||
| class Det(StructuredModel): | ||||||
| match_threshold = 0.5 | ||||||
| cls: str = ComparableField(threshold=1.0, required_match=True) | ||||||
| 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. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Applied as suggested. Measured: the pair scores the same either way, and the list scores |
||||||
|
|
||||||
| - 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. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Applied as suggested. Measured: |
||||||
| - 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. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since 649ad4a, each field is scored ground truth first, so with an asymmetric comparator swapping can change the result (gt
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Applied as suggested. Measured with |
||||||
| - Only `str`, `int`, `float` and `bool` fields (optionally `Optional`) may be required, and a class may not hold a nested `StructuredModel` field whose class has required fields. Both raise `ValueError` when the class is defined. Only a direct, `Optional` or `Annotated` nested field is checked; one reached through a `Dict` or a `Union` is not, and its required fields are ignored. | ||||||
| - The veto applies where objects are paired in a `List[StructuredModel]`. A single nested object has no pairing step, so it is not vetoed. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. On your question: document these here for now; a warning at class definition is #678.
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Applied the For #678: mixed lists already raise |
||||||
| - The setting is 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. | ||||||
|
|
||||||
| ### Example Model | ||||||
|
|
||||||
| ```python | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -33,8 +33,8 @@ matcher.calculate_metrics(["apple", "banana"], ["banana", "aple"]) | |||||||||||
|
|
||||||||||||
| The assignment decides what is paired. `match_threshold` then splits the paired | ||||||||||||
| items into two groups. It never puts a pair back into the unpaired counts. With | ||||||||||||
| `m` and `n` as the two list lengths and `k` as the pair count, which is always | ||||||||||||
| `min(m, n)`: | ||||||||||||
| `m` and `n` as the two list lengths and `k` as the pair count, which is | ||||||||||||
| `min(m, n)` unless `is_pair_excluded` vetoes pairs: | ||||||||||||
|
|
||||||||||||
| | Key | Meaning | Closed form | | ||||||||||||
| |---|---|---| | ||||||||||||
|
|
@@ -44,8 +44,9 @@ items into two groups. It never puts a pair back into the unpaired counts. With | |||||||||||
| | `fa` | prediction item with no partner, a false alarm | `n` minus `k` | | ||||||||||||
| | `fp` | the rollup, `fd` plus `fa` | `n` minus `tp` | | ||||||||||||
|
|
||||||||||||
| The four leaf counts cover `max(m, n)` items once each, so nothing is counted | ||||||||||||
| twice and nothing is dropped. Only one of `fn` and `fa` can be non zero. | ||||||||||||
| The four leaf counts cover `m + n - k` items once each, so nothing is counted | ||||||||||||
| 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. | ||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Applied as suggested. Measured: a 1 x 1 input whose pair is vetoed gives |
||||||||||||
| `tp + fp == n` and `tp + fn + fd == m`, which is why `precision` and `recall` | ||||||||||||
| have a denominator in closed form and the method needs no special case per | ||||||||||||
| input shape. | ||||||||||||
|
|
||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The per-pair clause (Must fix 1), plus the new matcher keyword. Your
aggregatesentence stays:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Applied, with one addition: the nested refusal now says
ValueErrorwhen the class is defined, or on first use for a nested class defined further down.