posteriors


Nameposteriors JSON
Version 0.0.2 PyPI version JSON
download
home_pageNone
SummaryUncertainty quantification with PyTorch
upload_time2024-04-16 18:07:49
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseApache-2.0
keywords pytorch uncertainty
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <div align="center">
<img src="https://storage.googleapis.com/posteriors/logo_with_text.png" alt="logo"></img>
</div>

[**Installation**](#installation)
| [**Quickstart**](#quickstart)
| [**Methods**](#methods)
| [**Friends**](#friends)
| [**Contributing**](#contributing)
| [**Documentation**](https://normal-computing.github.io/posteriors/)

## What is `posteriors`?

General purpose python library for uncertainty quantification with [`PyTorch`](https://github.com/pytorch/pytorch).

- [x] **Composable**: Use with [`transformers`](https://huggingface.co/docs/transformers/en/index), [`lightning`](https://lightning.ai/), [`torchopt`](https://github.com/metaopt/torchopt), [`torch.distributions`](https://pytorch.org/docs/stable/distributions.html) and more!
- [x] **Extensible**: Add new methods! Add new models!
- [x] **Functional**: Easier to test, closer to mathematics!
- [x] **Scalable**: Big model? Big data? No problem!
- [x] **Swappable**: Swap between algorithms with ease!


## Installation

`posteriors` is available on [PyPI](https://pypi.org/project/posteriors/) and can be installed via `pip`:

```bash
pip install posteriors
```

## Quickstart

`posteriors` is functional first and aims to be easy to use and extend. Let's try it out
by training a simple model with variational inference:
```python
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
from torch import nn, utils, func
import torchopt
import posteriors

dataset = MNIST(root="./data", transform=ToTensor())
train_loader = utils.data.DataLoader(dataset, batch_size=32, shuffle=True)
num_data = len(dataset)

classifier = nn.Sequential(nn.Linear(28 * 28, 64), nn.ReLU(), nn.Linear(64, 10))
params = dict(classifier.named_parameters())


def log_posterior(params, batch):
    images, labels = batch
    images = images.view(images.size(0), -1)
    output = func.functional_call(classifier, params, images)
    log_post_val = (
        -nn.functional.cross_entropy(output, labels)
        + posteriors.diag_normal_log_prob(params) / num_data
    )
    return log_post_val, output


transform = posteriors.vi.diag.build(
    log_posterior, torchopt.adam(), temperature=1 / num_data
)  # Can swap out for any posteriors algorithm

state = transform.init(params)

for batch in train_loader:
    state = transform.update(state, batch)

```

Observe that `posteriors` recommends specifying `log_posterior` and `temperature` such that 
`log_posterior` remains on the same scale for different batch sizes. `posteriors` 
algorithms are designed to be stable as `temperature` goes to zero.

Further, the output of `log_posterior` is a tuple containing the evaluation 
(single-element Tensor) and an additional argument (TensorTree) containing any 
auxiliary information we'd like to retain from the model call, here the model predictions.
If you have no auxiliary information, you can simply return `torch.tensor([])` as
the second element. For more info see [`torch.func.grad`](https://pytorch.org/docs/stable/generated/torch.func.grad.html) 
(with `has_aux=True`) or the [documentation](https://normal-computing.github.io/posteriors/log_posteriors).

Check out the [tutorials](https://normal-computing.github.io/posteriors/tutorials) for more detailed usage!

## Methods

`posteriors` supports a variety of methods for uncertainty quantification, including:

- [**Extended Kalman filter**](posteriors/ekf/)
- [**Laplace approximation**](posteriors/laplace/)
- [**Stochastic gradient MCMC**](posteriors/sgmcmc/)
- [**Variational inference**](posteriors/vi/)

With full details available in the [API documentation](https://normal-computing.github.io/posteriors/api).

`posteriors` is designed to be easily extensible, if you're favorite method is not listed above,
[raise an issue]((https://github.com/normal-computing/posteriors/issues)) and we'll see what we can do!


## Friends

Interfaces seamlessly with:

- [`torch`](https://github.com/pytorch/pytorch) and in particular [`torch.func`](https://pytorch.org/docs/stable/func.html).
- [`torch.distributions`](https://pytorch.org/docs/stable/distributions.html) for distributions and sampling, (note that it's typically required to set `validate_args=False` to conform with the control flows in [`torch.func`](https://pytorch.org/docs/stable/func.html)).
- Functional and flexible torch optimizers from [`torchopt`](https://github.com/metaopt/torchopt).
- [`transformers`](https://github.com/huggingface/transformers) for pre-trained models.
- [`lightning`](https://github.com/Lightning-AI/lightning) for convenient training and logging, see [examples/lightning_autoencoder.py](examples/lightning_autoencoder.py).

The functional transform interface is strongly inspired by frameworks such as 
[`optax`](https://github.com/google-deepmind/optax) and [`blackjax`](https://github.com/blackjax-devs/blackjax).

As well as other UQ libraries [`fortuna`](https://github.com/awslabs/fortuna),
[`laplace`](https://github.com/aleximmer/Laplace), [`numpyro`](https://github.com/pyro-ppl/numpyro),
[`pymc`](https://github.com/pymc-devs/pymc) and [`uncertainty-baselines`](https://github.com/google/uncertainty-baselines).


## Contributing

You can report a bug or request a feature by [creating a new issue on GitHub](https://github.com/normal-computing/posteriors/issues).


If you want to contribute code, please check the [contributing guide](https://normal-computing.github.io/posteriors/contributing).

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "posteriors",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "pytorch, uncertainty",
    "author": null,
    "author_email": "Sam Duffield <sam@normalcomputing.ai>",
    "download_url": "https://files.pythonhosted.org/packages/17/71/7db36665bd9364360afc26c5d6d4cc09fbbe15f3d11db7fe5d8e4773efb4/posteriors-0.0.2.tar.gz",
    "platform": null,
    "description": "<div align=\"center\">\n<img src=\"https://storage.googleapis.com/posteriors/logo_with_text.png\" alt=\"logo\"></img>\n</div>\n\n[**Installation**](#installation)\n| [**Quickstart**](#quickstart)\n| [**Methods**](#methods)\n| [**Friends**](#friends)\n| [**Contributing**](#contributing)\n| [**Documentation**](https://normal-computing.github.io/posteriors/)\n\n## What is `posteriors`?\n\nGeneral purpose python library for uncertainty quantification with [`PyTorch`](https://github.com/pytorch/pytorch).\n\n- [x] **Composable**: Use with [`transformers`](https://huggingface.co/docs/transformers/en/index), [`lightning`](https://lightning.ai/), [`torchopt`](https://github.com/metaopt/torchopt), [`torch.distributions`](https://pytorch.org/docs/stable/distributions.html) and more!\n- [x] **Extensible**: Add new methods! Add new models!\n- [x] **Functional**: Easier to test, closer to mathematics!\n- [x] **Scalable**: Big model? Big data? No problem!\n- [x] **Swappable**: Swap between algorithms with ease!\n\n\n## Installation\n\n`posteriors` is available on [PyPI](https://pypi.org/project/posteriors/) and can be installed via `pip`:\n\n```bash\npip install posteriors\n```\n\n## Quickstart\n\n`posteriors` is functional first and aims to be easy to use and extend. Let's try it out\nby training a simple model with variational inference:\n```python\nfrom torchvision.datasets import MNIST\nfrom torchvision.transforms import ToTensor\nfrom torch import nn, utils, func\nimport torchopt\nimport posteriors\n\ndataset = MNIST(root=\"./data\", transform=ToTensor())\ntrain_loader = utils.data.DataLoader(dataset, batch_size=32, shuffle=True)\nnum_data = len(dataset)\n\nclassifier = nn.Sequential(nn.Linear(28 * 28, 64), nn.ReLU(), nn.Linear(64, 10))\nparams = dict(classifier.named_parameters())\n\n\ndef log_posterior(params, batch):\n    images, labels = batch\n    images = images.view(images.size(0), -1)\n    output = func.functional_call(classifier, params, images)\n    log_post_val = (\n        -nn.functional.cross_entropy(output, labels)\n        + posteriors.diag_normal_log_prob(params) / num_data\n    )\n    return log_post_val, output\n\n\ntransform = posteriors.vi.diag.build(\n    log_posterior, torchopt.adam(), temperature=1 / num_data\n)  # Can swap out for any posteriors algorithm\n\nstate = transform.init(params)\n\nfor batch in train_loader:\n    state = transform.update(state, batch)\n\n```\n\nObserve that `posteriors` recommends specifying `log_posterior` and `temperature` such that \n`log_posterior` remains on the same scale for different batch sizes. `posteriors` \nalgorithms are designed to be stable as `temperature` goes to zero.\n\nFurther, the output of `log_posterior` is a tuple containing the evaluation \n(single-element Tensor) and an additional argument (TensorTree) containing any \nauxiliary information we'd like to retain from the model call, here the model predictions.\nIf you have no auxiliary information, you can simply return `torch.tensor([])` as\nthe second element. For more info see [`torch.func.grad`](https://pytorch.org/docs/stable/generated/torch.func.grad.html) \n(with `has_aux=True`) or the [documentation](https://normal-computing.github.io/posteriors/log_posteriors).\n\nCheck out the [tutorials](https://normal-computing.github.io/posteriors/tutorials) for more detailed usage!\n\n## Methods\n\n`posteriors` supports a variety of methods for uncertainty quantification, including:\n\n- [**Extended Kalman filter**](posteriors/ekf/)\n- [**Laplace approximation**](posteriors/laplace/)\n- [**Stochastic gradient MCMC**](posteriors/sgmcmc/)\n- [**Variational inference**](posteriors/vi/)\n\nWith full details available in the [API documentation](https://normal-computing.github.io/posteriors/api).\n\n`posteriors` is designed to be easily extensible, if you're favorite method is not listed above,\n[raise an issue]((https://github.com/normal-computing/posteriors/issues)) and we'll see what we can do!\n\n\n## Friends\n\nInterfaces seamlessly with:\n\n- [`torch`](https://github.com/pytorch/pytorch) and in particular [`torch.func`](https://pytorch.org/docs/stable/func.html).\n- [`torch.distributions`](https://pytorch.org/docs/stable/distributions.html) for distributions and sampling, (note that it's typically required to set `validate_args=False` to conform with the control flows in [`torch.func`](https://pytorch.org/docs/stable/func.html)).\n- Functional and flexible torch optimizers from [`torchopt`](https://github.com/metaopt/torchopt).\n- [`transformers`](https://github.com/huggingface/transformers) for pre-trained models.\n- [`lightning`](https://github.com/Lightning-AI/lightning) for convenient training and logging, see [examples/lightning_autoencoder.py](examples/lightning_autoencoder.py).\n\nThe functional transform interface is strongly inspired by frameworks such as \n[`optax`](https://github.com/google-deepmind/optax) and [`blackjax`](https://github.com/blackjax-devs/blackjax).\n\nAs well as other UQ libraries [`fortuna`](https://github.com/awslabs/fortuna),\n[`laplace`](https://github.com/aleximmer/Laplace), [`numpyro`](https://github.com/pyro-ppl/numpyro),\n[`pymc`](https://github.com/pymc-devs/pymc) and [`uncertainty-baselines`](https://github.com/google/uncertainty-baselines).\n\n\n## Contributing\n\nYou can report a bug or request a feature by [creating a new issue on GitHub](https://github.com/normal-computing/posteriors/issues).\n\n\nIf you want to contribute code, please check the [contributing guide](https://normal-computing.github.io/posteriors/contributing).\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Uncertainty quantification with PyTorch",
    "version": "0.0.2",
    "project_urls": null,
    "split_keywords": [
        "pytorch",
        " uncertainty"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c469b6f38c2e9038b836f1ff311cb249f515565f9875c804e50e4e35a08516be",
                "md5": "fa9b2d73c681dc46ea8ca0b4c6edad3c",
                "sha256": "6dcf15e55af02889b1f4255cef858999b2f57ab8cead82c21cf13273c515f352"
            },
            "downloads": -1,
            "filename": "posteriors-0.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fa9b2d73c681dc46ea8ca0b4c6edad3c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 30032,
            "upload_time": "2024-04-16T18:07:47",
            "upload_time_iso_8601": "2024-04-16T18:07:47.398702Z",
            "url": "https://files.pythonhosted.org/packages/c4/69/b6f38c2e9038b836f1ff311cb249f515565f9875c804e50e4e35a08516be/posteriors-0.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "17717db36665bd9364360afc26c5d6d4cc09fbbe15f3d11db7fe5d8e4773efb4",
                "md5": "f62cee23fca73ae0115b62bdfe265c8a",
                "sha256": "b1f2752be71090f711bc2e3a51eb7f54510d28c3ae284dd200db1d62a55e8956"
            },
            "downloads": -1,
            "filename": "posteriors-0.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "f62cee23fca73ae0115b62bdfe265c8a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 28405,
            "upload_time": "2024-04-16T18:07:49",
            "upload_time_iso_8601": "2024-04-16T18:07:49.099860Z",
            "url": "https://files.pythonhosted.org/packages/17/71/7db36665bd9364360afc26c5d6d4cc09fbbe15f3d11db7fe5d8e4773efb4/posteriors-0.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-16 18:07:49",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "posteriors"
}
        
Elapsed time: 0.22718s