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

Add Metric <-> Lightning Module integration tests #4008

Merged
merged 3 commits into from
Oct 9, 2020
Merged
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
79 changes: 79 additions & 0 deletions tests/metrics/test_metric_lightning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import torch
from tests.base.boring_model import BoringModel
from pytorch_lightning.metrics import Metric
from pytorch_lightning import Trainer


class SumMetric(Metric):
def __init__(self):
super().__init__()
self.add_state("x", torch.tensor(0.0), dist_reduce_fx="sum")

def update(self, x):
self.x += x

def compute(self):
return self.x


def test_metric_lightning(tmpdir):
class TestModel(BoringModel):
def __init__(self):
super().__init__()
self.metric = SumMetric()
self.sum = 0.0

def training_step(self, batch, batch_idx):
ananyahjha93 marked this conversation as resolved.
Show resolved Hide resolved
x = batch
self.metric(x.sum())
self.sum += x.sum()

return self.step(x)

def training_epoch_end(self, outs):
assert torch.allclose(self.sum, self.metric.compute())
Copy link
Member

Choose a reason for hiding this comment

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

now much close, lets spec tolerance, also why not exact?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

default tolerance is 1e-8, i can parameterize if you want. Can't do exact bc of floating point

self.sum = 0.0

model = TestModel()
model.val_dataloader = None

trainer = Trainer(
default_root_dir=tmpdir,
limit_train_batches=2,
limit_val_batches=2,
max_epochs=2,
log_every_n_steps=1,
weights_summary=None,
)
trainer.fit(model)


def test_metric_lightning_log(tmpdir):
class TestModel(BoringModel):
def __init__(self):
super().__init__()
self.metric = SumMetric()
self.sum = 0.0

def training_step(self, batch, batch_idx):
x = batch
self.metric(x.sum())
self.sum += x.sum()
self.log("sum", self.metric, on_epoch=True, on_step=False)
return self.step(x)

model = TestModel()
model.val_dataloader = None

trainer = Trainer(
default_root_dir=tmpdir,
limit_train_batches=2,
limit_val_batches=2,
max_epochs=1,
log_every_n_steps=1,
weights_summary=None,
)
trainer.fit(model)

logged = trainer.logged_metrics
assert torch.allclose(torch.tensor(logged["sum"]), model.sum)