Repository navigation
docs(521): replace history-narrating comments with the rule they protect #674
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
base: dev
Are you sure you want to change the base?
Changes from 1 commit
87a781b
ac57e13
856406d
3772fa4
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 |
|---|---|---|
|
|
@@ -9,7 +9,7 @@ The Structured Object Evaluator is designed to compare complex, nested data stru | |
| Key components: | ||
| - **StructuredModel**: Base class for defining structured data models | ||
| - **ComparableField**: Field descriptor for configuring comparison behavior | ||
| - **ANLSTree**: Tree-based representation for structured objects | ||
| - **ANLSTree** (in `trees/`): an alternate, parallel evaluation path — see [#135](https://github.com/awslabs/stickler/issues/135) | ||
| - **Utility functions**: For calculating ANLS scores and handling key scores | ||
|
|
||
| ## Installation | ||
|
|
@@ -389,131 +389,20 @@ Available comparators: | |
|
|
||
| ## API Reference | ||
|
|
||
| ### StructuredModel | ||
|
|
||
| ```python | ||
| class StructuredModel(BaseModel): | ||
| """Base class for structured data models with comparison capabilities.""" | ||
|
|
||
| def compare_with(self, other: 'StructuredModel') -> Dict[str, Any]: | ||
| """ | ||
| Compare this model with another model. | ||
| Args: | ||
| other: Another StructuredModel to compare with | ||
| Returns: | ||
| Dictionary with comparison results | ||
| """ | ||
|
|
||
| @classmethod | ||
| def from_json(cls, json_obj: Dict[str, Any]) -> 'StructuredModel': | ||
| """ | ||
| Create a model instance from a JSON object. | ||
| Args: | ||
| json_obj: JSON object to convert | ||
| Returns: | ||
| StructuredModel instance | ||
| """ | ||
|
|
||
| @classmethod | ||
| def from_json_schema(cls, schema: Dict[str, Any]) -> Type['StructuredModel']: | ||
| """ | ||
| Create a StructuredModel subclass from a JSON Schema document. | ||
| Args: | ||
| schema: JSON Schema document (Draft 7 compatible) | ||
| Returns: | ||
| New StructuredModel subclass | ||
| Example: | ||
| >>> schema = { | ||
| ... "type": "object", | ||
| ... "title": "Product", | ||
| ... "properties": { | ||
| ... "name": {"type": "string"}, | ||
| ... "price": {"type": "number"} | ||
| ... }, | ||
| ... "required": ["name", "price"] | ||
| ... } | ||
| >>> Product = StructuredModel.from_json_schema(schema) | ||
| >>> product = Product(name="Widget", price=9.99) | ||
| """ | ||
| ``` | ||
|
|
||
| ### Utility Functions | ||
|
|
||
| ```python | ||
| def anls_score( | ||
| gt: Any, | ||
| pred: Any, | ||
| return_gt: bool = False, | ||
| return_key_scores: bool = False | ||
| ) -> Union[float, Tuple[float, Any], Tuple[float, Any, Dict[str, Any]]]: | ||
| """ | ||
| Calculate ANLS score between two objects. | ||
| Args: | ||
| gt: Ground truth object | ||
| pred: Prediction object | ||
| return_gt: Whether to return the closest ground truth | ||
| return_key_scores: Whether to return detailed key scores | ||
| Returns: | ||
| Either just the overall score (float), or a tuple with the score and | ||
| closest ground truth, or a tuple with the score, closest ground truth, | ||
| and key scores. | ||
| """ | ||
|
|
||
| def compare_json( | ||
| gt_json: Dict[str, Any], | ||
| pred_json: Dict[str, Any], | ||
| model_cls: Type[StructuredModel] | ||
| ) -> Dict[str, Any]: | ||
| """ | ||
| Compare JSON objects using a StructuredModel. | ||
| Args: | ||
| gt_json: Ground truth JSON | ||
| pred_json: Prediction JSON | ||
| model_cls: StructuredModel class to use for comparison | ||
| Returns: | ||
| Dictionary with comparison results | ||
| """ | ||
| ``` | ||
| See the generated [API reference](https://awslabs.github.io/stickler/API-Reference/api/) for | ||
| `StructuredModel`, `anls_score`, and `compare_json` with their full signatures and options — | ||
| including `compare_with`'s options and `anls_score`'s `threshold` parameter, both missing from | ||
| this section previously. | ||
|
|
||
| ## Performance Optimizations | ||
|
|
||
| ### Hungarian Matching Optimization (2025) | ||
|
|
||
| The Structured Object Evaluator has been optimized to eliminate redundant Hungarian matching operations for list comparisons. Previously, the system performed 4-5 separate Hungarian matching calculations per list field, leading to O(n²) complexity for list-heavy comparisons. | ||
|
|
||
| **Optimization Details:** | ||
| - **Problem**: Multiple calls to `get_matched_pairs_with_scores()`, `get_assignments()`, and `get_unmatched_indices()` for the same list pairs | ||
| - **Solution**: Consolidated to single `get_complete_matching_info()` call that returns all required information | ||
| - **Performance Impact**: 60-75% improvement for comparisons with multiple list fields | ||
| - **Backward Compatibility**: All existing APIs maintained, optimization is transparent to users | ||
|
|
||
| **Files Modified:** | ||
| - `hungarian_helper.py`: Added unified `get_complete_matching_info()` method | ||
| - `structured_model.py`: Updated to use single Hungarian matching call | ||
| - `structured_list_comparator.py`: Optimized list comparison logic | ||
| - `comparison_helper.py`: Updated helper methods | ||
| - `evaluator_format_helper.py`: Updated evaluator formatting | ||
|
|
||
| **Testing**: All 374 existing tests pass, ensuring no regression in functionality. | ||
|
|
||
| ### Post-Processing Architecture | ||
|
|
||
| The comparison pipeline uses a constructive building approach in `compare_recursive()` followed by lightweight post-processing transformations: | ||
|
|
||
| 1. **Primary Traversal**: `compare_recursive()` builds the comparison tree structure efficiently | ||
| 2. **Aggregate Metrics**: `AggregateMetricsCalculator.calculate_aggregate_metrics()` adds Universal Aggregate Field data | ||
| 3. **Derived Metrics**: `_add_derived_metrics_to_result()` adds precision, recall, F1 scores | ||
| 3. **Derived Metrics**: `DerivedMetricsCalculator.add_derived_metrics_to_result` adds precision, recall, F1 scores | ||
|
|
||
| This architecture prioritizes correctness of the core comparison logic while keeping post-processing transformations simple and maintainable. The post-processing steps operate on already-computed confusion matrix data and represent a small fraction of total computation time. | ||
|
|
||
|
|
@@ -524,9 +413,12 @@ See the [examples](../../../examples/key_information_evaluation/structured_objec | |
| ## Known Limitations | ||
|
|
||
| ### Dictionary Fields | ||
| Dictionary fields (`Dict[str, Any]`) with text-based comparators like `LevenshteinComparator` are not supported as they would produce unpredictable results. | ||
| A `Dict[str, Any]` field given a text comparator like `LevenshteinComparator` warns once and | ||
| scores 0.0 rather than comparing meaningfully (see [#297](https://github.com/awslabs/stickler/issues/297)). | ||
| A dict field with no comparator named gets `ANLSStarComparator` instead. | ||
|
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. Required. This new text is right, but the example 7 lines below still says Measured on Please change
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. Fixed in ac57e13 |
||
|
|
||
| **Solution**: Create proper StructuredModel subclasses instead of using raw dictionaries. | ||
| **Recommended**: define a `StructuredModel` subclass instead of a raw dict, so each key gets | ||
| its own configured comparator. | ||
|
|
||
| **Example**: | ||
| ```python | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -31,63 +31,17 @@ class _ClassGatedComparator(BaseComparator): | |||||||||||||||||||
| """Applies the object-pair gate to a list element, else delegates. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| List elements reach a comparator through the Hungarian cost matrix, which | ||||||||||||||||||||
| sees values and knows nothing about the field. Wrapping the comparator is | ||||||||||||||||||||
| what makes a list element obey the same rules as the singular form: both | ||||||||||||||||||||
| then read the same configured comparator, with the same gate in front of it. | ||||||||||||||||||||
| Without this, `Single(pet=Cat('rex'))` against `Dog('rev')` scored 0.0 while | ||||||||||||||||||||
| `Listed(pets=[Cat('rex')])` against `[Dog('rex')]` scored 1.0 -- the parity | ||||||||||||||||||||
| #319 exists to establish, broken in the opposite direction. See #321 for | ||||||||||||||||||||
| whether a refused element should pair at all. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| The gate itself is `ConfigurationHelper.can_compare_object_pair`, the same | ||||||||||||||||||||
| call `ComparisonDispatcher` CASE 4/CASE 5 and both `compare_field_raw` | ||||||||||||||||||||
| readers make, so an element and a singular value are judged by one rule. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| Installed when at least one element of EITHER list is a plain model, so the | ||||||||||||||||||||
| ordinary primitive-list path keeps its cost-matrix hot loop unwrapped. The | ||||||||||||||||||||
| LIST is what qualifies for wrapping; which PAIRS are then judged is | ||||||||||||||||||||
| `_judges`, and it is a pair with a plain model on at least one side. A pair | ||||||||||||||||||||
| with a plain model on neither -- dict against dict, `StructuredModel` against | ||||||||||||||||||||
| `StructuredModel` -- is delegated untouched. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| That narrowing is the whole correctness of this wrapper, and it was wrong in | ||||||||||||||||||||
| both directions before. Judging every pair because the list qualified made an | ||||||||||||||||||||
| element's verdict depend on what ELSE the list happened to hold: | ||||||||||||||||||||
|
|
||||||||||||||||||||
| f: Optional[List[Any]] dev list-wide gate | ||||||||||||||||||||
| [{'a':1},{'b':2},{'c':3}] 1.0 1.0 | ||||||||||||||||||||
| [{'a':1},{'b':2},{'c':3}, Plain('p')] 1.0 0.0 <- fd on all four | ||||||||||||||||||||
| [NoteSM] vs [Note2SM] 1.0 1.0 | ||||||||||||||||||||
| [Plain, NoteSM] vs [Plain, Note2SM] 1.0 0.0 | ||||||||||||||||||||
| same, with a comparator declared on `f` 1.0 0.5 | ||||||||||||||||||||
|
|
||||||||||||||||||||
| The dict row zeroed three elements that score 1.0 on their own, in the same | ||||||||||||||||||||
| list, on `dev`, and here the moment the plain model is removed -- and it drew | ||||||||||||||||||||
| a "holds a mapping" warning on a field whose annotation says nothing about | ||||||||||||||||||||
| mappings. The two `[Plain, NoteSM]` rows are worse than wrong-looking: both | ||||||||||||||||||||
| enforce the cross-class rule that #327 is explicitly holding open (the bare | ||||||||||||||||||||
| row's 0.0 is fd=2, the refused `Plain` pair plus `NoteSM`/`Note2SM`; with | ||||||||||||||||||||
| `[Plain, NoteSM]` on both sides it scores 0.5), so a user got the #327 answer | ||||||||||||||||||||
| or the documented one according to whether an unrelated plain model shared | ||||||||||||||||||||
| the list. Both rules now apply to exactly the population the wrapper was | ||||||||||||||||||||
| installed for. The declared row now scores 1.0; the bare row scores 0.5, | ||||||||||||||||||||
| because the bare annotation still refuses the `Plain` pair on its own | ||||||||||||||||||||
| (`[Plain]` vs `[Plain]` scores 0.0), not because of the cross-class rule. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| A dict element does not reach the gate -- neither because | ||||||||||||||||||||
| `_holds_a_plain_model` does not look for one, which was the old and only | ||||||||||||||||||||
| conditionally true reason, nor by accident: `_is_plain_model` is asked of both | ||||||||||||||||||||
| sides here. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| WARNING TIMING. The matcher asks this comparator for every cell of the cost | ||||||||||||||||||||
| matrix and keeps one per row, so warning from inside `_compare` announced an | ||||||||||||||||||||
| outcome that never happened -- an identical `[Plain('aaa'), Note('bbb')]` pair | ||||||||||||||||||||
| scored 1.0 with `tp=2` and still warned that a `Plain` had been compared | ||||||||||||||||||||
| against a `Note`, from the cross cell the matcher discarded. Worse, `warn_once` | ||||||||||||||||||||
| spends one message per field for the life of the process, so that probe cell | ||||||||||||||||||||
| silenced the genuine wrong-class prediction later in the same corpus. Probing | ||||||||||||||||||||
| is therefore silent, and `warn_for_selected` replays the gate on the pairs the | ||||||||||||||||||||
| matcher actually chose. | ||||||||||||||||||||
| sees values, not the field, so without this wrapper a list element skips | ||||||||||||||||||||
| the gate that a singular field value goes through (#319). Installed when | ||||||||||||||||||||
| at least one element of EITHER list is a plain model; `_judges` below | ||||||||||||||||||||
| decides which PAIRS it then applies to (a pair with a plain model on at | ||||||||||||||||||||
| least one side, #327's cross-class rule otherwise left alone, see #321). | ||||||||||||||||||||
|
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. For vawsgit's #321 note, a wording that keeps #321 apart from the pair rule and says which pairs are delegated untouched:
Suggested change
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| Warnings are replayed against the matcher's chosen pairs rather than raised from | ||||||||||||||||||||
| inside `_compare`: the matcher probes every cell of the cost matrix, including pairs | ||||||||||||||||||||
| it never selects, and `warn_once` only fires once per field for the process's life | ||||||||||||||||||||
| so warning from a probe-and-discarded cell could silence the real warning for a pair | ||||||||||||||||||||
| the matcher actually picks. | ||||||||||||||||||||
| """ | ||||||||||||||||||||
|
|
||||||||||||||||||||
| def __init__(self, inner: BaseComparator, model_cls=None, field_name: str = ""): | ||||||||||||||||||||
|
|
@@ -454,13 +408,13 @@ def compare_unordered_lists( | |||||||||||||||||||
| isinstance(item, StructuredModel) for item in gt_list[:1] + pred_list[:1] | ||||||||||||||||||||
| ): | ||||||||||||||||||||
| # For StructuredModel lists, we need to use individual comparison scoring for consistency | ||||||||||||||||||||
| # Use HungarianHelper to get optimal pairings - OPTIMIZED: Single call gets all info | ||||||||||||||||||||
| # Use HungarianHelper to get optimal pairings: a single call returns matched pairs and scores | ||||||||||||||||||||
| hungarian_info = hungarian_helper.get_complete_matching_info( | ||||||||||||||||||||
| gt_list, pred_list | ||||||||||||||||||||
| ) | ||||||||||||||||||||
| matched_pairs = hungarian_info["matched_pairs"] | ||||||||||||||||||||
|
|
||||||||||||||||||||
| # CRITICAL FIX: Replace raw scores with threshold-applied scores from individual comparison | ||||||||||||||||||||
| # Replace raw scores with threshold-applied scores from individual comparison | ||||||||||||||||||||
| # This ensures consistency between individual and list comparison results | ||||||||||||||||||||
| threshold_corrected_pairs = [] | ||||||||||||||||||||
| for gt_idx, pred_idx, raw_score in matched_pairs: | ||||||||||||||||||||
|
|
@@ -487,7 +441,7 @@ def compare_unordered_lists( | |||||||||||||||||||
| ) | ||||||||||||||||||||
| else: | ||||||||||||||||||||
| # Use the provided comparator for other types | ||||||||||||||||||||
| # CRITICAL FIX: Use match_threshold=0.0 to capture ALL matches, not just those above threshold | ||||||||||||||||||||
| # 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. | ||||||||||||||||||||
| # | ||||||||||||||||||||
| # `0.0` is a capture-all sentinel: only `matched_pairs` is read | ||||||||||||||||||||
|
|
@@ -586,7 +540,7 @@ def unordered_list_metrics( | |||||||||||||||||||
| # Total false positives include both false discoveries and false alarms | ||||||||||||||||||||
| fp = fd + fa | ||||||||||||||||||||
|
|
||||||||||||||||||||
| # CRITICAL FIX: Use threshold-applied scores for consistency with individual comparison | ||||||||||||||||||||
| # Use threshold-applied scores for consistency with individual comparison | ||||||||||||||||||||
| # This ensures list comparison matches the same scoring logic as individual comparison | ||||||||||||||||||||
| if not matched_pairs: | ||||||||||||||||||||
| # Two empty lists agree perfectly: there is nothing to find and | ||||||||||||||||||||
|
|
||||||||||||||||||||
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.
StructuredModelandcompare_withrender on the Models page.API-Reference/api/has onlycompare_structured_models,anls_scoreandcompare_json, and its own tip sends readers on to Models. This also drops the "previously" clause: