Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ Each release links to full notes on the

### Fixed

- List reporting ([#332](https://github.com/awslabs/stickler/issues/332)):
`non_matches` and `field_comparisons` reuse the pairings, scores, and
threshold decisions made during list scoring. Rejected pairs produce indexed
false-discovery records. Primitive-list reports avoid extra comparator calls
and preserve scoring's threshold tolerance. Standard structured-child reports
reuse scored child results; custom comparison overrides retain their fallback.

- **An unrecognized key in a model config is now reported instead of dropped.**
`model_from_json` read a closed set of keys and ignored everything else, so
`"threshhold": 0.99` built at the fallback 0.5 with no exception and no warning,
Expand Down
17 changes: 8 additions & 9 deletions docs/docs/Guides/Comparators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -611,20 +611,19 @@ accepts.
Stickler warns once per field rather than raising, because which class arrives is
a property of the prediction, and raising would end a bulk run partway through.

!!! warning "A refused list element is counted but not reported"
!!! note "Rejected list elements are included in reports"

A refused element is one `fd` in the confusion matrix, but it produces no
entry in `non_matches`, so the counts and the item-level report disagree:
A rejected pair contributes one `fd` in the confusion matrix and an indexed
entry in `non_matches`. With `document_field_comparisons=True`, its row has
`match=False` and `score=0.0`:

```
[Plain(sku='a')] vs [Cat(sku='a')] -> fd=1, non_matches: []
[Plain(sku='a')] vs [Cat(sku='a')] -> fd=1, non_matches: f[0]
```

An ordinary below-threshold element *is* reported, so this is specific to a
refusal. The item-level report re-derives its own pairing without the field's
comparator, which is why it cannot see the refusal. Read the counts, not
`non_matches`, when you need to know whether a list element was refused.
Tracked in [#332](https://github.com/awslabs/stickler/issues/332).
Both reports use the field's comparator and threshold for plain-model and
primitive lists. Structured-model lists retain recursive matching and the
element model's `match_threshold`.

### The annotation has to name the model

Expand Down
7 changes: 4 additions & 3 deletions src/stickler/algorithms/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

One module, one public class. `HungarianMatcher` pairs the items of two lists so
that the total similarity is as high as it can be, which is what lets a list
field be scored without caring about order. Both of its internal callers are on
field be scored without caring about order. Its internal callers are on
the traditional evaluation path.

**ANLS Star does not go through this class.** `trees/list_tree.py` calls
Expand Down Expand Up @@ -77,19 +77,20 @@ a score inside that window is a TP there and an FD here.

## How the evaluator uses it

Both internal callers read **only** `matched_pairs` and classify the scores
All internal callers read **only** `matched_pairs` and classify the scores
themselves:

| Caller | What it does with the pairs |
|---|---|
| `HungarianHelper.get_complete_matching_info` | derives the matched and unmatched index sets for object matching over `List[StructuredModel]` |
| `ComparisonHelper.compare_unordered_lists` | hands them to `unordered_list_metrics`, which counts against its own `classification_threshold` |
| `ComparisonHelperBase.get_optimal_assignments` | provides pairings for direct report-helper calls; `compare_with` reports instead reuse the scoring pass's pairings |

`unordered_list_metrics` uses the same derivation as `calculate_metrics`, so the
two agree on what a count means. The remaining difference is the tolerant
threshold test noted above.

Because neither caller reads the counts, a change to how `calculate_metrics`
Because these callers do not read the counts, a change to how `calculate_metrics`
classifies cannot move an evaluator score. It is a public API in its own right
though, so a change there is still breaking for a direct caller.

Expand Down
6 changes: 5 additions & 1 deletion src/stickler/structured_object_evaluator/models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ its `from_json()` ingestion and `compare_with()` comparison pipeline.
**Comparison pipeline**
- `comparison_engine.py` — `ComparisonEngine`, the orchestrator behind
`compare_with()`. Runs a single recursive traversal, then layers on confusion
matrix, non-matches, field comparisons, and optional metrics.
matrix, non-matches, field comparisons, and optional metrics. Structured-list
reporting reuses child traversals from scoring for the standard `compare_with`
implementation; that cache is removed from public results. Custom overrides
of `compare_with`/`compare_recursive` and direct report-helper calls retain
their comparison fallback.
- `comparison_dispatcher.py`, `field_comparator.py`,
`primitive_list_comparator.py`, `structured_list_comparator.py`,
`hungarian_helper.py` — dispatch and per-type comparison, including Hungarian
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,17 @@ def confusion_matrix_builder(self):
self._confusion_matrix_builder = ConfusionMatrixBuilder(self.model)
return self._confusion_matrix_builder

def compare_recursive(self, other: "StructuredModel") -> Dict[str, Any]:
@staticmethod
def _drop_list_matching(result: Dict[str, Any]) -> None:
"""Remove scoring-only pairing details from a public result tree."""
for field_result in result.get("fields", {}).values():
if isinstance(field_result, dict):
field_result.pop("_list_matching", None)
ComparisonEngine._drop_list_matching(field_result)

def compare_recursive(
self, other: "StructuredModel", *, _include_list_matching: bool = False
) -> Dict[str, Any]:
"""The core recursive comparison function.

This method performs a single-traversal comparison of two StructuredModel
Expand Down Expand Up @@ -177,6 +187,8 @@ def compare_recursive(self, other: "StructuredModel") -> Dict[str, Any]:
if total_weight > 0:
result["overall"]["similarity_score"] = total_score / total_weight

if not _include_list_matching:
self._drop_list_matching(result)
return result

def compare_with(
Expand All @@ -192,6 +204,7 @@ def compare_with(
confidence_metrics: Optional[List["ConfidenceMetric"]] = None,
add_bbox_metrics: bool = False,
bbox_iou_thresholds: Optional[Union[float, Iterable[float]]] = None,
_retain_recursive_result: bool = False,
) -> Dict[str, Any]:
"""Compare with another instance using single traversal.

Expand Down Expand Up @@ -249,7 +262,7 @@ def compare_with(
>>> print(result["confusion_matrix"]["overall"]["tp"])
"""
# SINGLE TRAVERSAL: Get everything in one pass
recursive_result = self.compare_recursive(other)
recursive_result = self.compare_recursive(other, _include_list_matching=True)

# Extract scoring information from recursive result
field_scores = {}
Expand Down Expand Up @@ -441,6 +454,17 @@ def compare_with(
if pred_bboxes:
result["prediction_bboxes"] = pred_bboxes

# The collectors have consumed the scoring-only pairings. Keep the
# public recursive/confusion-matrix result shape unchanged.
if _retain_recursive_result:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker (root cause of the comment above). Pairing data travels inside the public result tree and is stripped at several separate exits (compare_recursive, the compare_with recursive result, the compare_with confusion matrix), so any exit without a strip leaks it. _dispatch_field_comparison is one already; a new public helper or collector would be the next.

Suggested fix: keep the pairings in a side map owned by the engine and keyed by field path, which the collectors read. Public dicts then never hold private keys and need no strip-on-exit. That also removes the extra tree walks noted at line 465.

# Internal structured-list scoring passes this same traversal to
# the report collectors instead of comparing a child again.
result["_recursive_result"] = recursive_result
else:
self._drop_list_matching(recursive_result)
if "confusion_matrix" in result:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. Each public compare_with walks the result tree twice more to strip _list_matching: once on recursive_result, once on the confusion-matrix copies made before the collectors ran. Building the confusion matrix after stripping, or keeping the data out of the tree (see line 459), removes both walks.

self._drop_list_matching(result["confusion_matrix"])

# If evaluator_format is requested, transform the result
if evaluator_format:
return self.model._format_for_evaluator(result, other, recall_with_fd)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,32 @@ def _holds_a_plain_model(items: List[Any]) -> bool:
return any(_is_plain_model(item) for item in items)


def _match_non_structured_lists(
gt_list: List[Any],
pred_list: List[Any],
comparator: BaseComparator,
*,
model_cls=None,
field_name: str = "",
warn_selected: bool = False,
) -> List[tuple]:
"""Use the same raw-value matcher and class gate for scoring and direct reports."""
from stickler.algorithms.hungarian import HungarianMatcher

element_comparator = comparator
if _holds_a_plain_model(gt_list) or _holds_a_plain_model(pred_list):
element_comparator = _ClassGatedComparator(
comparator, model_cls=model_cls, field_name=field_name
)
matcher = HungarianMatcher(
element_comparator, match_threshold=0.0, normalize_values=False
)
pairs = matcher.calculate_metrics(gt_list, pred_list)["matched_pairs"]
if warn_selected and isinstance(element_comparator, _ClassGatedComparator):
element_comparator.warn_for_selected(gt_list, pred_list, pairs)
return pairs


def _maybe_absent(val: Any) -> bool:
"""Whether ``val`` could be absent under *either* of ``NullHelper``'s rules.

Expand Down Expand Up @@ -180,6 +206,7 @@ def compare_unordered_lists(
clip_under_threshold: bool = True,
model_cls=None,
field_name: str = "",
pair_sink: List[tuple] | None = None,
) -> Dict[str, Any]:
"""Compare two lists as unordered collections using Hungarian matching.

Expand All @@ -196,6 +223,8 @@ def compare_unordered_lists(
default to a falsy value so a caller with no field in hand still
gets the gate -- it refuses the same pairs either way, and only
the warning is less specific.
pair_sink: Optional list populated with the selected (ground-truth
index, prediction index, score) tuples from this scoring pass.

Returns:
Dictionary with confusion matrix metrics including:
Expand Down Expand Up @@ -264,8 +293,6 @@ def compare_unordered_lists(
)
else:
# Use the provided comparator for other types
from stickler.algorithms.hungarian import HungarianMatcher

# CRITICAL FIX: Use match_threshold=0.0 to capture ALL matches, not just those above threshold
# This allows us to keep track of partial matches for scoring.
#
Expand All @@ -289,29 +316,15 @@ def compare_unordered_lists(
# Gate the element comparator on class identity. See
# _ClassGatedComparator; skipped entirely for ordinary primitive
# lists so the cost matrix stays unwrapped.
element_comparator = comparator
if _holds_a_plain_model(gt_list) or _holds_a_plain_model(pred_list):
element_comparator = _ClassGatedComparator(
comparator, model_cls=model_cls, field_name=field_name
)

hungarian = HungarianMatcher(
element_comparator, match_threshold=0.0, normalize_values=False
)
classification_threshold = threshold

# Get detailed metrics from HungarianMatcher
metrics = hungarian.calculate_metrics(gt_list, pred_list)
matched_pairs = metrics["matched_pairs"]

# Only now is it known which pairs were chosen. The gate ran silently
# over the whole cost matrix; warning from inside it described
# discarded cells and spent `warn_once`'s single message per field on
# them. See `_ClassGatedComparator.warn_for_selected`.
if isinstance(element_comparator, _ClassGatedComparator):
element_comparator.warn_for_selected(
gt_list, pred_list, matched_pairs
)
matched_pairs = _match_non_structured_lists(
gt_list, pred_list, comparator,
model_cls=model_cls, field_name=field_name, warn_selected=True,
)

if pair_sink is not None:
pair_sink.extend(matched_pairs)

return ComparisonHelper.unordered_list_metrics(
matched_pairs=matched_pairs,
Expand Down
Loading