Skip to content

Fix #318 cannot pickle metrics #319

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

Merged
merged 3 commits into from
Sep 12, 2020
Merged
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 tests/run/executor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def test_train_loop(self):
save_every=[cond.time(seconds=10), cond.validation(better=True)],
train_metrics=[("loss", metric.RunningAverage(20)),
metric.F1(pred_name="preds", mode="macro"),
metric.Accuracy(pred_name="preds"),
metric.Accuracy[float](pred_name="preds"),
metric.LR(optimizer)],
optimizer=optimizer,
stop_training_on=cond.epoch(10),
Expand Down
16 changes: 16 additions & 0 deletions tests/run/metric/classification_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
Unit tests for classification related operations.
"""
import functools
import pickle
import unittest

import numpy as np
Expand Down Expand Up @@ -74,3 +75,18 @@ def test_f1(self):
self._test_metric(
metric, functools.partial(f1_score, average=mode),
binary=(mode == 'binary'))


class MetricPicklingTest(unittest.TestCase):
def test_pickle_unpickle(self):
metric = Accuracy(pred_name="123")
metric.add([1, 2, 3], [1, 2, 4])
metric_new = pickle.loads(pickle.dumps(metric))
self.assertEqual(metric.count, metric_new.count)
self.assertEqual(metric.correct, metric_new.correct)

metric = Accuracy[float](pred_name="123")
metric.add([1, 2, 3], [1, 2, 4])
metric_new = pickle.loads(pickle.dumps(metric))
self.assertEqual(metric.count, metric_new.count)
self.assertEqual(metric.correct, metric_new.correct)
19 changes: 17 additions & 2 deletions texar/torch/run/metric/base_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
"""
Base classes for Executor metrics.
"""

import sys
from abc import ABC, abstractmethod
from typing import Generic, List, Optional, Sequence, TypeVar
from typing import Generic, List, Optional, Sequence, TYPE_CHECKING, TypeVar

__all__ = [
"Metric",
Expand All @@ -27,6 +27,21 @@
Input = TypeVar('Input')
Value = TypeVar('Value')

if not TYPE_CHECKING and sys.version_info[:2] <= (3, 6):
# In Python 3.6 and below, pickling a `Generic` subclass that is specialized
# would cause an exception. To prevent troubles with `Executor` save & load,
# we use a dummy implementation of `Generic` through our home-brew
# `GenericMeta`.
from abc import ABCMeta # pylint: disable=ungrouped-imports

class GenericMeta(ABCMeta):
def __getitem__(cls, params):
# Whatever the parameters, just return the same class.
return cls

class Generic(metaclass=GenericMeta): # pylint: disable=function-redefined
pass


class Metric(Generic[Input, Value], ABC):
r"""Base class of all metrics. You should not directly inherit this class,
Expand Down