Skip to content
Next Next commit
fix: break list assignment ties so scores ignore element order
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
  • Loading branch information
pcbeingused33 and claude committed Nov 28, 2026
commit b8de657be83c0bca6b4efc6ce2d5e32095592a69
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,9 @@ Each release links to full notes on the

### Fixed

- A list field of scalar values no longer scores differently when elements are
reordered and several assignments tie on total similarity. The tie now goes to
the assignment with more pairs meeting the field's threshold (#658).

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.

A possible wording, with a bold lead, the issue link and the new argument:

Suggested change
- A list field of scalar values no longer scores differently when elements are
reordered and several assignments tie on total similarity. The tie now goes to
the assignment with more pairs meeting the field's threshold (#658).
- **A list of values scores the same in any order when pairings tie.** The
solver picked among equally good pairings by position, so reordering a
`List[str]` could move it from 2 TP and 1 FD (`0.5`) to 1 TP and 2 FD
(`0.25`). A tie now goes to the pairing with more pairs meeting the field's
threshold, then to the one where those pairs score more.
`List[StructuredModel]` is unchanged. `HungarianMatcher` takes the rule as a
new `tie_break_threshold` argument, off by default
([#658](https://github.com/awslabs/stickler/issues/658)).

- **`to_stickler_config()` exports a tuple field as a tuple.** It was written
as `"str"`, so the model rebuilt by `model_from_json()` rejected the original
value. Tuples of primitives keep their element types (`Tuple[float, float]`);
Expand Down
33 changes: 32 additions & 1 deletion src/stickler/algorithms/hungarian.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
# Memory threshold for warning in MB
HUNGARIAN_SIZE_WARNING_THRESHOLD = 10000 # Matrix size (product of dimensions)

# Total weight of the tie-break, small enough not to outrank a real difference
# between two assignments' similarity totals.
_TIE_BREAK_WEIGHT = 1e-9

# Global Munkres instance for optimization
_MUNKRES = Munkres()

Expand All @@ -35,6 +39,7 @@ def __init__(
size_threshold: int = HUNGARIAN_SIZE_WARNING_THRESHOLD,
normalize_values: bool = True,
match_threshold: float = 0.7,
tie_break_threshold: Optional[float] = None,
):
"""Initialize the Hungarian matcher.

Expand Down Expand Up @@ -68,11 +73,16 @@ def __init__(
never sees ``""`` standing in for a missing
element.
match_threshold: Minimum similarity score to consider a match as TP
tie_break_threshold: If given, assignments with equal total
similarity are ranked by how many pairs meet this threshold,
then by the similarity those pairs add up to, so the counts
do not depend on element order. Reported scores are unchanged.
"""
self.comparator = comparator or (lambda x, y: float(x == y))
self.size_threshold = size_threshold
self.normalize_values = normalize_values
self.match_threshold = match_threshold
self.tie_break_threshold = tie_break_threshold

def _normalize_value(self, value: Any) -> Any:
"""Normalize a value to improve string matching.
Expand Down Expand Up @@ -188,6 +198,25 @@ def _score(self, item1: Any, item2: Any) -> float:
raise
return compare(self._comparable_form(item1), self._comparable_form(item2))

def _ranking_matrix(self, similarity_matrix: np.ndarray) -> np.ndarray:
"""Similarities as the solver should rank them, ties broken."""
if self.tie_break_threshold is None:
return similarity_matrix

# Imported here for the same reason as in calculate_metrics.
from stickler.structured_object_evaluator.models.threshold_helper import (
ThresholdHelper,
)

pairs = min(similarity_matrix.shape)
above = np.vectorize(ThresholdHelper.is_above_threshold)(
similarity_matrix, self.tie_break_threshold
)
# One more pair above the threshold outweighs any sum of similarities,
# which the division by ``pairs + 1`` keeps below one.
bonus = above * (1 + similarity_matrix / (pairs + 1))
return similarity_matrix + bonus * (_TIE_BREAK_WEIGHT / pairs)

def match(self, list1: Any, list2: Any) -> Tuple[List[Tuple[int, int]], np.ndarray]:
"""Find optimal assignments between two lists.

Expand Down Expand Up @@ -233,7 +262,9 @@ def match(self, list1: Any, list2: Any) -> Tuple[List[Tuple[int, int]], np.ndarr

# Convert to cost matrix for the Hungarian algorithm
# Cost is 1 - similarity (because Hungarian minimizes cost)
cost_matrix = make_cost_matrix(similarity_matrix, lambda x: 1 - x)
cost_matrix = make_cost_matrix(
self._ranking_matrix(similarity_matrix), lambda x: 1 - x
)

# Compute the optimal assignment
matched_indices = _MUNKRES.compute(cost_matrix)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ def _match_non_structured_lists(
model_cls=None,
field_name: str = "",
warn_selected: bool = False,
threshold: Optional[float] = None,
) -> List[tuple]:
"""Use the same raw-value matcher and class gate for scoring and direct reports."""
from stickler.algorithms.hungarian import HungarianMatcher
Expand All @@ -191,7 +192,10 @@ def _match_non_structured_lists(
comparator, model_cls=model_cls, field_name=field_name
)
matcher = HungarianMatcher(
element_comparator, match_threshold=0.0, normalize_values=False
element_comparator,
match_threshold=0.0,
normalize_values=False,
tie_break_threshold=threshold,
)
pairs = matcher.calculate_metrics(gt_list, pred_list)["matched_pairs"]
if warn_selected and isinstance(element_comparator, _ClassGatedComparator):
Expand Down Expand Up @@ -515,6 +519,7 @@ def compare_unordered_lists(
matched_pairs = _match_non_structured_lists(
gt_list, pred_list, comparator,
model_cls=model_cls, field_name=field_name, warn_selected=True,
threshold=threshold,
)

result = ComparisonHelper.unordered_list_metrics(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,15 @@ def get_match_threshold(self, obj_list: List[Any]) -> float:
def get_optimal_assignments(
self, gt_list: List[Any], pred_list: List[Any],
comparator: Optional[BaseComparator] = None,
match_threshold: Optional[float] = None,
) -> tuple:
"""Get optimal assignments and matched pairs with scores.

Args:
gt_list: Ground truth list
pred_list: Prediction list
comparator: Field comparator for non-structured list elements.
match_threshold: Field threshold, used to break assignment ties.

Returns:
Tuple of (assignments, matched_pairs_with_scores)
Expand All @@ -81,7 +83,7 @@ def get_optimal_assignments(
# Direct helper calls use the scoring matcher, but do not emit
# selected-pair warnings a second time.
matched_pairs_with_scores = _match_non_structured_lists(
gt_list, pred_list, comparator
gt_list, pred_list, comparator, threshold=match_threshold
)
assignments = [(i, j) for i, j, _ in matched_pairs_with_scores]

Expand Down Expand Up @@ -396,6 +398,7 @@ def collect_list_entries(
assignments, matched_pairs_with_scores = self.get_optimal_assignments(
gt_list, pred_list, **self._supported_options(
self.get_optimal_assignments, comparator=comparator,
match_threshold=match_threshold,
)
)
if match_threshold is None:
Expand Down
41 changes: 41 additions & 0 deletions tests/structured_object_evaluator/test_list_assignment_ties.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Tied optimal assignments must not make list scores depend on element order."""

from itertools import permutations
from typing import List

import pytest

from stickler import ComparableField, StructuredModel


class _Model(StructuredModel):
values: List[str] = ComparableField(threshold=0.7)


@pytest.mark.parametrize("clip", [True, False])
def test_tied_assignments_score_independently_of_element_order(clip):
class Model(StructuredModel):
values: List[str] = ComparableField(threshold=0.7, clip_under_threshold=clip)

gt = ["bcc", "caaa", "cbac"]
results = []
for gt_order in permutations(gt):
for pred_order in permutations(["baaa", "bbaa", "bbac"]):
result = Model(values=list(gt_order)).compare_with(
Model(values=list(pred_order)), include_confusion_matrix=True
)
overall = result["confusion_matrix"]["fields"]["values"]["overall"]
results.append((result["overall_score"], overall["tp"], overall["fd"]))

assert {(tp, fd) for _, tp, fd in results} == {(2, 1)}
assert [score for score, _, _ in results] == pytest.approx(
[results[0][0]] * len(results)
)


def test_tie_break_reports_the_pairs_that_were_counted():
result = _Model(values=["bcc", "caaa", "cbac"]).compare_with(
_Model(values=["baaa", "bbac", "bbaa"]), document_non_matches=True
)

assert len(result["non_matches"]) == 1