Skip to content

Commit

Permalink
Fix: Allow hashing of metrics with lists in their state (#5939)
Browse files Browse the repository at this point in the history
* Fix: Allow hashing of metrics with lists in their state

* Add test case and modify semantics of Metric __hash__ in order to be compatible with structural equality checks

* Fix pep8 style issue

Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Feb 18, 2021
1 parent bfcfac4 commit 77f6aa4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
8 changes: 7 additions & 1 deletion pytorch_lightning/metrics/metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,13 @@ def __hash__(self):
hash_vals = [self.__class__.__name__]

for key in self._defaults.keys():
hash_vals.append(getattr(self, key))
val = getattr(self, key)
# Special case: allow list values, so long
# as their elements are hashable
if hasattr(val, '__iter__') and not isinstance(val, torch.Tensor):
hash_vals.extend(val)
else:
hash_vals.append(val)

return hash(tuple(hash_vals))

Expand Down
26 changes: 26 additions & 0 deletions tests/metrics/test_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,32 @@ def compute(self):
assert a.compute() == 5


def test_hash():

class A(Dummy):
pass

class B(DummyList):
pass

a1 = A()
a2 = A()
assert hash(a1) != hash(a2)

b1 = B()
b2 = B()
assert hash(b1) == hash(b2)
assert isinstance(b1.x, list) and len(b1.x) == 0
b1.x.append(torch.tensor(5))
assert isinstance(hash(b1), int) # <- check that nothing crashes
assert isinstance(b1.x, list) and len(b1.x) == 1
b2.x.append(torch.tensor(5))
# Sanity:
assert isinstance(b2.x, list) and len(b2.x) == 1
# Now that they have tensor contents, they should have different hashes:
assert hash(b1) != hash(b2)


def test_forward():

class A(Dummy):
Expand Down

0 comments on commit 77f6aa4

Please sign in to comment.