Machine learning metrics for distributed, scalable PyTorch applications.
Перейти к файлу
Alan Du da0017410c
Add AverageMeter implementation (#138)
* Add AverageMeter

* Fix type annotation to accomodate Python 3.6 bug

* Add tests

* Update changelog

* Add AverageMeter to docs

* fixup! Add AverageMeter to docs

* Code review comments

* Add tests for scalar case

* Fix behavior on PyTorch <1.8

* fixup! Add tests for scalar case

* fixup! fixup! Add tests for scalar case

* Update CHANGELOG.md

* Add Pearson correlation coefficient (#157)

* init files

* rest

* pep8

* changelog

* clamp

* suggestions

* rename

* format

* _sk_pearsonr

* inline

* fix sync

* fix tests

* fix docs

* Apply suggestions from code review

* Update torchmetrics/functional/regression/pearson.py

* atol

* update

* pep8

* pep8

* chlog

* .

Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: Jirka Borovec <jirka.borovec@seznam.cz>

* Spearman correlation coefficient (#158)

* ranking

* init files

* update

* nearly working

* fix tests

* pep8

* add docs

* fix doctests

* fix docs

* pep8

* isort

* ghlog

* Apply suggestions from code review

Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>

* Added changes for Test Differentiability [1/n] (#154)

* added test changes

* fix style error

* fixed typo

* added changes for requires_grad

* metrics differentiability testing generalization

* Update tests/classification/test_accuracy.py

Co-authored-by: Nicki Skafte <skaftenicki@gmail.com>

* fix tests

* pep8

* changelog

* fix docs

* fix tests

* pep8

* Apply suggestions from code review

Co-authored-by: Nicki Skafte <skaftenicki@gmail.com>
Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>

* Binned PR-related metrics (#128)

* WIP: Binned PR-related metrics

* attempt to fix types

* switch to linspace to make old pytorch happy

* make flake happy

* clean up

* Add more testing, move test input generation to the approproate place

* bugfixes and more stable and thorough tests

* flake8

* Reuse python zip-based implementation as it can't be reproduced with torch.where/max

* address comments

* isort

* Add docs and doctests, make APIs same as non-binned versions

* pep8

* isort

* doctests likes longer title underlines :O

* use numpy's nan_to_num

* add atol to bleu tests to make them more stable

* atol=1e-2 for bleu

* add more docs

* pep8

* remove nlp test hack

* address comments

* pep8

* abc

* flake8

* remove typecheck

* chlog

Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: Nicki Skafte <skaftenicki@gmail.com>
Co-authored-by: Jirka Borovec <jirka.borovec@seznam.cz>

* version + about (#170)

* version + about

* flake8

* try

* .

* fix doc

* overload sig

* fix

* Different import style

Co-authored-by: Nicki Skafte <skaftenicki@gmail.com>
Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: Jirka Borovec <jirka.borovec@seznam.cz>
Co-authored-by: Bhadresh Savani <bhadreshpsavani@gmail.com>
Co-authored-by: Maxim Grechkin <maximsch2@gmail.com>
2021-04-14 18:51:58 +00:00
.github Add testing agains each feat PT version (#127) 2021-03-25 20:44:26 +01:00
docs Add AverageMeter implementation (#138) 2021-04-14 18:51:58 +00:00
integrations Add testing agains each feat PT version (#127) 2021-03-25 20:44:26 +01:00
requirements Fix to blau score (#165) 2021-04-09 08:43:49 +00:00
tests Add AverageMeter implementation (#138) 2021-04-14 18:51:58 +00:00
torchmetrics Add AverageMeter implementation (#138) 2021-04-14 18:51:58 +00:00
.codecov.yml update codecov 2021-03-27 09:07:13 +01:00
.gitignore Refactor Information Retrieval tests (#156) 2021-04-06 13:26:52 +00:00
.mergify.yml Initial commit 2020-12-22 21:02:46 +01:00
.pep8speaks.yml Initial commit 2020-12-22 21:02:46 +01:00
.pre-commit-config.yaml Feature pre commit yaml (#145) 2021-03-30 10:46:24 +02:00
.readthedocs.yml Refactor requirements (#130) 2021-03-25 08:51:38 +01:00
CHANGELOG.md Add AverageMeter implementation (#138) 2021-04-14 18:51:58 +00:00
LICENSE take over Apache-2.0 2021-02-24 12:05:16 +01:00
MANIFEST.in Feature pre commit yaml (#145) 2021-03-30 10:46:24 +02:00
Makefile Refactor requirements (#130) 2021-03-25 08:51:38 +01:00
README.md formatting 2021-04-06 09:58:39 +02:00
azure-pipelines.yml Add testing agains each feat PT version (#127) 2021-03-25 20:44:26 +01:00
pyproject.toml mypy 2021-02-22 10:43:07 +01:00
requirements.txt version + about (#170) 2021-04-14 10:13:42 +02:00
setup.cfg Add testing agains each feat PT version (#127) 2021-03-25 20:44:26 +01:00
setup.py version + about (#170) 2021-04-14 10:13:42 +02:00

README.md

Machine learning metrics for distributed, scalable PyTorch applications.


What is TorchmetricsImplementing a metricBuilt-in metricsDocsCommunityLicense


PyPI - Python Version PyPI Status PyPI Status Conda Slack license

CI testing - base Build Status codecov Documentation Status


Installation

Simple installation from PyPI

pip install torchmetrics
Other installations

Install using conda

conda install torchmetrics

Pip from source

# with git
pip install git+https://github.com/PytorchLightning/metrics.git@master

Pip from archive

pip install https://github.com/PyTorchLightning/metrics/archive/master.zip

What is Torchmetrics

TorchMetrics is a collection of 25+ PyTorch metrics implementations and an easy-to-use API to create custom metrics. It offers:

  • A standardized interface to increase reproducibility
  • Reduces boilerplate
  • Automatic accumulation over batches
  • Metrics optimized for distributed-training
  • Automatic synchronization between multiple devices

You can use TorchMetrics with any PyTorch model or with PyTorch Lightning to enjoy additional features such as:

  • Module metrics are automatically placed on the correct device.
  • Native support for logging metrics in Lightning to reduce even more boilerplate.

Using TorchMetrics

Module metrics

The module-based metrics contain internal metric states (similar to the parameters of the PyTorch module) that automate accumulation and synchronization across devices!

  • Automatic accumulation over multiple batches
  • Automatic synchronization between multiple devices
  • Metric arithmetic

This can be run on CPU, single GPU or multi-GPUs!

For the single GPU/CPU case:

import torch
# import our library
import torchmetrics 

# initialize metric
metric = torchmetrics.Accuracy()

n_batches = 10
for i in range(n_batches):
    # simulate a classification problem
    preds = torch.randn(10, 5).softmax(dim=-1)
    target = torch.randint(5, (10,))

    # metric on current batch
    acc = metric(preds, target)
    print(f"Accuracy on batch {i}: {acc}")    

# metric on all batches using custom accumulation
acc = metric.compute()
print(f"Accuracy on all data: {acc}")

Module metric usage remains the same when using multiple GPUs or multiple nodes.

Example using DDP

import os
import torch
from torch import nn
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
import torchmetrics

def metric_ddp(rank, world_size):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'

    # create default process group
    dist.init_process_group("gloo", rank=rank, world_size=world_size)

    # initialize model
    metric = torchmetrics.Accuracy()

    # define a model and append your metric to it
    # this allows metric states to be placed on correct accelerators when
    # .to(device) is called on the model
    model = nn.Linear(10, 10)
    model.metric = metric
    model = model.to(rank)

    # initialize DDP
    model = DDP(model, device_ids=[rank])

    n_epochs = 5
    # this shows iteration over multiple training epochs
    for n in range(n_epochs):

        # this will be replaced by a DataLoader with a DistributedSampler
        n_batches = 10
        for i in range(n_batches):
            # simulate a classification problem
            preds = torch.randn(10, 5).softmax(dim=-1)
            target = torch.randint(5, (10,))

            # metric on current batch
            acc = metric(preds, target)
            if rank == 0:  # print only for rank 0
                print(f"Accuracy on batch {i}: {acc}")    

        # metric on all batches and all accelerators using custom accumulation
        # accuracy is same across both accelerators
        acc = metric.compute()
        print(f"Accuracy on all data: {acc}, accelerator rank: {rank}")

        # Reseting internal state such that metric ready for new data
        metric.reset()
    
    # cleanup
    dist.destroy_process_group()

if __name__ == "__main__":
    world_size = 2   # number of gpus to parallize over
    mp.spawn(metric_ddp, args=(world_size,), nprocs=world_size, join=True)

Implementing your own Module metric

Implementing your own metric is as easy as subclassing an torch.nn.Module. Simply, subclass torchmetrics.Metric and implement the following methods:

import torch
from torchmetrics import Metric

class MyAccuracy(Metric):
    def __init__(self, dist_sync_on_step=False):
        # call `self.add_state`for every internal state that is needed for the metrics computations
	# dist_reduce_fx indicates the function that should be used to reduce 
	# state from multiple processes
	super().__init__(dist_sync_on_step=dist_sync_on_step)

        self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum")
        self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")

    def update(self, preds: torch.Tensor, target: torch.Tensor):
        # update metric states
        preds, target = self._input_format(preds, target)
        assert preds.shape == target.shape

        self.correct += torch.sum(preds == target)
        self.total += target.numel()

    def compute(self):
        # compute final result
        return self.correct.float() / self.total

Functional metrics

Similar to torch.nn, most metrics have both a module-based and a functional version. The functional versions are simple python functions that as input take torch.tensors and return the corresponding metric as a torch.tensor.

import torch
# import our library
import torchmetrics

# simulate a classification problem
preds = torch.randn(10, 5).softmax(dim=-1)
target = torch.randint(5, (10,))

acc = torchmetrics.functional.accuracy(preds, target)

Implemented metrics

And many more!

Contribute!

The lightning + torchmetric team is hard at work adding even more metrics. But we're looking for incredible contributors like you to submit new metrics and improve existing ones!

Join our Slack to get help becoming a contributor!

Community

For help or questions, join our huge community on Slack!

Citations

Were excited to continue the strong legacy of open source software and have been inspired over the years by Caffe, Theano, Keras, PyTorch, torchbearer, ignite, sklearn and fast.ai. When/if a paper is written about this, well be happy to cite these frameworks and the corresponding authors.

License

Please observe the Apache 2.0 license that is listed in this repository. In addition the Lightning framework is Patent Pending.