mirror of
https://github.com/wassname/pytorch-lightning.git
synced 2026-09-10 12:21:57 +08:00
* New metric classes (#1326) * Create metrics package * Create metric.py * Create utils.py * Create __init__.py * add tests for metric utils * add docstrings for metrics utils * add function to recursively apply other function to collection * add tests for this function * update test * Update pytorch_lightning/metrics/metric.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * update metric name * remove example docs * fix tests * add metric tests * fix to tensor conversion * fix apply to collection * Update CHANGELOG.md * Update pytorch_lightning/metrics/metric.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * remove tests from init * add missing type annotations * rename utils to convertors * Create metrics.rst * Update index.rst * Update index.rst * Update pytorch_lightning/metrics/convertors.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * Update pytorch_lightning/metrics/convertors.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * Update pytorch_lightning/metrics/convertors.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * Update pytorch_lightning/metrics/metric.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * Update tests/utilities/test_apply_to_collection.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * Update tests/utilities/test_apply_to_collection.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * Update tests/metrics/convertors.py Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * add doctest example * rename file and fix imports * added parametrized test * replace lambda with inlined function * rename apply_to_collection to apply_func * Separated class description from init args * Apply suggestions from code review Co-Authored-By: Jirka Borovec <Borda@users.noreply.github.com> * adjust random values * suppress output when seeding * remove gpu from doctest * Add requested changes and add ellipsis for doctest * forgot to push these files... * add explicit check for dtype to convert to * fix ddp tests * remove explicit ddp destruction Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> * move dtype device mixin to more general place * refactor to general device dtype mixin * add initial metric package description * change default to none for mac os * pep8 * fix import * Update index.rst * Update ci-testing.yml * Apply suggestions from code review Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> * Update CHANGELOG.md * Update pytorch_lightning/metrics/converters.py * readme * Update metric.py * Update pytorch_lightning/metrics/converters.py Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> Co-authored-by: Jirka <jirka@pytorchlightning.ai>
104 lines
3.6 KiB
Python
104 lines
3.6 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Any, Optional, Union
|
|
|
|
import torch
|
|
import torch.distributed
|
|
|
|
from pytorch_lightning.metrics.converters import tensor_metric, numpy_metric
|
|
from pytorch_lightning.utilities.apply_func import apply_to_collection
|
|
from pytorch_lightning.utilities.device_dtype_mixin import DeviceDtypeModuleMixin
|
|
|
|
__all__ = ['Metric', 'TensorMetric', 'NumpyMetric']
|
|
|
|
|
|
class Metric(DeviceDtypeModuleMixin, torch.nn.Module, ABC):
|
|
"""
|
|
Abstract base class for metric implementation.
|
|
|
|
Should be used to implement metrics that
|
|
1. Return multiple Outputs
|
|
2. Handle their own DDP sync
|
|
"""
|
|
def __init__(self, name: str):
|
|
"""
|
|
Args:
|
|
name: the metric's name
|
|
|
|
"""
|
|
super().__init__()
|
|
self.name = name
|
|
self._dtype = torch.get_default_dtype()
|
|
self._device = torch.device('cpu')
|
|
|
|
@abstractmethod
|
|
def forward(self, *args, **kwargs) -> torch.Tensor:
|
|
"""
|
|
Implements the actual metric computation.
|
|
|
|
Returns:
|
|
metric value
|
|
|
|
"""
|
|
raise NotImplementedError
|
|
|
|
|
|
class TensorMetric(Metric):
|
|
"""
|
|
Base class for metric implementation operating directly on tensors.
|
|
All inputs and outputs will be casted to tensors if necessary.
|
|
Already handles DDP sync and input/output conversions.
|
|
"""
|
|
def __init__(self, name: str,
|
|
reduce_group: Optional[Any] = None,
|
|
reduce_op: Optional[Any] = None):
|
|
"""
|
|
|
|
Args:
|
|
name: the metric's name
|
|
reduce_group: the process group for DDP reduces (only needed for DDP training).
|
|
Defaults to all processes (world)
|
|
reduce_op: the operation to perform during reduction within DDP (only needed for DDP training).
|
|
Defaults to sum.
|
|
"""
|
|
super().__init__(name)
|
|
self._orig_call = tensor_metric(group=reduce_group,
|
|
reduce_op=reduce_op)(super().__call__)
|
|
|
|
def __call__(self, *args, **kwargs) -> torch.Tensor:
|
|
def _to_device_dtype(x: torch.Tensor) -> torch.Tensor:
|
|
return x.to(device=self.device, dtype=self.dtype, non_blocking=True)
|
|
|
|
return apply_to_collection(self._orig_call(*args, **kwargs), torch.Tensor,
|
|
_to_device_dtype)
|
|
|
|
|
|
class NumpyMetric(Metric):
|
|
"""
|
|
Base class for metric implementation operating on numpy arrays.
|
|
All inputs will be casted to numpy if necessary and all outputs will
|
|
be casted to tensors if necessary.
|
|
Already handles DDP sync and input/output conversions.
|
|
"""
|
|
def __init__(self, name: str,
|
|
reduce_group: Optional[Any] = None,
|
|
reduce_op: Optional[Any] = None):
|
|
"""
|
|
|
|
Args:
|
|
name: the metric's name
|
|
reduce_group: the process group for DDP reduces (only needed for DDP training).
|
|
Defaults to all processes (world)
|
|
reduce_op: the operation to perform during reduction within DDP (only needed for DDP training).
|
|
Defaults to sum.
|
|
"""
|
|
super().__init__(name)
|
|
self._orig_call = numpy_metric(group=reduce_group,
|
|
reduce_op=reduce_op)(super().__call__)
|
|
|
|
def __call__(self, *args, **kwargs) -> torch.Tensor:
|
|
def _to_device_dtype(x: torch.Tensor) -> torch.Tensor:
|
|
return x.to(device=self.device, dtype=self.dtype, non_blocking=True)
|
|
|
|
return apply_to_collection(self._orig_call(*args, **kwargs), torch.Tensor,
|
|
_to_device_dtype)
|