Skip to content
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

fix for MetricCollection.update gives identical results #2944

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

-
- Fixed `MetricCollection.update` gives identical results ([#2944](https://github.com/Lightning-AI/torchmetrics/issues/2944))


---
Expand Down
6 changes: 4 additions & 2 deletions src/torchmetrics/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,10 +315,12 @@ def _equal_metric_states(metric1: Metric, metric2: Metric) -> bool:
return False

if isinstance(state1, Tensor) and isinstance(state2, Tensor):
return state1.shape == state2.shape and allclose(state1, state2)
if not (state1.shape == state2.shape and allclose(state1, state2)):
return False

if isinstance(state1, list) and isinstance(state2, list):
return all(s1.shape == s2.shape and allclose(s1, s2) for s1, s2 in zip(state1, state2))
if not (all(s1.shape == s2.shape and allclose(s1, s2) for s1, s2 in zip(state1, state2))):
return False

return True

Expand Down
32 changes: 32 additions & 0 deletions tests/unittests/bases/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -743,3 +743,35 @@ def compute(self):
# Print the calculated metrics
assert "my_prefix/accuracy/my_postfix" in res
assert "my_prefix/precision/my_postfix" in res


def test_collection_update():
"""Test that metric collection updates metrics.

See issue: https://github.com/Lightning-AI/torchmetrics/issues/2916

"""
from torchmetrics.text import BLEUScore

scores = MetricCollection({
"bleu-1": BLEUScore(1),
"bleu-2": BLEUScore(2),
"bleu-3": BLEUScore(3),
"bleu-4": BLEUScore(4),
})

preds = ["the cat is on the mat"]
target = [["there is a cat on the mat", "a cat is on the mat"]]

scores.update(preds, target)
actual = scores.compute()

expected = {
"bleu-1": torch.tensor(0.8333),
"bleu-2": torch.tensor(0.8165),
"bleu-3": torch.tensor(0.7937),
"bleu-4": torch.tensor(0.7598),
}

for k, v in expected.items():
torch.testing.assert_close(actual=actual.get(k), expected=v, rtol=1e-4, atol=1e-4)
Loading