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

CompositionalMetric only returns value for last batch #644

Closed
Callidior opened this issue Nov 29, 2021 · 1 comment · Fixed by #645
Closed

CompositionalMetric only returns value for last batch #644

Callidior opened this issue Nov 29, 2021 · 1 comment · Fixed by #645
Labels
bug / fix Something isn't working help wanted Extra attention is needed

Comments

@Callidior
Copy link
Contributor

Callidior commented Nov 29, 2021

🐛 Bug

When using a compositional metric, i.e., metric_a + metric_b or 2 * metric_a with forward() instead of update(), the value returned by .compute() will be based only on the last batch.

This is because the default implementation of Metric.forward(), which is inherited by CompositionalMetric, calls reset(), which in turn resets all child metrics. Their state, however, is not restored by forward() afterwards.

My proposed fix would be to override forward() in CompositionalMetric and I will file a PR implementing this.

To Reproduce

Code sample

import torch
import torchmetrics
from torchmetrics.metric import CompositionalMetric

# Example predictions and targets
pred = torch.tensor([0.4, 0.2, 0.6, 0.7, 0.5])
target = torch.tensor([0.5, 0.4, 0.4, 0.3, 0.6])

# Compute base metric in batches
metric = torchmetrics.MeanSquaredError()
metric(preds=pred[:3], target=target[:3])
metric(preds=pred[3:], target=target[3:])
val = metric.compute()
print(val)

# Compute compositional metric in batches
cm = 1 * torchmetrics.MeanSquaredError()
cm(preds=pred[:3], target=target[:3])
cm(preds=pred[3:], target=target[3:])
val = cm.compute()
print(val)

Expected behavior

Two identical values are printed:

tensor(0.0520)
tensor(0.0520)

Actual (faulty) behavior

The compositional metric only returns the value for the last batch:

tensor(0.0520)
tensor(0.0850)

Environment

  • PyTorch Version (e.g., 1.0): 1.10.0
  • OS (e.g., Linux): Linux
  • How you installed PyTorch (conda, pip, source): conda
  • Build command you used (if compiling from source):
  • Python version: 3.8
  • CUDA/cuDNN version: 11.1
  • GPU models and configuration:
  • Any other relevant information:

Additional context

@Callidior Callidior added bug / fix Something isn't working help wanted Extra attention is needed labels Nov 29, 2021
@github-actions
Copy link

Hi! thanks for your contribution!, great first issue!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug / fix Something isn't working help wanted Extra attention is needed
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant